Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Tighten limits

Manav Rathi0aecce57fdc1
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index acc7671d7d..d7f1d88366 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -1097,6 +1097,9 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
_ = castDb.DeleteOldSessions(context.Background(), timeUtil.MicrosecondsBeforeDays(7))
_ = collectionLinkRepo.CleanupAccessHistory(context.Background())
_ = fileLinkRepo.CleanupAccessHistory(context.Background())
+ })
+
+ schedule(c, "@every 30m", func() {
_ = pasteRepo.CleanupExpired(context.Background())
})
diff --git a/server/ente/paste.go b/server/ente/paste.go
index 6e64a1cef3..fb2d10287e 100644
--- a/server/ente/paste.go
+++ b/server/ente/paste.go
@@ -11,6 +11,9 @@ const (
pasteKdfNonceMaxLength = 64
pasteKdfMemLimitInteractive = 64 * 1024 * 1024
pasteKdfOpsLimitInteractive = 2
+ pasteDecryptionHeaderMaxLength = 128
+ pasteEncryptedPasteKeyMaxLength = 256
+ pasteEncryptedPasteKeyNonceMaxLength = 128
)
type CreatePasteRequest struct {
@@ -27,7 +30,7 @@ func (r *CreatePasteRequest) Validate(maxCiphertextBytes int) error {
if strings.TrimSpace(r.EncryptedData) == "" || strings.TrimSpace(r.DecryptionHeader) == "" {
return NewBadRequestWithMessage("invalid encrypted payload")
}
- if len(r.EncryptedData) > maxCiphertextBytes || len(r.DecryptionHeader) > maxCiphertextBytes {
+ if len(r.EncryptedData) > maxCiphertextBytes || len(r.DecryptionHeader) > pasteDecryptionHeaderMaxLength {
return NewBadRequestWithMessage("encrypted payload too large")
}
@@ -36,7 +39,7 @@ func (r *CreatePasteRequest) Validate(maxCiphertextBytes int) error {
strings.TrimSpace(r.KdfNonce) == "" {
return NewBadRequestWithMessage("invalid key material")
}
- if len(r.EncryptedPasteKey) > maxCiphertextBytes || len(r.EncryptedPasteKeyNonce) > maxCiphertextBytes {
+ if len(r.EncryptedPasteKey) > pasteEncryptedPasteKeyMaxLength || len(r.EncryptedPasteKeyNonce) > pasteEncryptedPasteKeyNonceMaxLength {
return NewBadRequestWithMessage("key material too large")
}
if len(r.KdfNonce) > pasteKdfNonceMaxLength {
diff --git a/server/ente/paste_test.go b/server/ente/paste_test.go
index d1b571730e..64966aef47 100644
--- a/server/ente/paste_test.go
+++ b/server/ente/paste_test.go
@@ -25,6 +25,42 @@ func TestCreatePasteRequestValidate_Valid(t *testing.T) {
}
}
+func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPayload(t *testing.T) {
+ req := newValidPasteRequest()
+ req.EncryptedData = strings.Repeat("a", 1025)
+
+ if err := req.Validate(1024); err == nil {
+ t.Fatal("expected oversized encrypted payload to be rejected")
+ }
+}
+
+func TestCreatePasteRequestValidate_RejectsOversizedDecryptionHeader(t *testing.T) {
+ req := newValidPasteRequest()
+ req.DecryptionHeader = strings.Repeat("a", pasteDecryptionHeaderMaxLength+1)
+
+ if err := req.Validate(1024); err == nil {
+ t.Fatal("expected oversized decryption header to be rejected")
+ }
+}
+
+func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPasteKey(t *testing.T) {
+ req := newValidPasteRequest()
+ req.EncryptedPasteKey = strings.Repeat("a", pasteEncryptedPasteKeyMaxLength+1)
+
+ if err := req.Validate(1024); err == nil {
+ t.Fatal("expected oversized encrypted paste key to be rejected")
+ }
+}
+
+func TestCreatePasteRequestValidate_RejectsOversizedEncryptedPasteKeyNonce(t *testing.T) {
+ req := newValidPasteRequest()
+ req.EncryptedPasteKeyNonce = strings.Repeat("a", pasteEncryptedPasteKeyNonceMaxLength+1)
+
+ if err := req.Validate(1024); err == nil {
+ t.Fatal("expected oversized encrypted paste key nonce to be rejected")
+ }
+}
+
func TestCreatePasteRequestValidate_RejectsOversizedKdfNonce(t *testing.T) {
req := newValidPasteRequest()
req.KdfNonce = strings.Repeat("a", pasteKdfNonceMaxLength+1)
diff --git a/server/pkg/controller/public/paste.go b/server/pkg/controller/public/paste.go
index 8eb3c54858..f3de6a1ce5 100644
--- a/server/pkg/controller/public/paste.go
+++ b/server/pkg/controller/public/paste.go
@@ -3,6 +3,7 @@ package public
import (
"crypto/sha256"
"encoding/hex"
+ "fmt"
"net/http"
"strings"
"time"
@@ -20,7 +21,9 @@ import (
const (
pasteAccessTokenLength = 10
- maxCiphertextBytes = 64 * 1024
+ // For 4k input, worst case is 32040 bytes after JSON escaping (up to 6x),
+ // secretstream overhead (+17), and base64 encoding. Keep a small margin.
+ maxCiphertextBytes = 32256
pasteTTL = 24 * time.Hour
guardTTL = 2 * time.Minute
guardCookieName = "paste_guard"
@@ -159,6 +162,9 @@ func (c *PasteController) validateGuard(ctx *gin.Context, accessToken string) er
}
parsedToken, err := jwt.ParseWithClaims(guardToken, &enteJWT.PasteGuardClaim{}, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
return c.JwtSecret, nil
})
if err != nil {
diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.go
index eab7545e43..32467fdfb7 100644
--- a/server/pkg/middleware/rate_limit.go
+++ b/server/pkg/middleware/rate_limit.go
@@ -24,6 +24,7 @@ type RateLimitMiddleware struct {
reset time.Duration
ticker *time.Ticker
limit10ReqPerMin *limiter.Limiter
+ limit300ReqPerMin *limiter.Limiter
limit200ReqPerMin *limiter.Limiter
limit200ReqPerSec *limiter.Limiter
discordCtrl *discord.DiscordController
@@ -32,6 +33,7 @@ type RateLimitMiddleware struct {
func NewRateLimitMiddleware(discordCtrl *discord.DiscordController, limit int64, reset time.Duration) *RateLimitMiddleware {
rl := &RateLimitMiddleware{
limit10ReqPerMin: util.NewRateLimiter("10-M"),
+ limit300ReqPerMin: util.NewRateLimiter("300-M"),
limit200ReqPerMin: util.NewRateLimiter("200-M"),
limit200ReqPerSec: util.NewRateLimiter("200-S"),
discordCtrl: discordCtrl,
@@ -79,6 +81,24 @@ func (r *RateLimitMiddleware) GlobalRateLimiter() gin.HandlerFunc {
func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.Context) string) gin.HandlerFunc {
return func(c *gin.Context) {
requestPath := urlSanitizer(c)
+
+ globalRateLimiter := r.getGlobalLimiter(requestPath, c.Request.Method)
+ if globalRateLimiter != nil {
+ limitContext, err := globalRateLimiter.Get(c, requestPath)
+ if err != nil {
+ log.Error("Failed to check global rate limit", err)
+ c.Next() // assume that limit hasn't reached
+ return
+ }
+ if limitContext.Reached {
+ msg := fmt.Sprintf("Global rate limit breached %s", requestPath)
+ go r.discordCtrl.NotifyPotentialAbuse(msg)
+ log.Error(msg)
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})
+ return
+ }
+ }
+
rateLimiter := r.getLimiter(requestPath, c.Request.Method)
if rateLimiter != nil {
key := fmt.Sprintf("%s-%s", network.GetClientIP(c), requestPath)
@@ -130,6 +150,16 @@ func (r *RateLimitMiddleware) APIRateLimitForUserMiddleware(urlSanitizer func(_
}
}
+// getGlobalLimiter, based on reqPath & reqMethod, returns a limiter that should
+// be applied globally for requests matching the route. It returns nil if no
+// global route-specific limit should be applied.
+func (r *RateLimitMiddleware) getGlobalLimiter(reqPath string, reqMethod string) *limiter.Limiter {
+ if reqPath == "/paste/create" || reqPath == "/paste/guard" || reqPath == "/paste/consume" {
+ return r.limit300ReqPerMin
+ }
+ return nil
+}
+
// getLimiter, based on reqPath & reqMethod, return instance of limiter.Limiter which needs to
// be applied for a request. It returns nil if the request is not rate limited
func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limiter.Limiter {
diff --git a/server/pkg/middleware/request_logger.go b/server/pkg/middleware/request_logger.go
index 3de3c6e546..b5bc29e79c 100644
--- a/server/pkg/middleware/request_logger.go
+++ b/server/pkg/middleware/request_logger.go
@@ -44,6 +44,9 @@ func shouldSkipBodyLog(method string, path string) bool {
if path == "/admin/user/terminate-session" {
return true
}
+ if method == http.MethodPost && (path == "/paste/create" || path == "/paste/guard" || path == "/paste/consume") {
+ return true
+ }
return false
}