Smart Contract Exploitation and Hacking Course Announcement
What Is this:
For those who have been hitting me up on twitter and YouTube for more blockchain smart contract exploitation content this blog is for you. I have posted a video below explaining what this is and included a course outline of the content we are providing free for everyone. I was actually told recently that I am crazy for giving out this level of detailed content and training for free.. However, I believe in the original hacker ethic code from long ago, that information should be freely available for everyone!! In this frame of mind, the only pay for content will be if you wish to go the extra mile. For the person who wants to prove to themselves or others that they learned something via a certification package with detailed exam prep targets and guides, followed by a final exam CTF and reporting write-up.
So I hope you enjoy this content. The content and walk through labs will be all free. This content will be posted regularly over the next few months 90% of it is already written and ready to go.
We will start off with the differences between Solidity and other languages and do a quick coding overview before we start hacking. This way everyone is on the same page when we start looking at coding examples of vulnerable targets or reviewing case study code. Then we will cover a wide range of typical issues that effect decentralized applications(DApps) and smart contracts on the Ethereum blockchain. How to spot them and exploit them with full walk-through style learning. Subjects we have already released (Re-Entrancy, Integer Attacks, Authorization) have been updated with new code, new examples, and case studies etc. Some of the learning content will be the same but with a lot of newly added content. And in the case of Authorization completely re-written and expanded on.
Basically this course was created to get the information out there in a clear concise way. Because when I started researching blockchain hacking all I found was a paragraph here and there on something that was overly technical or completely theoretical. I couldn't find any clear concise learning or examples. This drove me nuts trying to figure everything out, until I gave up and just coded my own vulnerabilities and hacked them. So hopefully this fills the knowledge gap to offer a clear and concise, Zero Fluff resource to those on the same path.
Pre- Requisites:
This is more of a intermediate / advanced course with a white box code approach to bug hunting and a dynamic approach to application hacking and exploiting targets, with that said you will need the following pre-requisites:
Ability to code in some language and understanding of coding concepts.
Application hacking or development background with firm understanding of vulnerabilities
Contact Info:
As this is free, I only ask that you provide constructive feedback as we are creating other more advanced hacking courses on random subjects we are interested in. Most of which will be free. And feedback helps us not do things which are not useful and integrate new ideas where they make sense.
In part 1 and 2 we covered re-entrancy and authorization attack scenarios within the Ethereum smart contract environment. In this blog we will cover integer attacks against blockchain decentralized applications (DAPs) coded in Solidity.
Integer Attack Explanation:
An integer overflow and underflow happens when a check on a value is used with an unsigned integer, which either adds or subtracts beyond the limits the variable can hold. If you remember back to your computer science class each variable type can hold up to a certain value length. You will also remember some variable types only hold positive numbers while others hold positive and negative numbers.
If you go outside of the constraints of the number type you are using it may handle things in different ways such as an error condition or perhaps cutting the number off at the maximum or minimum value.
In the Solidity language for Ethereum when we reach values past what our variable can hold it in turn wraps back around to a number it understands. So for example if we have a variable that can only hold a 2 digit number when we hit 99 and go past it, we will end up with 00. Inversely if we had 00 and we subtracted 1 we would end up with 99.
Normally in your math class the following would be true:
99 + 1 = 100 00 - 1 = -1
In solidity with unsigned numbers the following is true: 99 + 1 = 00 00 - 1 = 99
So the issue lies with the assumption that a number will fail or provide a correct value in mathematical calculations when indeed it does not. So comparing a variable with a require statement is not sufficiently accurate after performing a mathematical operation that does not check for safe values.
That comparison may very well be comparing the output of an over/under flowed value and be completely meaningless. The Require statement may return true, but not based on the actual intended mathematical value. This in turn will lead to an action performed which is beneficial to the attacker for example checking a low value required for a funds validation but then receiving a very high value sent to the attacker after the initial check. Lets go through a few examples.
Simple Example:
Lets say we have the following Require check as an example: require(balance - withdraw_amount > 0) ;
Now the above statement seems reasonable, if the users balance minus the withdrawal amount is less than 0 then obviously they don’t have the money for this transaction correct?
This transaction should fail and produce an error because not enough funds are held within the account for the transaction. But what if we have 5 dollars and we withdraw 6 dollars using the scenario above where we can hold 2 digits with an unsigned integer?
Let's do some math. 5 - 6 = 99
Last I checked 99 is greater than 0 which poses an interesting problem. Our check says we are good to go, but our account balance isn't large enough to cover the transaction. The check will pass because the underflow creates the wrong value which is greater than 0 and more funds then the user has will be transferred out of the account.
Because the following math returns true: require(99 > 0)
Withdraw Function Vulnerable to an UnderFlow:
The below example snippet of code illustrates a withdraw function with an underflow vulnerability:
In this example the require line checks that the balance is greater then 0 after subtracting the _amount but if the _amount is greater than the balance it will underflow to a value above 0 even though it should fail with a negative number as its true value.
require(balances[msg.sender] - _amount > 0);
It will then send the value of the _amount variable to the recipient without any further checks:
msg.sender.transfer(_amount);
Followed by possibly increasing the value of the senders account with an underflow condition even though it should have been reduced:
balances[msg.sender] -= _amount;
Depending how the Require check and transfer functions are coded the attacker may not lose any funds at all but be able to transfer out large sums of money to other accounts under his control simply by underflowing the require statements which checks the account balance before transferring funds each time.
Transfer Function Vulnerable to a Batch Overflow:
Overflow conditions often happen in situations where you are sending a batched amount of values to recipients. If you are doing an airdrop and have 200 users who are each receiving a large sum of tokens but you check the total sum of all users tokens against the total funds it may trigger an overflow. The logic would compare a smaller value to the total tokens and think you have enough to cover the transaction for example if your integer can only hold 5 digits in length or 00,000 what would happen in the below scenario?
You have 10,000 tokens in your account
You are sending 200 users 499 tokens each
Your total sent is 200*499 or 99,800
The above scenario would fail as it should since we have 10,000 tokens and want to send a total of 99,800. But what if we send 500 tokens each? Lets do some more math and see how that changes the outcome.
You have 10,000 tokens in your account
You are sending 200 users 500 tokens each
Your total sent is 200*500 or 100,000
New total is actually 0
This new scenario produces a total that is actually 0 even though each users amount is 500 tokens which may cause issues if a require statement is not handled with safe functions which stop an overflow of a require statement.
Lets take our new numbers and plug them into the below code and see what happens:
1: The total variable is 100,000 which becomes 0 due to the 5 digit limit overflow when a 6th digit is hit at 99,999 + 1 = 0. So total now becomes 0.
2: This line checks if the users balance is high enough to cover the total value to be sent which in this case is 0 so 10,000 is more then enough to cover a 0 total and this check passes due to the overflow.
3: This line deducts the total from the senders balance which does nothing since the total of 10,000 - 0 is 10,000. The sender has lost no funds.
4-5: This loop iterates over the 200 users who each get 500 tokens and updates the balances of each user individually using the real value of 500 as this does not trigger an overflow condition. Thus sending out 100,000 tokens without reducing the senders balance or triggering an error due to lack of funds. Essentially creating tokens out of thin air.
In this scenario the user retained all of their tokens but was able to distribute 100k tokens across 200 users regardless if they had the proper funds to do so.
Lab Follow Along Time:
We went through what might have been an overwhelming amount of concepts in this chapter regarding over/underflow scenarios now lets do an example lab in the video below to illustrate this point and get a little hands on experience reviewing, writing and exploiting smart contracts. Also note in the blockchain youtube playlist we cover the same concepts from above if you need to hear them rather then read them.
For this lab we will use the Remix browser environment with the current solidity version as of this writing 0.5.12. You can easily adjust the compiler version on Remix to this version as versions update and change frequently. https://remix.ethereum.org/
Below is a video going through coding your own vulnerable smart contract, the video following that goes through exploiting the code you create and the videos prior to that cover the concepts we covered above:
This next video walks through exploiting the code above, preferably hand coded by you into the remix environment. As the best way to learn is to code it yourself and understand each piece:
Conclusion:
We covered a lot of information at this point and the video series playlist associated with this blog series has additional information and walk throughs. Also other videos as always will be added to this playlist including fixing integer overflows in the code and attacking an actual live Decentralized Blockchain Application. So check out those videos as they are dropped and the current ones, sit back and watch and re-enforce the concepts you learned in this blog and in the previous lab. This is an example from a full set of labs as part of a more comprehensive exploitation course we have been working on.
Bypassing Blockchain
Authorization via Unsecured Functions
Note: Since the
first part of this series I have also uploaded some further videos on
remediation of reentrancy and dealing with compiler versions when working with
this hacking blockchain series.Head to
the console cowboys YouTube account to check those out.Haha as mentioned before I always forget to
post blogs when I get excited making videos and just move on to my next
project… So make sure to subscribe to the YouTube if you are waiting for any
continuation of a video series.. It may show up there way before here.
Note 2: You WILL run into issues when dealing with Ethereum hacking, and you will have to google them as versions and functionality changes often... Be cognizant of versions used hopefully you will not run into to many hard to fix issues.
In the second part
of this lab series we are going to take a look at privacy issues on the blockchain which can
result in a vulnerably a traditional system maynot face. Since typically blockchain projects are open source and also sometimes viewable within blockchain explorers but traditional application business logic is not usually available to us. With traditional applications we might not find these issues due to lack of knowledge of internal functionality or
inability to read private values on a remote server side script.After we review some issues we are going to exploit an authorization issues by writing web3.js code to directly bypass vertical
authorization restrictions.
Blockchain projects
are usually open source projects which allow you to browse their code and see
what's going on under the hood.This is
fantastic for a lot of reasons but a developer can run into trouble with this
if bad business logic decisions are deployed to the immutable blockchain.In the first part of this series I mentioned
that all uploaded code on the blockchain is immutable. Meaning that if you find
a vulnerability it cannot be patched. So let's think about things that can go
wrong..
A few things that
can go wrong:
Randomization
functions that use values we can predict if we know the algorithm
Hard-coded values
such as passwords and private variables you can't change.
Publicly called
functions which offer hidden functionality
Race conditions
based on how requirements are calculated
Since this will be
rather technical, require some setup and a lot of moving parts we will follow
this blog via the video series below posting videos for relevant sections with
a brief description of each.I posted these
a little bit ago but have not gotten a chance to post the blog associated with
it.Also note this series is turning
into a full lab based blockchain exploitation course so keep a lookout for
that.
In this first video
you will see how data about your project is readily available on the blockchain
in multiple formats for example:
ABI data that allows
you to interact with methods.
Actual application
code.
Byte code and
assembly code.
Contract addresses
and other data.
Lab Video Part 1: Blockchain OSINT:
Once you have the
data you need to interact with a contract on the blockchain via some OSINT how
do you actually interface with it? That’s the question we are going to answer
in this second video. We will take the ABI contract array and use it to interact
with methods on the blockchain via Web3.js and then show how this correlates to
its usage in an HTML file
Lab Video Part 2: Connecting to a Smart Contract:
Time to Exploit an Application:
Exploit lab time, I
created an vulnerable application you can use to follow along in the next
video. Lab files can be downloaded from the same location as the last blog
located below. Grab the AuthorizationLab.zip file:
Ok so you can see
what's running on the blockchain, you can connect to it, now what?Now we need to find a vulnerability and show
how to exploit it. Since we are talking about privacy in this blog and using it
to bypass issues. Lets take a look at a simple authorization bypass we can
exploit by viewing an authorization coding error and taking advantage of it to
bypass restrictions set in the Smart Contract.You will also learn how to setup a local blockchain for testing purposes
and you can download a hackable application to follow along with the exercises
in the video..
Lab Video Part 3: Finding and hacking a Smart Contract Authorization Issue:
Summary:
In this part of
the series you learned a lot, you learned how to transfer your OSINT skills to
the blockchain. Leverage the information found to connect to that Smart
Contract. You also learned how to interact with methods and search for issues
that you can exploit. Finally you used your browsers developer console as a
means to attack the blockchain application for privilege escalation.
I realized the other day I posted Part 2 of this series to my youtube awhile ago but not blogger so this one will be quick and mostly via video walkthrough. I often post random followup videos which may never arrive on this blog. So if you’re waiting on something specific I mentioned or the next part to a series its always a good idea to subscribe to the YouTube. This is almost always true if there is video associated with the post.
In the last blog we went over using virtual CAN devices to interact with a virtual car simulators of a CAN network This was awesome because it allowed us to learn how to interact with he underlying CAN network without fear of hacking around on an expensive automobile. But now it’s time to put on your big boy pants and create a real CAN interface with hardware and plug your hardware device into your ODB2 port.
The video I created below will show you where to plug your device in, how to configure it and how to take the information you learned while hacking around on the virtual car from part1 and apply it directly to a real car.
Video Walk Through Using Hardware on a Real Car
As a reference here are the two device options I used in the video and the needed cable:
Hardware Used:
Get OBD2 Cable:
https://amzn.to/2QSmtyL
Get CANtact:
https://amzn.to/2xCqhMt
Get USB2CAN:
https://shop.8devices.com/usb2can
Creating Network Interfaces:
As a reference here are the commands from the video for creating a CAN network interface:
USB2Can Setup:
The following command will bring up your can interface and you should see the device light color change:
sudo ip link set can0 up type can bitrate 125000
Contact Setup:
Set your jumpers on 3,5 and 7 as seen in the picture in the video
Sudo slcand -o -s6 /dev/ttyACM can0 <— whatever device you see in your DMESG output
Ifconfig can0 up
Summary:
That should get you started connecting to physical cars and hacking around. I was also doing a bit of python coding over these interfaces to perform actions and sniff traffic. I might post that if anyone is interested. Mostly I have been hacking around on blockchain stuff and creating full course content recently so keep a look out for that in the future.
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
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 create
a 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
auser. 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 lettingthe 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) {
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.
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.
A step by step lab based mini course on analyzing your car network
I wanted to learn about hacking cars. As usual I searched around the internet and didn’t find any comprehensive resources on how to do this, just bits and pieces of the same info over and over which is frustrating. I am not a car hacking expert, I just like to hack stuff. This mini course will run in a fully simulated lab environment available from open garages, which means in 5 minutes from now you can follow along and hack cars without ever bricking your girlfriends car. Since you obviously wouldn’t attack your own Lambo, totally use your girlfriends Prius.
Below are the topics covered in this blogseries so you can decide if you want to read further:
Whats covered in this car hacking mini course:
Setting up Virtual Environments for testing
Sniffing CAN Traffic
Parsing CAN Traffic
Reverse Engineering CAN IDs
Denial of service attacks
Replaying/Injecting Traffic
Coding your own CAN Socket Tools in python
Targeted attacks against your cars components
Transitioning this to attacking a real car with hardware
The first thing we are going to do before we get into any car hacking specifics such as “WTF is CAN?”, is get your lab up and running. We are going to run a simple simulated CAN Bus network which controls various features of your simulated car. Its better to learn by doing then sit here and recite a bunch of car network lingo at you and hope you remember it.
I also don’t want you to buy a bunch of hardware and jack into your real car right away. Instead there are options that can get you started hacking cars RIGHT NOW by following along with this tutorial. This will also serve to take away the fear of hacking your actual car by understanding what your doing first.
Video Playlist:
Setting up your Lab:
First things first, set yourself up with an Ubuntu VMware install, and load it up. Optionally you could use a Kali Iinux VM, however, that thing drives me nuts with copy paste issues and I think Kayak was giving me install problems. So support is on you if you would like to use Kali. However, I do know Kali will work fine with OpenGarages virtual car.. So feel free to use it for that if you have it handy and want to get started right away.
Install PreReq Libraries:
Once you load this up you are going to want to install CAN utilities and pre-requisite libraries. This is really easy to do with the following Apt-get commands:
Once this is done we can startup the simulator by changing directories to the downloaded repo and running the following 2 commands, which will setup a virtual CAN interface and a simulator GUI Cluster:
Run the setup Script to get the vcan0 interface up:
root@kali:~/ICSim# ./setup_vcan.sh
root@kali:~/ICSim# ./icsim vcan0
On a new terminal tab we will open up our simulators controller with the following command,
root@kali:~/ICSim#./controls vcan0
Note: that the controller must be the in-focus GUI screen to send keyboard commands to the simulator.
How to Use the Simulator:
The simulator has a speedometer with Right and Left turn signals, doors etc. Below are the list of commands to control the simulator when the Control panel is in focus. Give them each a try and note the changes to the simulator.
Up and Down keys control the gauges clusters speedometer
Left and Right keys Control the Blinkers
Right Shift + X, A or B open doors
Left Shift + X, A or be Close doors
Try a few of the above commands for example Right Shift +X and you will see the interface change like so, notice the open door graphic:
Awesome, thanks to OpenGarages you now you have your very own car to hack
Notice in the setup commands above we used a VCan0 interface. Run Ifconfig and you will now see that you indeed have a new network interface that speaks to the CAN network over VCan0.
ficti0n@ubuntu:~/Desktop/ICSim$ ifconfig vcan0
vcan0 Link encap:UNSPECHWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
Car networks run on a variety of protocols most prevalent being CAN. You can think of a CAN Bus like an old school networking hub where everyone can see everyone elses traffic. This is true to some extent although you may not see all of the cars traffic if its not connected to that particular bus your plugged into. You can think of CAN traffic kind of like UDP in that its send and forget, the main difference being parts of the CAN bus network don't actually have addresses and everything runs off arbitration IDs and priorities. Thats enough background to get you doing rather then reading.
With a little knowledge out of the way lets check if we can see our CAN traffic from our virtual car via the CanDump utility, which you installed as part of CanUtils package above. Using the following command on the vcan0 interface our simulator uses you can view a stream of traffic:
ficti0n@ubuntu:~/Desktop/ICSim$ candump vcan0
Above we can see a bunch of CAN frames, and if we perform actions on the vehicle we will see changes to data values in the CanDump output.However this may happen very fast, and we may not be able to see if for example we unlocked our simulators door. This is because things are changing constantly in the cars IDLE state. One single value changing may not stand out enough for us to take notice or may scroll so fast we cant see it.
Capture and Replay CAN Actions:
One option would be to perform an action and replay it, we should see the actions happen again in the replay if the traffic for the action we recorded is on the same bus network our device is plugged into. There are loads of networks within a car and its not guaranteed our network tap for example an OBD2 port plugin is connected to the same network as door we opened.Or the door may not be connected to the network at all depending on your car and its age or how its configured.
Replaying dumps with CanPlayer:
Another useful tool included with CanUtils package is CanPlayer for replaying traffic. If the functionality we are trying to capture is on the same Bus as the adaptor plugged into the car, or in this case our Virtual CAN interface, we can use CanDump to save traffic to a file. We then use CanPlayer to replay the traffic on the network. For example lets run CanDump and open a door and then replay the functionality with CanPlayer.
Lab 1 Steps:
Run CanDump
Right Shift + X to open a door
Cancel CanDump (ctrl+c)
Left Shift + X to close the door
Run can player with the saved dump and it will replay the traffic and open the door
Recording the door opening:(-l for logging)
ficti0n@ubuntu:~/Desktop/ICSim$ candump -l vcan0
Replaying the CanDump file:(use the file your can dump created)
Nice, so if all went well you should see that your door is now open again. If this did not happen when attacking a real car, just try to replay it again. CAN networks are not like TCP/IP, they are more like UDP in that you send out your request and its not expecting a response. So if it gets lost then it gets lost and you have to resend. Perhaps something with higher priority on the network was sending at the time of your replay and your traffic was overshadowed by it.
Interacting with the Can Bus and Reversing Traffic:
So thats cool, but what about actually understanding what is going on with this traffic, CanDump is not very useful for this, is scrolls by to quickly for us to learn much from.Instead we can use CanSniffer with colorized output to show us the bytes within packets that change. Below is an example of CanSniffer Traffic:
You will see 3 fields, Time, IDand Data. Its pretty easy to figure out what these are based on thier name. The most important part for our usage in this blog are the ID and the Data fields.
The ID field is the frame ID which is loosely associated with the device on the network which is effected by the frame being sent. The ID to also determines the priority of the frame on the network.The lower the number of the CAN-ID the higher priority it has on the network and more likely it will be handled first.The data field is the data being sent to change some parameter like unlocking a door or updating output. You will notice that some of the bytes are highlighted RED. The values in red are the values that are changing during the idle state you are currently in.
Determine which ID and Byte controls the throttle:
So with the terminal sniffing window open put the simulator and the controller into the foreground, with the controller being the window you have clicked and selected.Pay attention to the CanSniffer output while hitting the UP ARROW and look for a value that was white but is now Red and increasing in value as the throttle goes up.This might take you a few minutes of paying attention to whats going on to see.
The following 2 pictures show ID 244 in the IDLE state followed by pressing the up button to increase the speed. You will notice a byte has turned red and is increasing in value through a range of HEX values 0-F. It will continue to enumerate through values till it reaches its max speed.
The byte in ID 244 which is changing is the value while the throttle is engaged, so 244 associated in some way with the increasing speed. The throttle speed is a good value to start with as it keeps increasing its value when pressed making it easier to spot while viewing the CanSniffer output.
Singling out Values with Filters:
If you would like to single out the throttle value then click the terminal window and press -000000 followed by the Enter key which will clear out all of the values scrolling. Then press +244 followed by the Enter key which will add back the throttle ID. You can now click the controller again and increase the speed with your Up arrow button without all the noise clouding your view.You will instead as shown below only have ID 244 in your output:
To get back all of the IDs again click the terminal window and input +000000 followed by the Enter key. Now you should see all of the output as before.Essentially 000000 means include everything. But when you put a minus in front of it then it negates everything and clears your terminal window filtering out all values.
Determine Blinker ID:
Now lets figure out another ID for the blinkers. If you hit the left or right arrow with the controls window selected you will notice a whole new ID appears in the list, ID 188 shown in the picture below which is associated with the blinker.
This ID was not listed before as it was not in use within the data output until you pressed the blinker control.Lets single this value out by pressing -000000 followed by +188. Just like in the throttle example your terminal should only show ID 188, initially it will show with 00 byte values.
As you press the left and the right blinker you will see the first Byte change from 00 to 01 or 02. If neither is pressed as in the screenshot above it will be 00. Its kind of hard to have the controller in focus and get a screenshot at the same time but the ID will remain visible as 00 until it times out and disappears from the list when not active. However with it filtered out as above you can get a better view of things and it wont disappear.
Time for YOU to do some Protocol Reversing:
This lab will give you a good idea how to reverse all of the functionality of the car and associate each action with the proper ID and BYTE. This way you can create a map of intended functionality changes you wish to make.Above we have done a few walk throughs with you on how to determine which byte and ID is associated with an action. Now its time to map everything out yourself with all the remaining functionality before moving on to attacking individual components.
Lab Work Suggestion:
Take out a piece of paper and a pencil
Try unlocking and locking doors and write down the ID which controls this action (remember your filters)
Try unlocking each door and write down the BYTES needed for each door to open
Try locking each doors and what Bytes change and what are their values, write them down
Do the same thing for the blinkers left and right (Might be different then what I did above)
What ID is the speedometer using?What byte changes the speed?
Attacking Functionality Directly:
With all of the functionality mapped out we can now try to target various devices in the network directly without interacting with the controllers GUI. Maybe we broke into the car via cellular OnStar connectionor the center console units BLE connection which was connected to the CAN network in some way.
After an exploit we have direct access to the CAN network and we would like to perform actions. Or maybe you have installed a wireless device into an OBD2 port under the dashboard you have remote access to the automobile.
Using the data from the CAN network reversing lab above we can call these actions directly with the proper CAN-ID and Byte.Since we are remote to the target we can’t just reach over and grab the steering wheel or hit the throttle we will instead send your CAN frame to make the change.
One way we can do this is via the CanSend utility. Lets take our information from our lab above and make the left turn signal flash with the following ID 188 for the turn signal by changing the first byte to 01 indicating the left signal is pressed. CanSend uses the format ID#Data. You will see this below when sending the turn signal via CanSend.
You should have noticed that the left signal flashed. If not pay more attention and give it another try or make sure you used the correct ID and changed the correct byte.So lets do the same thing with the throttle and try to set the speed to something with ID 244 that we determined was the throttle.
My guess is that nothing happened because its so fast the needle is not going to jump to that value. So instead lets try repeating this over and over again with a bash loop which simply says that while True keep sending the throttle value of 11 which equates to about 30mph:
ficti0n@ubuntu:~/Desktop/ICSim$ while true; do cansend vcan0 244#00000011F6;done
Yes thats much better, you may notice the needle jumping back and forth a bit. The reason the needle is bouncing back and forth is because the normal CAN traffic is sent telling the car its actually set to 00 in between your frames saying its 30mph.But it worked and you have now changed the speed the car sees and you have flashed the blinker without using the cars normal blinker controls. Pretty cool right?
Monitor the CAN Bus and react to it:
Another way to handle this issue is to monitor the CAN network and when it sees an ID sent it will automatically send the corresponding ID with a different value.. Lets give that a try to modify our speed output by monitoring for changes. Below we are simply running CanDump and parsing for ID 244 in the log output which is the throttle value that tells the car the speed. When a device in the car reports ID 244 and its value we will immediately resend our own value saying the speed is 30mph with the value 11.See below command and try this out.
ficti0n@ubuntu:~/Desktop/ICSim$ candump vcan0 | grep " 244 " | while read line; do cansend vcan0 244#00000011F6; done
With this running after a few seconds you will see the speed adjust to around 30MPH once it captures a legitimate CAN-ID 244 from the network traffic and sends its own value right after.
Ok cool, so now while the above command is still running click the controller window and start holding down the Up arrow with the controller in focus.. After a few seconds or so when the speed gets above 30MPH you will see the needle fighting for the real higher value and adjusting back to 30MPH as your command keeps sending its on value as a replacement to the real speed.
So thats one way of monitoring the network and reacting to what you see in a very crude manner.Maybe someone stole your car and you want to monitor for an open door and if they try to open the door it immediately locks them in.
Conclusion and whats next:
I am not an expert car hacker but I hope you enjoyed this. Thats about as far as I want to go into this subject today, in the next blog we will get into how to code python to perform actions on the CAN network to manipulate things in a similar way.With your own code you are not limited to the functionality of the tools you are provided and can do whatever you want. This is much more powerful then just using the CanUtils pre defined tools. Later on I will also get into the hardware side of things if you would like to try this on a real car where things are more complicated and things can go wrong.