-
Notifications
You must be signed in to change notification settings - Fork 13
/
launcher.py
232 lines (180 loc) · 6.14 KB
/
launcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import json
import os
import random
import string
import time
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional
from uuid import UUID
import requests
from eth_account import Account
from web3 import Web3
from web3.exceptions import TransactionNotFound
from web3.types import TxReceipt
from eth_sandbox import get_shared_secret
HTTP_PORT = os.getenv("HTTP_PORT", "8545")
PUBLIC_IP = os.getenv("PUBLIC_IP", "127.0.0.1")
CHALLENGE_ID = os.getenv("CHALLENGE_ID", "challenge")
ENV = os.getenv("ENV", "dev")
FLAG = os.getenv("FLAG", "PCTF{placeholder}")
Account.enable_unaudited_hdwallet_features()
@dataclass
class Ticket:
challenge_id: string
team_id: string
def check_ticket(ticket: str) -> Ticket:
if ENV == "dev":
return Ticket(challenge_id=CHALLENGE_ID, team_id="team")
ticket_info = requests.get(
f"https://us-central1-paradigm-ctf-2022.cloudfunctions.net/checkTicket?ticket={ticket}"
).json()
if ticket_info["status"] != "VALID":
return None
return Ticket(
challenge_id=ticket_info["challengeId"], team_id=ticket_info["teamId"]
)
@dataclass
class Action:
name: str
handler: Callable[[], int]
def sendTransaction(web3: Web3, tx: Dict) -> Optional[TxReceipt]:
if "gas" not in tx:
tx["gas"] = 10_000_000
if "gasPrice" not in tx:
tx["gasPrice"] = 0
# web3.provider.make_request("anvil_impersonateAccount", [tx["from"]])
txhash = web3.eth.sendTransaction(tx)
# web3.provider.make_request("anvil_stopImpersonatingAccount", [tx["from"]])
while True:
try:
rcpt = web3.eth.getTransactionReceipt(txhash)
break
except TransactionNotFound:
time.sleep(0.1)
if rcpt.status != 1:
raise Exception("failed to send transaction")
return rcpt
def new_launch_instance_action(
do_deploy: Callable[[Web3, str], str],
):
def action() -> int:
ticket = check_ticket(input("ticket please: "))
if not ticket:
print("invalid ticket!")
return 1
if ticket.challenge_id != CHALLENGE_ID:
print("invalid ticket!")
return 1
data = requests.post(
f"http://127.0.0.1:{HTTP_PORT}/new",
headers={
"Authorization": f"Bearer {get_shared_secret()}",
"Content-Type": "application/json",
},
data=json.dumps(
{
"team_id": ticket.team_id,
}
),
).json()
if data["ok"] == False:
print(data["message"])
return 1
uuid = data["uuid"]
mnemonic = data["mnemonic"]
deployer_acct = Account.from_mnemonic(mnemonic, account_path=f"m/44'/60'/0'/0/0")
player_acct = Account.from_mnemonic(mnemonic, account_path=f"m/44'/60'/0'/0/1")
web3 = Web3(Web3.HTTPProvider(
f"http://127.0.0.1:{HTTP_PORT}/{uuid}",
request_kwargs={
"headers": {
"Authorization": f"Bearer {get_shared_secret()}",
"Content-Type": "application/json",
},
},
))
setup_addr = do_deploy(web3, deployer_acct.address, player_acct.address)
with open(f"/tmp/{ticket.team_id}", "w") as f:
f.write(
json.dumps(
{
"uuid": uuid,
"mnemonic": mnemonic,
"address": setup_addr,
}
)
)
print()
print(f"your private blockchain has been deployed")
print(f"it will automatically terminate in 30 minutes")
print(f"here's some useful information")
print(f"uuid: {uuid}")
print(f"rpc endpoint: http://{PUBLIC_IP}:{HTTP_PORT}/{uuid}")
print(f"private key: {player_acct.privateKey.hex()}")
print(f"setup contract: {setup_addr}")
return 0
return Action(name="launch new instance", handler=action)
def new_kill_instance_action():
def action() -> int:
ticket = check_ticket(input("ticket please: "))
if not ticket:
print("invalid ticket!")
return 1
if ticket.challenge_id != CHALLENGE_ID:
print("invalid ticket!")
return 1
data = requests.post(
f"http://127.0.0.1:{HTTP_PORT}/kill",
headers={
"Authorization": f"Bearer {get_shared_secret()}",
"Content-Type": "application/json",
},
data=json.dumps(
{
"team_id": ticket.team_id,
}
),
).json()
print(data["message"])
return 1
return Action(name="kill instance", handler=action)
def is_solved_checker(web3: Web3, addr: str) -> bool:
result = web3.eth.call(
{
"to": addr,
"data": web3.sha3(text="isSolved()")[:4],
}
)
return int(result.hex(), 16) == 1
def new_get_flag_action(
checker: Callable[[Web3, str], bool] = is_solved_checker,
):
def action() -> int:
ticket = check_ticket(input("ticket please: "))
if not ticket:
print("invalid ticket!")
return 1
if ticket.challenge_id != CHALLENGE_ID:
print("invalid ticket!")
return 1
try:
with open(f"/tmp/{ticket.team_id}", "r") as f:
data = json.loads(f.read())
except:
print("bad ticket")
return 1
web3 = Web3(Web3.HTTPProvider(f"http://127.0.0.1:{HTTP_PORT}/{data['uuid']}"))
if not checker(web3, data['address']):
print("are you sure you solved it?")
return 1
print(FLAG)
return 0
return Action(name="get flag", handler=action)
def run_launcher(actions: List[Action]):
for i, action in enumerate(actions):
print(f"{i+1} - {action.name}")
action = int(input("action? ")) - 1
if action < 0 or action >= len(actions):
print("can you not")
exit(1)
exit(actions[action].handler())