Happy-Birthday

一、

wiz26年的四月份靶场题,感觉还是很有意思的,遂做一做

啥时候做出来就可以满上了:(

二、

简单看一下handler.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
import hashlib
import hmac
import json
import os
import re
import time
import uuid

import boto3

s3 = boto3.client("s3")
sns = boto3.client("sns")
PRIVATE_BUCKET = os.environ.get("PRIVATE_BUCKET")
PUBLIC_BUCKET = os.environ.get("PUBLIC_BUCKET")
SNS_TOPIC_ARN = os.environ.get("SNS_TOPIC_ARN")
TOKEN_SECRET = os.environ.get("TOKEN_SECRET")
TOKEN_TTL = 3600 # 1 hour
ALLOWED_DOMAIN = "@cloudsecuritychampionship.com"
API_BASE_URL = os.environ.get("API_BASE_URL")

EMAIL_RE = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")

SNS_TOPIC_NAME = SNS_TOPIC_ARN.split(":")[-1] if SNS_TOPIC_ARN else ""


def _make_token():
ts = str(int(time.time()))
sig = hmac.new(TOKEN_SECRET.encode(), ts.encode(), hashlib.sha256).hexdigest()[:16]
return f"{ts}:{sig}"


def _verify_token(token):
try:
ts, sig = token.split(":", 1)
expected = hmac.new(
TOKEN_SECRET.encode(), ts.encode(), hashlib.sha256
).hexdigest()[:16]
if not hmac.compare_digest(sig, expected):
return False
if time.time() - int(ts) > TOKEN_TTL:
return False
return True
except Exception:
return False


def _read_template(template):
if ".." in template:
return None, "Invalid template name."

template_key = os.path.join("templates", f"{template}.txt")

try:
obj = s3.get_object(Bucket=PRIVATE_BUCKET, Key=template_key)
return obj["Body"].read().decode(), None
except Exception:
return None, "Template not found."


def handler(event, context):
is_apigw = "requestContext" in event

if is_apigw:
body = json.loads(event.get("body") or "{}")
resource_path = event.get("resource", "")

if resource_path == "/register":
token = body.get("token", "")
template = body.get("template", "default_balloon")

if not token or not _verify_token(token):
return _response(
403,
{
"status": "error",
"message": "Invalid or expired invitation token.",
},
)

content, err = _read_template(template)
if err:
return _response(400, {"status": "error", "message": err})

name = body.get("name", "Guest")
card_content = content.replace("{{name}}", name)

card_id = str(uuid.uuid4())
card_key = f"cards/{card_id}.html"

try:
s3.put_object(
Bucket=PUBLIC_BUCKET,
Key=card_key,
Body=card_content,
ContentType="text/html",
)
except Exception:
pass

card_url = f"https://{PUBLIC_BUCKET}.s3.amazonaws.com/{card_key}"

return _response(
200,
{
"status": "success",
"message": "Registration complete! Here is your birthday card.",
"card_url": card_url,
},
)

# /generate endpoint
email = body.get("email", "")

if not email:
return _response(400, {"status": "error", "message": "Email is required."})

if not EMAIL_RE.match(email):
return _response(
400,
{"status": "error", "message": "Please enter a valid email address."},
)

if not email.endswith(ALLOWED_DOMAIN):
return _response(
403,
{
"status": "error",
"message": (
f"Only {ALLOWED_DOMAIN} email addresses are eligible."
f" Invitations are delivered via the {SNS_TOPIC_NAME}"
f" notification channel."
),
},
)

try:
sns.subscribe(
TopicArn=SNS_TOPIC_ARN,
Protocol="email",
Endpoint=email,
)
except Exception as e:
return _response(
500,
{"status": "error", "message": f"Failed to send invitation: {str(e)}"},
)

token = _make_token()
register_url = f"{API_BASE_URL}/register.html?token={token}"

try:
sns.publish(
TopicArn=SNS_TOPIC_ARN,
Subject="Your Birthday Party Invitation!",
Message=json.dumps(
{
"message": "You're invited to the S3 Birthday Party!",
"action": "Complete your registration to get your personalized birthday card.",
"registration_url": register_url,
"token": token,
"expires_in": "1 hour",
"generated_by": context.function_name,
}
),
)
except Exception:
pass

return _response(
200,
{
"status": "success",
"message": "Invitation sent! Check your email.",
},
)

# Direct invocation path: requires valid token
token = event.get("token", "")
template = event.get("template", "default_balloon")

if not token or not _verify_token(token):
return {"status": "error", "message": "Invalid or expired invitation token."}

content, err = _read_template(template)
if err:
return {"status": "error", "message": err}

card_content = content.replace("{{name}}", event.get("name", "Friend"))

return {
"status": "success",
"data": {
"card_content": card_content,
},
}


def _response(status_code, body):
return {
"statusCode": status_code,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
"body": json.dumps(body),
}