Showing posts with label Defensive Security. Show all posts
Showing posts with label Defensive Security. Show all posts

16/03/2021

Ethereum Smart Contract Source Code Review

 Introduction 

As Crypto currency technologies are becoming more and more prevalent, as the time is passing by, and banks will soon start adopting them. Ethereum blockchain and other complex blockchain programs are relatively new and highly experimental. Therefore, we should expect constant changes in the security landscape, as new bugs and security risks are discovered, and new best practices are developed [1].This article is going to discuss how to perform a source code review in Ethereum Smart Contracts (SCs) and what to look for. More specifically we are going to focus in specific keywords and how to analyse them. 

The points analysed are going to be:
  • User supplied input filtering, when interacting directly with SC
  • Interfacing with external SCs
  • Interfacing with DApp applications
  • SC formal verification
  • Wallet authentication in DApp

SC Programming Mindset

When designing an SC ecosystem (a group of SCs, constitutes an ecosystem) is it wise to have some specific concepts and security design principles in mind. SC programming requires a different engineering mindset than we may be used to. The cost of failure can be high, and change can be difficult, making it in some ways more similar to hardware programming or financial services programming than web or mobile development. 

When programming SCs we should be able to:
  • Design carefully roll outs
  • Keep contracts simple and modular
  • Be fully aware of blockchain properties
  • Prepare for failure

Key Security Concepts For SCs Systems


More specifically it is mandatory and the responsible thing to  is to take into consideration the following areas:
  • SC ecosystem monitoring e.g. monitor for unusual transactions etc.
  • SC ecosystem governance/admin e.g. by using proxy SC that follow best practices etc.
  • SC formal verification of all the SCs interacting with
  • SC modular/clean coding e.g. use comments and modular code etc. 
  • SC ecosystem code auditing by an external independent 3rd party
  • SC ecosystem system penetration testing by an external independent 3rd party  
Note: At this point we should point out that it is important that DApp smart contract interaction should also be reviewed.

SCs User Input Validation

Make sure you apply user input validation on a DApp and SC level. Remember that on-chain data are public and an adversary can interact with a SC directly, by simply visiting an Ethereum explorer in etherscan.io, the following screenshots demonstrate that.

Below we can see an example of a deployed contract:



Simple by clicking in the SC link we can interact with the contract:



Note:  Above we can see the upgrade function call and various other Admin functions. Of course is not that easy to interact with them.

It is also known that etherscan.io provides some experimental features to decompile the SC code:


 If we click the decompile code we get this screen below:


Below we can see how a DApp or wallet can interact with a SC:



There are five categories of Ethereum wallets that can interact with DApps:
  • Browser built-in (e.g. Opera, Brave etc)
  • Browser extension (e.g. MetaMask )
  • Mobile wallets (e.g. Trust, Walleth, Pillar etc.)
  • Account-based web wallets (e.g. Fortmatic, 3box etc.)
  • Hardware wallets (e.g. Ledger, Trezor etc.)
Then there is a larger category of wallets that cannot integrate with DApps include generic wallet apps that lack the functionality to integrate with smart contracts. Different wallets have a different user experience to connect. For example, with MetaMask you get a Connect pop up. With mobile wallets, you scan a QR code. So phishing attacks take a different for e.g. an attacker can spoof a QR code, through online free QR generators etc. When assessing a DApp the architecture is of paramount importance. A user with a Metamask plugin can use it to connect to the DApp. The DApp automatically will associate the interaction with the user public key to run various tasks. 

For a Web based DApp we can use traditional filtering methods. But for SCs using Solidity we can use assert and require are as convenience functions that check for conditions (e.g. a user supplies input and the mentioned functions check if the conditions are met). In cases when conditions are not met, they throw exceptions, that we help us handle the errors.

These are the cases when Solidity creates assert-type of exceptions when we [3]:
  • Invoke Solidity assert with an argument, showing false.
  • Invoke a zero-initialized variable of an internal function type.
  • Convert a large or negative value to enum.
  • We divide or modulo by zero.
  • We access an array in an index that is too big or negative.
The require Solidity function guarantees validity of conditions that cannot be detected before execution. It checks inputs, contract state variables and return values from calls to external contracts.

In the following cases, Solidity triggers a require-type of exception when [3]:
  • We call require with arguments that result in false.
  • A function called through a message does not end properly.
  • We create a contract with new keyword and the process does not end properly.
  • We target a codeless contract with an external function.
  • We contract gets Ether through a public getter function.
  • We .transfer() ends in failure.
Generally speaking when handling complex user input and run mathematical calculations it is mandatory to use external libraries from 3rd partyaudited code. A code project to look into would be SafeMath from OpenZeppelin. SafeMath is a wrapper over Solidity’s arithmetic operations with added overflow checks. Arithmetic operations in Solidity wrap on overflow. This can easily result in bugs, because programmers usually assume that an overflow raises an error, which is the standard behavior in high level programming languages. SafeMath restores this intuition by reverting the transaction when an operation overflows.

SC External Calls


Calls to untrusted 3rd party Smart Contracts can introduce several security issues. External calls may execute malicious code in that contract or any other contract that it depends upon. As such, every external call should be treated as a potential security risk.  Solidity's call function is a low-level interface for sending a message to an SC. It returns false if the subcall encounters an exception, otherwise it returns true. There is no notion of a legal call, if it compiles, it's valid Solidity.


Especially when the return value of a message call is not checked, execution will resume even if the called contract throws an exception. If the call fails accidentally or an attacker forces the call to fail, this may cause unexpected behavior in the subsequent program logic. Always make sure to handle the possibility that the call will fail by checking the return value of that function [4].

Reentrancy (Recursive Call Attack)

One of the major risks of calling external contracts is that they can take over the control flow. In the reentrancy attack (a.k.a. recursive call attack) calling external contracts can take over the control flow, and make changes to your data that the calling function wasn’t expecting. A reentrancy attack occurs when the attacker drains funds from the target contract by recursively calling the target’s withdraw function [4].

Below we can see a schematic representation:




Note: For more information on this type of attack please see [4]

SC Denial of Service Attacks

Each block has an upper bound on the amount of gas that can be spent, and thus the amount computation that can be done. This is the Block Gas Limit. If the gas spent exceeds this limit, the transaction will fail. 

This leads to a couple possible Denial of Service vectors:
  • Gas Limit DoS on a Contract via Unbounded Operations
  • Gas Limit DoS on the Network via Block Stuffing
Note: For more information on DoS attacks see consensys.github.io

Use Of Delegatecall/Callcode and Libraries

According the Solidity docs [7], there exists a special variant of a message call, named delegatecall which is identical to a message call apart from the fact that the code at the target address is executed in the context of the calling contract and msg.sender and msg.value do not change their values.

This means that a contract can dynamically load code from a different address at runtime. Storage, current address and balance still refer to the calling contract, only the code is taken from the called address. This makes it possible to implement the “library” feature in Solidity: Reusable library code that can be applied to a contract’s storage, e.g. in order to implement a complex data structure.

Improper security use of this function was the cause for the Parity Multisig Wallet hack in 2017. This function is very useful for granting our contract the ability to make calls on other contracts, as if that code were a part of our own contract. However, using delegatecall() causes all public functions from the called contract to be callable by anyone. Because this behavior was not recognized when Parity built its own custom libraries. 

Epilogue 

Writing secure smart code is a lot of work and can be very complex.

References:


28/05/2016

Hacker’s Elusive Thoughts The Web

Introduction

The reason for this blog post is to advertise my book. First of all I would like to thank all the readers of my blog for the support and feedback on making my articles better. After 12+ years in the penetration testing industry, the time has come for me to publish my book and tranfer my knowledge to all the intersted people that like hacking and want to learn as much as possible. Also at the end of the blog you will find a sample chapter.



About The Author

Gerasimos is a security consultant holding a MSc in Information Security, a CREST (CRT), a CISSP, an ITILv3, a GIAC GPEN and a GIAC GAWPT accreditation. Working alongside diverse and highly skilled teams Gerasi- mos has been involved in countless comprehensive security tests and web application secure development engagements for global web applications and network platforms, counting more than 14 years in the web application and application security architecture.

Gerasimos further progressing in his career has participated in vari- ous projects providing leadership and accountability for assigned IT security projects, security assurance activities, technical security reviews and assess- ments and conducted validations and technical security testing against pre- production systems as part of overall validations.

Where From You Can Buy The Book

This book can be bought from leanbup. Leanpub is a unique publishing platform that provides a way in the world to write, publish and sell in-progress and completed ebooks. Anyone can sign up for free and use Leanpub's writing and publishing tools to produce a book and put it up for sale in our bookstore with one click. Authors are paid a royalty of 90% minus 50 cents per transaction with no constraints: they own their work and can sell it elsewhere for any price.

Authors and publishers can also upload books they have created using their own preferred book production processes and then sell them in the Leanpub bookstore, taking advantage of our high royalty rates and our in-progress publishing features.

Please for more information about bying the book see link: https://leanpub.com/hackerselusivethoughtstheweb

Why I Wrote This Book

I wrote this book to share my knowledge with anyone that wants to learn about Web Application security, understand how to formalize a Web Appli- cation penetration test and build a Web Application penetration test team.

The main goal of the book is to: 

Brainstorm you with some interesting ideas and help you build a com- prehensive penetration testing framework, which you can easily use for your specific needs. Help you understand why you need to write your own tools. Gain a better understanding of some not so well documented attack techniques.
The main goal of the book is not to:
 
Provide you with a tool kit to perform Web Application penetration tests. Provide you with complex attacks that you will not be able to under- stand. Provide you with up to date information on latest attacks.

Who This Book Is For 


This book is written to help hacking enthusiasts to become better and stan- dardize their hacking methodologies and techniques so as to know clearly what to do and why when testing Web Applications. This book will also be very helpful to the following professionals:

1. Web Application developers.
2. Professional Penetration Testers.
3. Web Application Security Analysts.
4. Information Security professionals.
5. Hiring Application Security Managers.
6. Managing Information Security Consultants.

How This Book Is Organised  

Almost all chapters are written in such a way so as to not require you to read the chapters sequentially, in order to understand the concepts presented, although it is recommended to do so. The following section is going to give you an overview of the book:

Chapter 1: Formalising Web Application Penetration Tests -
This chapter is a gentle introduction to the world of penetration testing, and attempt to give a realistic view on the current landscape. More specifically it attempt to provide you information on how to compose a Pen- etration Testing team and make the team as ecient as possible and why writing tools and choosing the proper tools is important.

Chapter 2: Scanning With Class -

The second chapter focuses on helping you understand the dierence between automated and manual scanning from the tester’s perspective. It will show you how to write custom scanning tools with the use of Python. This part of the book also contains Python chunks of code demonstrating on how to write tools and design your own scanner.

Chapter 3: Payload Management -

This chapter focuses on explaining two things a) What is a Web payload from security perspective, b) Why is it important to obfuscated your payloads.

Chapter 4: Infiltrating Corporate Networks Using XXE -

This chapter focuses on explaining how to exploit and elevate an External Entity (XXE) Injection vulnerability. The main purpose of this chapter is not to show you how to exploit an XXE vulnerability, but to broaden your mind on how you can combine multiple vulnerabilities together to infiltrate your target using an XXE vulnerability as an example.

Chapter 5: Phishing Like A Boss -

This chapter focuses on explaining how to perform phishing attacks using social engineering and Web vulnerabilities. The main purpose of this chapter is to help you broaden your mind on how to combine multiple security issues, to perform phishing attacks.

Chapter 6: SQL Injection Fuzzing For Fun And Profit -

This chapter focuses on explaining how to perform and automate SQL injection attacks through obfuscation using Python. It also explains why SQL injection attacks happen and what is the risk of having them in your web applications.


Sample Chapter Download
From the following link you will be able to download a sample chapter from my book:

Sample Book Download
















16/02/2015

Apache mod_negotiation or MultiViews filename bruteforcing

Filename Brute-forcing through MultiViews Vulnerability


This is a small post about a way to easily get backup files on Apache web servers with Multiviews option enabled. There is no much information in Multiviews (an Apache feature) and some Web Application scanners report this as Apache mod_negotiation filename brute-forcing rather than Multiviews option enabled. Apache HTTPD supports content negotiation as described in the HTTP/1.1 specification (see http://www.w3.org/Protocols/rfc2616/rfc2616.html). It can choose the best representation of a resource based on the browser-supplied preferences for media type, languages, character set and encoding. It also implements a couple of features to give more intelligent handling of requests from browsers that send incomplete negotiation information.

What are resources

A resource is a conceptual entity identified by a URI (RFC 2396). An HTTP server like Apache HTTP Server provides access to representations of the resource(s) within its namespace, with each representation in the form of a sequence of bytes with a defined media type, character set, encoding, etc. Each resource may be associated with zero, one, or more than one representation at any given time. If multiple representations are available, the resource is referred to as negotiable and each of its representations is termed a variant. The ways in which the variants for a negotiable resource vary are called the dimensions of negotiation.

Negotiation in httpd

In order to negotiate a resource, the server needs to be given information about each of the variants. This is done in one of two ways:
  • Using a type map (i.e., a *.var file) which names the files containing the variants explicitly, or
  • Using a 'MultiViews' search, where the server does an implicit filename pattern match and chooses from among the results.
Using MultiViews to brute-force files

MultiViews is a per-directory option, meaning it can be set with an Options directive within a <Directory>, <Location> or <Files> section in httpd.conf, or (if AllowOverride is properly set) in .htaccess files.

The effect of MultiViews is as follows: if the server receives a request for /some/dir/foo, if /some/dir has MultiViews enabled, and /some/dir/foo does not exist, then the server reads the directory looking for files named foo.*, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements.

MultiViews is an Apache option which acts with the following rules:

"if you request from the server a file e.g. /some/dir/foo and does not exist, then the server reads the directory looking for files named foo.*, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements."

Impact

An attacker can use this functionality to aid in finding hidden file processes on the directory and potentially gather further sensitive information through the mod_negotiation module. mod_negotiation is an Apache module responsible for selecting the document that best matches the clients capabilities, from one of several available documents. If the client provides an invalid Accept header, the server will respond with a 406 Not Acceptable error containing a pseudo directory listing. This behavior can help an attacker to learn more about his target, for example, generate a list of base names, generate a list of interesting extensions, and look for backup files and so on.

Proof Of Concept

Example 1:

Request:

GET /mymanual/de/glossarry.html HTTP/1.1
Host: xxx.xxx.xxx.xxx
Accept: application/xxx; q=1.0
Negotiate:*
User-Agent: xxx
Connection: close
Referer: http://xxx.xxx.xxx.xxx/test/se/
Cookie: LangID=2; PHPSESSID=xxxx


Response:

HTTP/1.1 300 Multiple Choices
Date: Tue, 16 Sep 2014 12:56:46 GMT
Server: Apache/2.2.22 (Linux/SUSE)
Alternates: {"glossary.html.de" 1 {type text/html} {charset iso-8859-1} {language de} {length 32714}}, {"glossary.html.en" 1 {type text/html} {charset iso-8859-1} {language en} {length 27855}}, {"glossary.html.es" 1 {type text/html} {charset iso-8859-1} {language es} {length 23586}}, {"glossary.html.fr" 1 {type text/html} {charset iso-8859-1} {language fr} {length 30561}}, {"glossary.html.ja.utf8" 1 {type text/html} {charset utf-8} {language ja} {length 30880}}, {"glossary.html.ko.euc-kr" 1 {type text/html} {charset euc-kr} {language ko} {length 19474}}, {"glossary.html.tr.utf8" 1 {type text/html} {charset utf-8} {language tr} {length 30911}}
Vary: negotiate,accept-language,accept-charset
TCN: list
Content-Length: 1039
Connection: close
Content-Type: text/html; charset=iso-8859-1
…[omitted]…
Note: In the first example we request for a specific file, the glossary.html and get the response displayed above.

Example 2:



Request:

GET /ba* HTTP/1.1
Host:xxx
Accept: application/whatever; q=1.0
Accept-charset: iso-8859-9
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0
Connection: close
Referer: http://xxx.xxx.xxx.xxx/manual/de/
Cookie: LangID=2; PHPSESSID=xxxx





Response:

HTTP/1.1 404 Not Found
Date: Tue, 16 Sep 2014 13:33:18 GMT
Server: Apache/2.2.22 (Linux/SUSE)
Alternates: {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-2} {language cs} {length 745}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language de} {length 766}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language en} {length 611}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {language es} {length 699}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language fr} {length 789}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language ga} {length 813}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language it} {length 692}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-2022-jp} {language ja} {length 749}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset euc-kr} {language ko} {length 703}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language nl} {length 688}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-2} {language pl} {length 707}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language pt-br} {length 753}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language pt} {length 272}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language ro} {length 689}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-5} {language sr} {length 716}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-1} {language sv} {length 722}}, {"HTTP_NOT_FOUND.html.var" 1 {type text/html} {charset iso-8859-9} {language tr} {length 755}}
Vary: accept-language,accept-charset
Content-Length: 409
Connection: close
Content-Type: text/html; charset=iso-8859-1
…[omitted]…


Note: In this example we request a file name using wild card characters e.g. *. More specifically .

Remediation 

Disable the MultiViews directive from Apache's configuration file and restart Apache. You can disable MultiViews by creating a .htaccess file containing the following line:

Options -Multiviews

References:
  1. http://www.wisec.it/sectou.php?id=4698ebdc59d15
  2. http://www.acunetix.com/vulnerabilities/apache-mod_negotiation-fi/
  3. http://www.securityfocus.com/bid/3009

17/04/2014

PHP Source Code Chunks of Insanity (Delete Post Pages) Part 4

Intro 

This post is going to talk about source code reviewing PHP and demonstrate how a relatively small chunk of code can cause you lots of problems.

The Code

In this article we are going to analyze the code displayed below. The code displayed below might seem innocent for some , but obviously is not. We are going to assume that is used by some web site to delete posts from the logged in users securely.
 <?php  
 require_once 'common.php';   
 validatemySession();   
 mydatabaseConnect();  
  $username = $_SESSION['username'];// Insecure source  
 $username = stripslashes($username);// Improper filtering  
 $username = mysql_real_escape_string($username);//Flawed function  
 // Delete the post that matches the postId ensuring that it was created by this user  
  $queryDelete = "DELETE FROM posts WHERE PostId = " . (int) $_GET['postId']. " AND Username = '$username'";  
  if (mysql_query($queryDelete))// Bad validation coding {  
       header('Location: myPosts.php'); }  
  else {  
      echo "An error has occurred.";   
      }  
 ?>  

If you look carefully the code you will se that the code is vulnerable to the following issue: SQL Injection!!
    
Think this is not accurate , think better.

The SQL Injection

An adversary in order to exploit this vulnerability would not have to script custom tools, would only have to have good knowledge of SQL injections methodologies and exposure to PHP coding.

Vulnerable Code:

1st Code Chunk 
 $username = $_SESSION['username'];// Insecure source  
 $username = stripslashes($username);// Improper filtering 
 $username = mysql_real_escape_string($username);//Flawed function  
2nd Code Chunk: 
 $queryDelete = "DELETE FROM posts WHERE PostId = " . (int) $_GET['postId']. " AND Username = '$username'";  
3rd Code Chunk:    
 if (mysql_query($queryDelete))  

The mysql_real_escape_string function is based in the black list mentality. What it does is that escapes special characters in the un-­‐escaped string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query. More specifically mysql_real_escape_string calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters:

1. \x00 
2. \n
3. \r
4. \
5. '
6. “

7. \x1a.

Due to this odd behavior characters such as the % and SQL keywords are not being affected, so queries that have the form of e.g. SELECT BENCHMARK(50,MD5(CHAR(118))) would be executed normally. A realistic scenario would be to use a query such as the one below:

Step1: SQL Payload that would cause the post to delete without the postId be known. 
 LIKE %’s’  

Note1: At this point we assume that the attacker knows the format of the username e.g. its user plus a two-­‐digit number. 

Step2: SQL Payload mutated in order to bypass the filters.
 LIKE CHAR(37, 8217, 115, 8217)  

Note2: Further expanding on the attack if the Web App does not have a standard format for the usernames then the adversary can brute-­‐force the username first latter e.g. try out all English letters e.g. LIKE %’a’, LIKE %’b’, LIKE %’c’ ... etc. and eventually execute the query with a valid first username letter. Translating that to an obfuscated SQL Payload would be LIKE CHAR(39, 97, 37, 39), LIKE CHAR(39, 98, 37, 39) etc.

Note3: The mysql_real_escape_string function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Alternatives to this function include: mysqli_real_escape_string and PDO::quote. The mysql_query() function sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier. In this specific code example the query returns true if a record is found (any record). This obscure behavior introduces the vulnerability combined of course with the above code. The function used in the mysql_query statement should return a record set only if the correct record set is returned and not just any match.

Note4: This extension is deprecated as of PHP 5.5.0.

Remedial Code:

Provide Server Side filters filter for remediating the vulnerability. Make use of strongly typed parameterized queries (using the bind_param).
 // Using prepared Statements.  
 if ($stmt = $mysqli-­‐>prepare("DELETE FROM posts WHERE PostId = ? AND Username = ? LIMIT 1"))  
 {  
 $stmt-­‐>bind_param('s', $ username); // Bind "$ username" to parameter. 
 $stmt-­‐>execute(); // Execute the prepared statement.  
 ...  
 }