mirror of
https://github.com/superseriousbusiness/gotosocial.git
synced 2025-11-07 05:19:30 -06:00
finish adding an initial draft of the nollamas security check
This commit is contained in:
parent
2442c6fc41
commit
86e342c443
4 changed files with 64 additions and 128 deletions
|
|
@ -499,6 +499,7 @@ var Start action.GTSAction = func(ctx context.Context) error {
|
||||||
s2sLimit := middleware.RateLimit(rlLimit, exceptions) // server-to-server (AP)
|
s2sLimit := middleware.RateLimit(rlLimit, exceptions) // server-to-server (AP)
|
||||||
fsMainLimit := middleware.RateLimit(rlLimit, exceptions) // fileserver / web templates
|
fsMainLimit := middleware.RateLimit(rlLimit, exceptions) // fileserver / web templates
|
||||||
fsEmojiLimit := middleware.RateLimit(rlLimit*2, exceptions) // fileserver (emojis only, use high limit)
|
fsEmojiLimit := middleware.RateLimit(rlLimit*2, exceptions) // fileserver (emojis only, use high limit)
|
||||||
|
nollamas := middleware.NoLLaMas(state.DB)
|
||||||
|
|
||||||
// throttling
|
// throttling
|
||||||
cpuMultiplier := config.GetAdvancedThrottlingMultiplier()
|
cpuMultiplier := config.GetAdvancedThrottlingMultiplier()
|
||||||
|
|
@ -544,7 +545,7 @@ var Start action.GTSAction = func(ctx context.Context) error {
|
||||||
nodeInfoModule.Route(route, s2sLimit, s2sThrottle, gzip)
|
nodeInfoModule.Route(route, s2sLimit, s2sThrottle, gzip)
|
||||||
activityPubModule.Route(route, s2sLimit, s2sThrottle, robotsDisallowAll, gzip)
|
activityPubModule.Route(route, s2sLimit, s2sThrottle, robotsDisallowAll, gzip)
|
||||||
activityPubModule.RoutePublicKey(route, s2sLimit, pkThrottle, robotsDisallowAll, gzip)
|
activityPubModule.RoutePublicKey(route, s2sLimit, pkThrottle, robotsDisallowAll, gzip)
|
||||||
webModule.Route(route, fsMainLimit, fsThrottle, robotsDisallowAIOnly, gzip)
|
webModule.Route(route, fsMainLimit, fsThrottle, robotsDisallowAIOnly, nollamas, gzip)
|
||||||
|
|
||||||
// Finally start the main http server!
|
// Finally start the main http server!
|
||||||
if err := route.Start(); err != nil {
|
if err := route.Start(); err != nil {
|
||||||
|
|
|
||||||
|
|
@ -257,6 +257,8 @@ var Start action.GTSAction = func(ctx context.Context) error {
|
||||||
nodeInfoModule = api.NewNodeInfo(processor) // nodeinfo endpoint
|
nodeInfoModule = api.NewNodeInfo(processor) // nodeinfo endpoint
|
||||||
activityPubModule = api.NewActivityPub(state.DB, processor) // ActivityPub endpoints
|
activityPubModule = api.NewActivityPub(state.DB, processor) // ActivityPub endpoints
|
||||||
webModule = web.New(state.DB, processor) // web pages + user profiles + settings panels etc
|
webModule = web.New(state.DB, processor) // web pages + user profiles + settings panels etc
|
||||||
|
|
||||||
|
nollamas = middleware.NoLLaMas(state.DB)
|
||||||
)
|
)
|
||||||
|
|
||||||
// these should be routed in order
|
// these should be routed in order
|
||||||
|
|
@ -271,7 +273,7 @@ var Start action.GTSAction = func(ctx context.Context) error {
|
||||||
nodeInfoModule.Route(route)
|
nodeInfoModule.Route(route)
|
||||||
activityPubModule.Route(route)
|
activityPubModule.Route(route)
|
||||||
activityPubModule.RoutePublicKey(route)
|
activityPubModule.RoutePublicKey(route)
|
||||||
webModule.Route(route)
|
webModule.Route(route, nollamas)
|
||||||
|
|
||||||
// Create background cleaner.
|
// Create background cleaner.
|
||||||
cleaner := cleaner.New(state)
|
cleaner := cleaner.New(state)
|
||||||
|
|
|
||||||
|
|
@ -18,25 +18,39 @@
|
||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"crypto/sha512"
|
||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
|
"crypto/x509"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"hash"
|
"hash"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"codeberg.org/gruf/go-byteutil"
|
"codeberg.org/gruf/go-byteutil"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
|
"github.com/superseriousbusiness/gotosocial/internal/db"
|
||||||
"github.com/superseriousbusiness/gotosocial/internal/oauth"
|
"github.com/superseriousbusiness/gotosocial/internal/oauth"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed challenge.html
|
func NoLLaMas(db db.DB) gin.HandlerFunc {
|
||||||
var challengeHTML []byte
|
instance, err := db.GetInstanceAccount(context.Background(), "")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
func NoLLaMas() gin.HandlerFunc {
|
// Generate seed hash from
|
||||||
|
// this instance private key.
|
||||||
|
priv := instance.PrivateKey
|
||||||
|
bpriv := x509.MarshalPKCS1PrivateKey(priv)
|
||||||
|
seed := sha512.Sum512(bpriv)
|
||||||
|
|
||||||
|
// Configure nollamas.
|
||||||
var nollamas nollamas
|
var nollamas nollamas
|
||||||
|
nollamas.seed = seed[:]
|
||||||
|
nollamas.ttl = time.Hour
|
||||||
|
nollamas.diff = 4
|
||||||
return nollamas.Serve
|
return nollamas.Serve
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -91,9 +105,8 @@ func (m *nollamas) Serve(c *gin.Context) {
|
||||||
// Check for a provided success token.
|
// Check for a provided success token.
|
||||||
cookie, _ := c.Cookie("gts-nollamas")
|
cookie, _ := c.Cookie("gts-nollamas")
|
||||||
|
|
||||||
if len(cookie) == 0 || len(cookie) > encodedHashLen {
|
if len(cookie) > encodedHashLen {
|
||||||
// If they provide no cookie, or
|
// Clearly invalid cookie, just
|
||||||
// obviously wrong cookie, just
|
|
||||||
// present them with new challenge.
|
// present them with new challenge.
|
||||||
m.renderChallenge(c, challenge)
|
m.renderChallenge(c, challenge)
|
||||||
return
|
return
|
||||||
|
|
@ -112,9 +125,11 @@ func (m *nollamas) Serve(c *gin.Context) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check headers to see if is in-progress challenge.
|
// Check query to see if an in-progress
|
||||||
nonce := c.Request.Header.Get("X-NoLLaMas-Solution")
|
// challenge solution has been provided.
|
||||||
if nonce == "" {
|
query := c.Request.URL.Query()
|
||||||
|
nonce := query.Get("nollamas_solution")
|
||||||
|
if nonce == "" || len(nonce) > 20 {
|
||||||
|
|
||||||
// No attempted solution, just
|
// No attempted solution, just
|
||||||
// present them with new challenge.
|
// present them with new challenge.
|
||||||
|
|
@ -134,15 +149,19 @@ func (m *nollamas) Serve(c *gin.Context) {
|
||||||
// Check that the first 'diff'
|
// Check that the first 'diff'
|
||||||
// many chars are indeed zeroes.
|
// many chars are indeed zeroes.
|
||||||
for i := range m.diff {
|
for i := range m.diff {
|
||||||
if subtle.ConstantTimeByteEq(solution[i], '0') == 0 {
|
if solution[i] != '0' {
|
||||||
|
|
||||||
// They failed challenge,
|
// They failed challenge,
|
||||||
// present them fail page.
|
// re-present challenge page.
|
||||||
m.renderFail(c)
|
m.renderChallenge(c, challenge)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Drop the solution from query.
|
||||||
|
query.Del("nollamas_solution")
|
||||||
|
c.Request.URL.RawQuery = query.Encode()
|
||||||
|
|
||||||
// They passed the challenge! Set success
|
// They passed the challenge! Set success
|
||||||
// token cookie and allow them to continue.
|
// token cookie and allow them to continue.
|
||||||
c.SetCookie("gts-nollamas", token, int(m.ttl/time.Second),
|
c.SetCookie("gts-nollamas", token, int(m.ttl/time.Second),
|
||||||
|
|
@ -156,21 +175,11 @@ func (m *nollamas) renderChallenge(c *gin.Context, challenge string) {
|
||||||
// our challenge page.
|
// our challenge page.
|
||||||
c.Abort()
|
c.Abort()
|
||||||
|
|
||||||
// Set the challenge we expect them to use in header.
|
// Write the templated challenge HTML response to client.
|
||||||
c.Request.Header.Set("X-NoLLaMas-Challenge", challenge)
|
c.HTML(http.StatusOK, "nollamas.tmpl", map[string]any{
|
||||||
c.Request.Header.Set("X-NoLLaMas-Difficulty", strconv.FormatUint(uint64(m.diff), 10))
|
"challenge": challenge,
|
||||||
|
"difficulty": m.diff,
|
||||||
// Write the challenge HTML response to client.
|
})
|
||||||
apiutil.Data(c, http.StatusOK, "text/html", challengeHTML)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *nollamas) renderFail(c *gin.Context) {
|
|
||||||
// Don't pass to further
|
|
||||||
// handlers, they only get
|
|
||||||
// our failure page.
|
|
||||||
c.Abort()
|
|
||||||
|
|
||||||
apiutil.Data(c, http.StatusOK, apiutil.AppJSON, []byte(`{"error": "failed nollamas challenge"}`))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *nollamas) token(c *gin.Context, hash hash.Hash) string {
|
func (m *nollamas) token(c *gin.Context, hash hash.Hash) string {
|
||||||
|
|
@ -201,7 +210,7 @@ func (m *nollamas) token(c *gin.Context, hash hash.Hash) string {
|
||||||
byte(now),
|
byte(now),
|
||||||
})
|
})
|
||||||
|
|
||||||
// Finally append unique client request data.
|
// Finally, append unique client request data.
|
||||||
userAgent := c.Request.Header.Get("User-Agent")
|
userAgent := c.Request.Header.Get("User-Agent")
|
||||||
_, _ = hash.Write(byteutil.S2B(userAgent))
|
_, _ = hash.Write(byteutil.S2B(userAgent))
|
||||||
clientIP := c.ClientIP()
|
clientIP := c.ClientIP()
|
||||||
|
|
@ -210,18 +219,3 @@ func (m *nollamas) token(c *gin.Context, hash hash.Hash) string {
|
||||||
// Return hex encoded hash output.
|
// Return hex encoded hash output.
|
||||||
return hex.EncodeToString(hash.Sum(nil))
|
return hex.EncodeToString(hash.Sum(nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
// appendTime will append time as seconds in binary.
|
|
||||||
// func appendTime(b []byte, t time.Time) []byte {
|
|
||||||
// sec := t.Unix()
|
|
||||||
// return append(b,
|
|
||||||
// byte(sec>>56),
|
|
||||||
// byte(sec>>48),
|
|
||||||
// byte(sec>>40),
|
|
||||||
// byte(sec>>32),
|
|
||||||
// byte(sec>>24),
|
|
||||||
// byte(sec>>16),
|
|
||||||
// byte(sec>>8),
|
|
||||||
// byte(sec),
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
|
|
|
||||||
|
|
@ -5,43 +5,6 @@
|
||||||
<title>Verifying...</title>
|
<title>Verifying...</title>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<style>
|
|
||||||
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@480&display=swap');
|
|
||||||
@media (prefers-color-scheme: light) {
|
|
||||||
:root {
|
|
||||||
--color-1: #f9fafb;
|
|
||||||
--color-2: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
:root {
|
|
||||||
--color-1: #f5a9b8;
|
|
||||||
--color-2: #000000;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@media (prefers-color-scheme: no-preference) {
|
|
||||||
:root {
|
|
||||||
--color-1: #f9fafb;
|
|
||||||
--color-2: #2563eb;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
html, body {
|
|
||||||
height: 100%;
|
|
||||||
margin: 0;
|
|
||||||
color: var(--color-1);
|
|
||||||
background-color: var(--color-2);
|
|
||||||
font-family: "IBM Plex Sans", sans-serif;
|
|
||||||
font-optical-sizing: auto;
|
|
||||||
font-weight: 480;
|
|
||||||
font-style: normal;
|
|
||||||
font-variation-settings: "wdth" 100;
|
|
||||||
font-size: 120%;
|
|
||||||
}
|
|
||||||
.hidden {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
|
@ -56,13 +19,15 @@
|
||||||
// Define our worker task func.
|
// Define our worker task func.
|
||||||
const workerTask = function() {
|
const workerTask = function() {
|
||||||
onmessage = async function(e) {
|
onmessage = async function(e) {
|
||||||
|
console.log('worker started');
|
||||||
|
|
||||||
const challenge = e.data.challenge;
|
const challenge = e.data.challenge;
|
||||||
const textEncoder = new TextEncoder();
|
const textEncoder = new TextEncoder();
|
||||||
|
|
||||||
// Get difficult and generate the expected
|
// Get difficulty and generate the expected
|
||||||
// zero ASCII prefix to check for in hashes.
|
// zero ASCII prefix to check for in hashes.
|
||||||
const difficultyStr = e.data.difficulty;
|
const difficultyStr = e.data.difficulty;
|
||||||
const difficulty = parseInt(diffStr, 10);
|
const difficulty = parseInt(difficultyStr, 10);
|
||||||
const zeroPrefix = '0'.repeat(difficulty);
|
const zeroPrefix = '0'.repeat(difficulty);
|
||||||
|
|
||||||
let nonce = 0;
|
let nonce = 0;
|
||||||
|
|
@ -82,14 +47,8 @@
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send status updates.
|
|
||||||
if (i % 1000 == 0) {
|
|
||||||
postMessage({nonce: nonce});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Iter.
|
// Iter.
|
||||||
i++;
|
nonce++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -99,47 +58,27 @@
|
||||||
{ type: 'application/javascript' });
|
{ type: 'application/javascript' });
|
||||||
const workerTaskURL = URL.createObjectURL(workerTaskBlob);
|
const workerTaskURL = URL.createObjectURL(workerTaskBlob);
|
||||||
|
|
||||||
const req = new XMLHttpRequest();
|
const challenge = '{{ .challenge }}';
|
||||||
req.open('GET', window.location.href, false);
|
const difficulty = '{{ .difficulty }}';
|
||||||
req.send(null);
|
console.log('challenge:', challenge);
|
||||||
|
console.log('difficulty:', difficulty);
|
||||||
// Read the incoming request headers for our challenge information.
|
|
||||||
const challenge = req.getResponseHeader('X-NoLLaMas-Challenge');
|
|
||||||
const difficulty = req.getResponseHeader('X-NoLLaMas-Difficulty');
|
|
||||||
console.log('received challenge:${challenge} difficulty:${difficulty}');
|
|
||||||
|
|
||||||
// Prepare the worker with task function.
|
// Prepare the worker with task function.
|
||||||
const worker = new Worker(workerTaskURL);
|
const worker = new Worker(workerTaskURL);
|
||||||
|
|
||||||
// Set the main worker function.
|
|
||||||
worker.onmessage = function (e) {
|
|
||||||
if (e.data.done) {
|
|
||||||
console.log("solution found for: ${e.data.nonce}");
|
|
||||||
|
|
||||||
fetch(window.location.href, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: { 'X-NoLLaMas-Solution': e.data.nonce },
|
|
||||||
credentials: 'include'
|
|
||||||
}).then(response => {
|
|
||||||
console.log("Server response:", response.status);
|
|
||||||
return response.text().then(() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = window.location.href;
|
|
||||||
}, 300);
|
|
||||||
});
|
|
||||||
}).catch(error => {
|
|
||||||
console.error('Error on refresh:', error);
|
|
||||||
});
|
|
||||||
} else if (e.data.progress) {
|
|
||||||
console.log("search progress: ${e.data.nonce}");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Post our challenge.
|
|
||||||
worker.postMessage({
|
worker.postMessage({
|
||||||
challenge: challenge,
|
challenge: challenge,
|
||||||
difficulty: difficulty,
|
difficulty: difficulty,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Set the main worker function.
|
||||||
|
worker.onmessage = function (e) {
|
||||||
|
if (e.data.done) {
|
||||||
|
console.log('solution found for:', e.data.nonce);
|
||||||
|
let url = new URL(window.location.href);
|
||||||
|
url.searchParams.append('nollamas_solution', e.data.nonce);
|
||||||
|
window.location.href = url.toString();
|
||||||
|
}
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
<div style="display: flex; align-items: center; justify-content: center; min-width: 100%; min-height: 100%;">
|
<div style="display: flex; align-items: center; justify-content: center; min-width: 100%; min-height: 100%;">
|
||||||
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 75%; text-align: center;">
|
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 75%; text-align: center;">
|
||||||
Loading…
Add table
Add a link
Reference in a new issue