tiktak: принимать legacy-токены для старых видео + fail-open в probe
MUMBLE "failed to get access using private key": чекер держит share-токен, выданный ещё старым keygen, а после перехода на HMAC ValidateKey его отвергал. - keygen/legacy.go: восстановленный из keygen.a алгоритм seed=(seed*17+42)%62 принимается ТОЛЬКО для video.id <= cutoff, то есть для видео, существовавших на момент перехода. Выше cutoff -- лишь HMAC. - cutoff берётся из max(video.id) при первом старте и пишется в public/.legacy_cutoff на volume: рестарт не должен расширять окно. Не смогли прочитать -- fail closed, legacy выключен. - Когда старые флаги протухнут: echo 0 > public/.legacy_cutoff + рестарт, и legacy отключается полностью. Ещё MUMBLE "cannot create video" -- он же DoS, у NOP-команды то же самое: - checkGeometry сделан FAIL-OPEN. Неразобранный ffprobe больше не отклоняет загрузку, режем только успешно прочитанную и абсурдную геометрию. - ffmpeg -max_alloc 128M: 1080p кадру нужно ~8 МБ, бомбе ~1 ГБ. Работает даже когда probe промолчал. check_tiktak.sh: smoke-тест для vulnbox, гоняет сценарий чекера целиком и отдельно проверяет, что патчи реально в задеплоенном билде. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -138,3 +138,11 @@ func (s *Storage) AddAccess(ctx context.Context, id int, userId int64) error {
|
||||
ExecContext(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// MaxVideoID reports the highest video id currently stored, 0 when empty.
|
||||
func (s *Storage) MaxVideoID(ctx context.Context) (int64, error) {
|
||||
sess := s.conn.NewSession(nil)
|
||||
var id int64
|
||||
err := sess.Select("COALESCE(MAX(id), 0)").From("video").LoadOneContext(ctx, &id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
@@ -38,5 +38,10 @@ func GenerateKey(vid int) string {
|
||||
|
||||
func ValidateKey(token string, vid int) bool {
|
||||
// Constant-time: never leak how much of the token was correct.
|
||||
return hmac.Equal([]byte(token), []byte(GenerateKey(vid)))
|
||||
if hmac.Equal([]byte(token), []byte(GenerateKey(vid))) {
|
||||
return true
|
||||
}
|
||||
// Grandfather in tokens handed out by the legacy algorithm, but only for
|
||||
// videos that already existed when we switched. See legacy.go.
|
||||
return legacyAccepted(token, vid)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package keygen
|
||||
|
||||
import "crypto/subtle"
|
||||
|
||||
// Reconstructed from legacy/keygen.a (GenerateToken), kept ONLY for backwards
|
||||
// compatibility: the checker may still hold tokens it was handed before the
|
||||
// HMAC switch, and rejecting those costs SLA ("failed to get access using
|
||||
// private key").
|
||||
//
|
||||
// int seed = n;
|
||||
// for (i = 0; i < 30; i++) { seed = (seed*17 + 42) % 62; out[i] = alpha[seed]; }
|
||||
//
|
||||
// The state collapses into n%62 after the first round, so this yields only 62
|
||||
// distinct tokens overall -- which is exactly why it had to go.
|
||||
func legacyKey(vid int) string {
|
||||
seed := vid
|
||||
out := make([]byte, tokenLen)
|
||||
for i := 0; i < tokenLen; i++ {
|
||||
seed = (seed*17 + 42) % 62
|
||||
out[i] = alphabet[seed]
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// legacyCutoff is the highest video id that existed when the HMAC patch was
|
||||
// deployed. Videos above it were never shared with a legacy token, so they must
|
||||
// never accept one. 0 disables legacy acceptance entirely.
|
||||
var legacyCutoff int
|
||||
|
||||
func SetLegacyCutoff(id int) { legacyCutoff = id }
|
||||
|
||||
func legacyAccepted(token string, vid int) bool {
|
||||
if legacyCutoff <= 0 || vid <= 0 || vid > legacyCutoff {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(token), []byte(legacyKey(vid))) == 1
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package keygen
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLegacyDualValidation(t *testing.T) {
|
||||
// Reference values produced independently from the disassembly.
|
||||
if got, want := legacyKey(1), "71npXhLZP5t3VJrvBfdFlRDNx9zHTb"; got != want {
|
||||
t.Fatalf("legacyKey(1) = %q, want %q", got, want)
|
||||
}
|
||||
if legacyKey(1) != legacyKey(63) {
|
||||
t.Fatal("legacy period should be 62")
|
||||
}
|
||||
|
||||
SetLegacyCutoff(0)
|
||||
if ValidateKey(legacyKey(5), 5) {
|
||||
t.Fatal("cutoff 0 must reject every legacy token")
|
||||
}
|
||||
|
||||
SetLegacyCutoff(100)
|
||||
if !ValidateKey(legacyKey(5), 5) {
|
||||
t.Fatal("old video must still accept its legacy token")
|
||||
}
|
||||
if ValidateKey(legacyKey(101), 101) {
|
||||
t.Fatal("video created after the switch must NOT accept a legacy token")
|
||||
}
|
||||
if !ValidateKey(GenerateKey(101), 101) {
|
||||
t.Fatal("new HMAC token must work above the cutoff")
|
||||
}
|
||||
if !ValidateKey(GenerateKey(5), 5) {
|
||||
t.Fatal("new HMAC token must work below the cutoff too")
|
||||
}
|
||||
if ValidateKey(legacyKey(6), 5) || ValidateKey("garbage", 5) {
|
||||
t.Fatal("wrong token accepted")
|
||||
}
|
||||
SetLegacyCutoff(0)
|
||||
}
|
||||
+37
-1
@@ -6,10 +6,14 @@ import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/gocraft/dbr/v2"
|
||||
"github.com/thanhpk/randstr"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"tiktak/db"
|
||||
"tiktak/keygen"
|
||||
"tiktak/server"
|
||||
"tiktak/server/auth"
|
||||
"tiktak/video"
|
||||
@@ -29,13 +33,21 @@ func main() {
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
storage := db.New(conn)
|
||||
|
||||
auth.SetSalt(randstr.Hex(20))
|
||||
|
||||
// Videos that already existed when the HMAC keygen was deployed may still
|
||||
// be shared with a legacy token the checker is holding. Freeze that cutoff
|
||||
// on first boot and persist it, so a container restart cannot widen the
|
||||
// window (a wider window means more videos accepting forgeable tokens).
|
||||
keygen.SetLegacyCutoff(legacyCutoff(storage))
|
||||
config := server.Config{
|
||||
StaticFolder: "public/static",
|
||||
VttFolder: "public/vtt",
|
||||
TemplatesFolder: "templates",
|
||||
}
|
||||
srv := server.NewServer(db.New(conn), &video.Storage{Directory: "public/video"}, config)
|
||||
srv := server.NewServer(storage, &video.Storage{Directory: "public/video"}, config)
|
||||
|
||||
// Start server
|
||||
go func() {
|
||||
@@ -54,3 +66,27 @@ func main() {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// legacyCutoffFile lives on the ./public volume so it survives restarts.
|
||||
const legacyCutoffFile = "public/.legacy_cutoff"
|
||||
|
||||
func legacyCutoff(storage *db.Storage) int {
|
||||
if b, err := ioutil.ReadFile(legacyCutoffFile); err == nil {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil {
|
||||
fmt.Println("legacy token cutoff (pinned):", n)
|
||||
return n
|
||||
}
|
||||
}
|
||||
|
||||
id, err := storage.MaxVideoID(context.Background())
|
||||
if err != nil {
|
||||
// Fail closed: no legacy tokens rather than an unbounded window.
|
||||
fmt.Println("cannot read max video id, legacy tokens disabled:", err)
|
||||
return 0
|
||||
}
|
||||
if err := ioutil.WriteFile(legacyCutoffFile, []byte(strconv.FormatInt(id, 10)), 0644); err != nil {
|
||||
fmt.Println("cannot pin legacy cutoff:", err)
|
||||
}
|
||||
fmt.Println("legacy token cutoff (fresh):", id)
|
||||
return int(id)
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ func generatePreview(ctx context.Context, inp string, out string) error {
|
||||
if err := checkGeometry(ctx, inp); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "ffmpeg", "-y", "-threads", "1", "-i", inp, "-vframes", "1", out)
|
||||
// -max_alloc caps a single ffmpeg allocation: a 1080p frame needs ~8 MB, a
|
||||
// 16383x16383 bomb needs ~1 GB. Second line of defence behind checkGeometry,
|
||||
// and it works even when the probe told us nothing.
|
||||
cmd := exec.CommandContext(ctx, "ffmpeg", "-y", "-threads", "1",
|
||||
"-max_alloc", "134217728", "-i", inp, "-vframes", "1", out)
|
||||
s := strings.Builder{}
|
||||
cmd.Stdout = &s
|
||||
cmd.Stderr = &s
|
||||
|
||||
@@ -20,16 +20,24 @@ func checkGeometry(ctx context.Context, inp string) error {
|
||||
args := []string{"-v", "error", "-select_streams", "v:0",
|
||||
"-show_entries", "stream=width,height", "-of", "csv=s=x:p=0", inp}
|
||||
|
||||
// FAIL-OPEN on purpose. A probe that errors out or prints something we do
|
||||
// not understand must NOT reject the upload: the checker's video would
|
||||
// start failing with "cannot create video" and that costs more than the
|
||||
// bomb does. Only a geometry we successfully read and that is absurd is
|
||||
// rejected. Bombs need a real, huge, parseable resolution to be bombs.
|
||||
out, err := exec.CommandContext(ctx, "ffprobe", args...).Output()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot probe video: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var w, h int
|
||||
if _, err := fmt.Sscanf(strings.TrimSpace(string(out)), "%dx%d", &w, &h); err != nil {
|
||||
return fmt.Errorf("cannot read video geometry")
|
||||
return nil
|
||||
}
|
||||
if w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension || w*h > MaxPixels {
|
||||
if w <= 0 || h <= 0 {
|
||||
return nil
|
||||
}
|
||||
if w > MaxDimension || h > MaxDimension || w*h > MaxPixels {
|
||||
return fmt.Errorf("video resolution %dx%d is not supported", w, h)
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user