Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions .github/workflows/smoketest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,13 @@ jobs:
- name: Configuration
run: |
uv sync --locked
mkdir var

cp conf/local_settings.py.example conf/local_settings.py
PRIVATE_KEY=$(openssl ecparam -name secp256k1 -genkey -noout)

sed -i "s!openssl ecparam -name secp256k1 -genkey -noout!${PRIVATE_KEY//$'\n'/\\n}!g" conf/local_settings.py
CERTIFICATE=$(openssl req -x509 -key conf/local_settings.py -days 30 -subj "/CN=notforproduction")
sed -i "s!openssl req -x509 -key conf/local_settings.py -days 30!${CERTIFICATE//$'\n'/\\n}!g" conf/local_settings.py

# set SECRET_KEY
sed -i "s/SECRET_KEY = ''/SECRET_KEY = 'test'/g" conf/local_settings.py

mkdir var
PRIVATE_KEY=$(uv run ./manage.py generate_key | awk 'NR==2')
sed -i "/^PRIVATE_KEY = '''/{n;s|.*|$PRIVATE_KEY|;}" conf/local_settings.py
- name: Run smoke test
run: |
source .venv/bin/activate
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

1. 安装 [uv](https://docs.astral.sh/uv/)。
1. 安装依赖:`uv sync --locked`。
1. 密钥配置:`cp conf/local_settings.py.example conf/local_settings.py`,编辑 `conf/local_settings.py`,其中有两条命令,需要执行并把输出贴在相应位置。
1. 设置环境变量:`export DJANGO_SETTINGS_MODULE=conf.settings.dev`。
1. 密钥配置:`cp conf/local_settings.py.example conf/local_settings.py`,运行 `uv run ./manage.py generate_key`,把输出的私钥填入 `PRIVATE_KEY`,并在其他地方存储公钥(题目可能需要使用)。
1. 创建数据目录:`mkdir var`。
1. 数据库初始化:`uv run ./manage.py migrate`。
1. (可选)Google 与 Microsoft app secret 写入数据库:`uv run ./manage.py setup`。
Expand All @@ -23,8 +23,8 @@
1. Media 目录:`mkdir -p /var/opt/hackergame/media`,`chown www-data: /var/opt/hackergame/media`。
1. 使用 uv 创建虚拟环境并安装 Python 软件包:`cd /opt/hackergame`,`uv sync --locked`。
1. 进入 venv:`. .venv/bin/activate`。
1. 密钥配置:`cp conf/local_settings.py.example conf/local_settings.py`,编辑 `conf/local_settings.py`,其中有两条命令,需要执行并把输出贴在相应位置。
1. 设置环境变量:`export DJANGO_SETTINGS_MODULE=conf.settings.hackergame`。
1. 密钥配置:`cp conf/local_settings.py.example conf/local_settings.py`,运行 `./manage.py generate_key`,把输出的私钥填入 `PRIVATE_KEY`。
1. 数据库初始化:`./manage.py migrate`。
1. Static 目录初始化:`./manage.py collectstatic`。
1. Google 与 Microsoft app secret 写入数据库:`./manage.py setup`。
Expand Down
5 changes: 1 addition & 4 deletions conf/local_settings.py.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
SECRET_KEY = ''
PRIVATE_KEY = '''
openssl ecparam -name secp256k1 -genkey -noout
'''
CERTIFICATE = '''
openssl req -x509 -key conf/local_settings.py -days 30
运行 manage.py generate_key 后输出的私钥(64 位十六进制字符串)
'''
GOOGLE_APP_SECRET = ''
MICROSOFT_APP_SECRET = ''
Expand Down
4 changes: 2 additions & 2 deletions frontend/management/commands/fake_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def a():
'name': f'flag {j}',
'score': random.randrange(100),
'type': ('expr', 'text')[j % 2],
'flag': ("f'flag{{%s:{token.partition(\":\")[0]}}}'" % j,
'flag': ("f'flag{{%s:{token[:12]}}}'" % j,
f'flag{{{j}}}')[j % 2],
} for j in range(random.randrange(1, 4))],
)
Expand All @@ -132,7 +132,7 @@ def a():
'score': random.randrange(100),
'type': ('text', 'expr')[i % 2],
'flag': ('flag{0}',
"'flag{0:'+token.partition(':')[0]+'}'")[i % 2],
"'flag{0:'+token[:12]+'}'")[i % 2],
}],
)

Expand Down
17 changes: 17 additions & 0 deletions frontend/management/commands/generate_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.core.management.base import BaseCommand
import nacl.encoding
import nacl.signing

class Command(BaseCommand):
help = '生成 libsodium (Ed25519) 签名密钥'

def handle(self, *args, **options):

key = nacl.signing.SigningKey.generate()
private_key = key.encode(encoder=nacl.encoding.HexEncoder).decode()
public_key = key.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode()

self.stdout.write('这是私钥,请放进 Hackergame 平台 conf/local_settings.py 的 PRIVATE_KEY:')
self.stdout.write(private_key)
self.stdout.write('这是公钥,可用于验证 token:')
self.stdout.write(public_key)
5 changes: 2 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ readme = "README.md"
requires-python = ">=3.9"
dependencies = [
"asgiref==3.8.1",
"cryptography==44.0.1",
"django==4.2.28",
"django-allauth==65.13.0",
"django-allauth[socialaccount]==65.13.0",
"gevent==24.11.1",
"markdown==3.7",
"psycopg==3.2.3",
Expand All @@ -18,7 +17,7 @@ dependencies = [
"pygments==2.18.0",
"pyjwt==2.9.0",
"pymemcache==4.0.0",
"pyopenssl==24.3.0",
"pynacl==1.5.0",
"pyyaml==6.0.2",
"requests==2.32.4",
"uwsgi==2.0.31",
Expand Down
6 changes: 3 additions & 3 deletions server/challenge/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ def test_fields(self):
class TestExprFlags(TestCase):
def setUp(self) -> None:
# a nonsense token
self.token = "2:BBBBBBu1qB2iBBjcpBBBwpBlBnlvryj508f3BeBs5gBaaBB5BiBBn+B4xBx/2+l+c1o81BqBcwBBBnBBpB5fBBewBBz20yw="
self.token = "ea7cc653e0838e229a31a10f98f3191daacb8e251c4b06827786e2b69ef6695b50786731c04e159f6b4e6a790a99f0d1ac5dc8099fefcbe50411953afc35920831"
return super().setUp()

def test_expr(self):
res = expr_flag("'flag{' + md5('secret' + token)[:16] + '}'", self.token)
self.assertEqual(res, "flag{6a513c83d63baea4}")
self.assertEqual(res, "flag{6f6814f00964b0ab}")
res = expr_flag("'flag{' + str(int(md5('secret' + token), 16) % 10001) + '}'", self.token)
self.assertEqual(res, "flag{9011}")
self.assertEqual(res, "flag{7148}")
36 changes: 23 additions & 13 deletions server/user/interface.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import base64
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import ec
from hashlib import sha256
from uuid import uuid4

import nacl.encoding
import nacl.signing

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import RegexValidator, EmailValidator

from server.exceptions import Error, NotFound, WrongArguments, WrongFormat
Expand Down Expand Up @@ -117,15 +117,26 @@ class User:
'aff': RegexValidator(r'^.{1,100}$', '了解比赛的渠道格式错误'),
'suspicious_reason': None,
}
_private_key = serialization.load_pem_private_key(
settings.PRIVATE_KEY.encode(),
password=None,
)
_private_key = None

def __init__(self, context, obj: models.User):
self._context = context
self._obj = obj

@classmethod
def _get_private_key(cls):
if cls._private_key is None:
try:
cls._private_key = nacl.signing.SigningKey(
settings.PRIVATE_KEY.strip().encode(),
encoder=nacl.encoding.HexEncoder,
)
except Exception as exc:
raise ImproperlyConfigured(
'PRIVATE_KEY 必须是 64 位十六进制字符串,可用 ./manage.py generate_key 生成'
) from exc
return cls._private_key

@classmethod
def test_authenticated(cls, context):
if context.elevated:
Expand Down Expand Up @@ -157,11 +168,10 @@ def create(cls, context, group, user=None, **kwargs):
user = get_user_model().objects.create_user(str(uuid4()))
self = cls(context, models.User(user=user.pk))
pk = str(user.pk)
sig = base64.b64encode(self._private_key.sign(
self._obj.token = self._get_private_key().sign(
pk.encode(),
ec.ECDSA(hashes.SHA256())
)).decode()
self._obj.token = pk + ':' + sig
encoder=nacl.encoding.HexEncoder,
).decode()
try:
server.trigger.interface.Trigger.test_can_update_profile(context)
except server.trigger.interface.TriggerIsOff:
Expand Down Expand Up @@ -430,7 +440,7 @@ def token_short(self):
User.test_permission(self._context, 'user.full',
'user.view', f'user.view_{self.group}')
token = self._obj.token
return token[: token.find(':') + 11] + '...'
return token if len(token) <= 10 else token[:10] + '...'

@property
def code(self):
Expand Down
Loading