mirror of
				https://github.com/superseriousbusiness/gotosocial.git
				synced 2025-10-30 21:42:24 -05:00 
			
		
		
		
	start adding proof of work middleware
This commit is contained in:
		
					parent
					
						
							
								6a6a499333
							
						
					
				
			
			
				commit
				
					
						2442c6fc41
					
				
			
		
					 2 changed files with 385 additions and 0 deletions
				
			
		
							
								
								
									
										158
									
								
								internal/middleware/challenge.html
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										158
									
								
								internal/middleware/challenge.html
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,158 @@ | |||
| <!DOCTYPE html> | ||||
| <html> | ||||
| 
 | ||||
| <head> | ||||
|     <title>Verifying...</title> | ||||
|     <meta charset="utf-8"> | ||||
|     <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> | ||||
| 
 | ||||
| <body> | ||||
|     <script> | ||||
|         document.addEventListener('DOMContentLoaded', function() { | ||||
|             const jsOnlyElements = document.querySelectorAll('.hidden'); | ||||
|             jsOnlyElements.forEach(el => { | ||||
|                 el.classList.remove('hidden'); | ||||
|             }); | ||||
|         }); | ||||
| 
 | ||||
|         // Define our worker task func. | ||||
|         const workerTask = function() { | ||||
|             onmessage = async function(e) { | ||||
|                 const challenge = e.data.challenge; | ||||
|                 const textEncoder = new TextEncoder(); | ||||
| 
 | ||||
|                 // Get difficult and generate the expected | ||||
|                 // zero ASCII prefix to check for in hashes. | ||||
|                 const difficultyStr = e.data.difficulty; | ||||
|                 const difficulty = parseInt(diffStr, 10); | ||||
|                 const zeroPrefix = '0'.repeat(difficulty); | ||||
| 
 | ||||
|                 let nonce = 0; | ||||
|                 while (true) { | ||||
|                     // Create possible solution string from challenge + nonce. | ||||
|                     const solution = textEncoder.encode(challenge + nonce.toString()); | ||||
| 
 | ||||
|                     // Generate SHA256 hashsum of solution string and hex encode the result. | ||||
|                     const hashBuffer = await crypto.subtle.digest('SHA-256', solution); | ||||
|                     const hashArray = Array.from(new Uint8Array(hashBuffer)); | ||||
|                     const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); | ||||
| 
 | ||||
|                     // Check if the hex encoded hash has | ||||
|                     // difficulty defined zeroes prefix. | ||||
|                     if (hashHex.startsWith(zeroPrefix)) { | ||||
|                         postMessage({ nonce: nonce, done: true }); | ||||
|                         break; | ||||
|                     } | ||||
| 
 | ||||
|                     // Send status updates. | ||||
|                     if (i % 1000 == 0) { | ||||
|                         postMessage({nonce: nonce}); | ||||
|                         continue; | ||||
|                     } | ||||
| 
 | ||||
|                     // Iter. | ||||
|                     i++; | ||||
|                 } | ||||
|             } | ||||
|         }; | ||||
| 
 | ||||
|         // Convert the worker task function to call-able base64 blob URL. | ||||
|         const workerTaskBlob = new Blob(['(',workerTask.toString(),')()'],  | ||||
|             { type: 'application/javascript' }); | ||||
|         const workerTaskURL = URL.createObjectURL(workerTaskBlob); | ||||
| 
 | ||||
| 		const req = new XMLHttpRequest(); | ||||
|         req.open('GET', window.location.href, false); | ||||
|         req.send(null); | ||||
| 
 | ||||
|         // 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. | ||||
| 		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({ | ||||
| 			challenge: challenge, | ||||
| 			difficulty: difficulty, | ||||
|         }); | ||||
|     </script> | ||||
|     <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;"> | ||||
|             <p class="hidden" style="margin-bottom: 0.25rem;"><svg fill="var(--color-1)" style="width: clamp(64px, 15%, 96px); height: auto;" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_d9Sa{transform-origin:center}.spinner_qQQY{animation:spinner_ZpfF 9s linear infinite}.spinner_pote{animation:spinner_ZpfF .75s linear infinite}@keyframes spinner_ZpfF{100%{transform:rotate(360deg)}}</style><path d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,20a9,9,0,1,1,9-9A9,9,0,0,1,12,21Z"/><rect class="spinner_d9Sa spinner_qQQY" x="11" y="6" rx="1" width="2" height="7"/><rect class="spinner_d9Sa spinner_pote" x="11" y="11" rx="1" width="2" height="9"/></svg></p> | ||||
|             <p class="hidden" style="margin-top: 0.5rem; max-width: 24rem;">One moment while we verify your connection...</p> | ||||
|             <noscript> | ||||
|                 <p style="display: flex; align-items: center; gap: 0.5rem;"> | ||||
|                     <svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M12 10V13" stroke="#ff7800" stroke-width="2" stroke-linecap="round"></path><path d="M12 16V15.9888" stroke="#ff7800" stroke-width="2" stroke-linecap="round"></path><path d="M10.2518 5.147L3.6508 17.0287C2.91021 18.3618 3.87415 20 5.39912 20H18.6011C20.126 20 21.09 18.3618 20.3494 17.0287L13.7484 5.147C12.9864 3.77538 11.0138 3.77538 10.2518 5.147Z" stroke="#ff7800" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></g></svg> | ||||
|                     Javascript must be enabled to verify your browser. | ||||
|                 </p> | ||||
|             </noscript> | ||||
|         </div> | ||||
|     </div> | ||||
| </body> | ||||
| 
 | ||||
| </html> | ||||
							
								
								
									
										227
									
								
								internal/middleware/nollamas.go
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										227
									
								
								internal/middleware/nollamas.go
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,227 @@ | |||
| // GoToSocial | ||||
| // Copyright (C) GoToSocial Authors admin@gotosocial.org | ||||
| // SPDX-License-Identifier: AGPL-3.0-or-later | ||||
| // | ||||
| // This program is free software: you can redistribute it and/or modify | ||||
| // it under the terms of the GNU Affero General Public License as published by | ||||
| // the Free Software Foundation, either version 3 of the License, or | ||||
| // (at your option) any later version. | ||||
| // | ||||
| // This program is distributed in the hope that it will be useful, | ||||
| // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
| // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
| // GNU Affero General Public License for more details. | ||||
| // | ||||
| // You should have received a copy of the GNU Affero General Public License | ||||
| // along with this program.  If not, see <http://www.gnu.org/licenses/>. | ||||
| 
 | ||||
| package middleware | ||||
| 
 | ||||
| import ( | ||||
| 	"crypto/sha256" | ||||
| 	"crypto/subtle" | ||||
| 	"encoding/hex" | ||||
| 	"hash" | ||||
| 	"net/http" | ||||
| 	"strconv" | ||||
| 	"time" | ||||
| 
 | ||||
| 	"codeberg.org/gruf/go-byteutil" | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util" | ||||
| 	"github.com/superseriousbusiness/gotosocial/internal/oauth" | ||||
| ) | ||||
| 
 | ||||
| //go:embed challenge.html | ||||
| var challengeHTML []byte | ||||
| 
 | ||||
| func NoLLaMas() gin.HandlerFunc { | ||||
| 	var nollamas nollamas | ||||
| 	return nollamas.Serve | ||||
| } | ||||
| 
 | ||||
| // i.e. outputted hash slice length. | ||||
| const hashLen = sha256.BlockSize | ||||
| 
 | ||||
| // i.e. hex.EncodedLen(hashLen). | ||||
| const encodedHashLen = 2 * hashLen | ||||
| 
 | ||||
| func newHash() hash.Hash { return sha256.New() } | ||||
| 
 | ||||
| type nollamas struct { | ||||
| 	seed []byte // securely hashed instance private key | ||||
| 	ttl  time.Duration | ||||
| 	diff uint8 | ||||
| } | ||||
| 
 | ||||
| func (m *nollamas) Serve(c *gin.Context) { | ||||
| 	if c.Request.Method != http.MethodGet { | ||||
| 		// Only interested in protecting | ||||
| 		// crawlable 'GET' endpoints. | ||||
| 		c.Next() | ||||
| 		return | ||||
| 	} | ||||
| 
 | ||||
| 	if _, ok := c.Get(oauth.SessionAuthorizedToken); ok { | ||||
| 		// Don't guard against requests | ||||
| 		// providing valid OAuth tokens. | ||||
| 		c.Next() | ||||
| 		return | ||||
| 	} | ||||
| 
 | ||||
| 	// Get new hasher. | ||||
| 	hash := newHash() | ||||
| 
 | ||||
| 	// Reset hash. | ||||
| 	hash.Reset() | ||||
| 
 | ||||
| 	// Generate a unique token for | ||||
| 	// this request only valid for | ||||
| 	// a period of now +- m.ttl. | ||||
| 	token := m.token(c, hash) | ||||
| 
 | ||||
| 	// For unique challenge string just use a | ||||
| 	// portion of their unique 'success' token. | ||||
| 	// SHA256 is not yet cracked, this is not an | ||||
| 	// application of a hash requiring serious | ||||
| 	// cryptographic security and it rotates on | ||||
| 	// a TTL basis, so it should be fine. | ||||
| 	challenge := token[:len(token)/2] | ||||
| 
 | ||||
| 	// Check for a provided success token. | ||||
| 	cookie, _ := c.Cookie("gts-nollamas") | ||||
| 
 | ||||
| 	if len(cookie) == 0 || len(cookie) > encodedHashLen { | ||||
| 		// If they provide no cookie, or | ||||
| 		// obviously wrong cookie, just | ||||
| 		// present them with new challenge. | ||||
| 		m.renderChallenge(c, challenge) | ||||
| 		return | ||||
| 	} | ||||
| 
 | ||||
| 	// Check whether passed cookie | ||||
| 	// is the expected success token. | ||||
| 	if subtle.ConstantTimeCompare( | ||||
| 		byteutil.S2B(token), | ||||
| 		byteutil.S2B(cookie), | ||||
| 	) == 1 { | ||||
| 
 | ||||
| 		// They passed us a valid, expected | ||||
| 		// token. They already passed checks. | ||||
| 		c.Next() | ||||
| 		return | ||||
| 	} | ||||
| 
 | ||||
| 	// Check headers to see if is in-progress challenge. | ||||
| 	nonce := c.Request.Header.Get("X-NoLLaMas-Solution") | ||||
| 	if nonce == "" { | ||||
| 
 | ||||
| 		// No attempted solution, just | ||||
| 		// present them with new challenge. | ||||
| 		m.renderChallenge(c, challenge) | ||||
| 		return | ||||
| 	} | ||||
| 
 | ||||
| 	// Reset hash. | ||||
| 	hash.Reset() | ||||
| 
 | ||||
| 	// Hash and encode input challenge with | ||||
| 	// proposed nonce as a possible solution. | ||||
| 	_, _ = hash.Write(byteutil.S2B(challenge)) | ||||
| 	_, _ = hash.Write(byteutil.S2B(nonce)) | ||||
| 	solution := hex.AppendEncode(nil, hash.Sum(nil)) | ||||
| 
 | ||||
| 	// Check that the first 'diff' | ||||
| 	// many chars are indeed zeroes. | ||||
| 	for i := range m.diff { | ||||
| 		if subtle.ConstantTimeByteEq(solution[i], '0') == 0 { | ||||
| 
 | ||||
| 			// They failed challenge, | ||||
| 			// present them fail page. | ||||
| 			m.renderFail(c) | ||||
| 			return | ||||
| 		} | ||||
| 	} | ||||
| 
 | ||||
| 	// They passed the challenge! Set success | ||||
| 	// token cookie and allow them to continue. | ||||
| 	c.SetCookie("gts-nollamas", token, int(m.ttl/time.Second), | ||||
| 		"", "", false, false) | ||||
| 	c.Next() | ||||
| } | ||||
| 
 | ||||
| func (m *nollamas) renderChallenge(c *gin.Context, challenge string) { | ||||
| 	// Don't pass to further | ||||
| 	// handlers, they only get | ||||
| 	// our challenge page. | ||||
| 	c.Abort() | ||||
| 
 | ||||
| 	// Set the challenge we expect them to use in header. | ||||
| 	c.Request.Header.Set("X-NoLLaMas-Challenge", challenge) | ||||
| 	c.Request.Header.Set("X-NoLLaMas-Difficulty", strconv.FormatUint(uint64(m.diff), 10)) | ||||
| 
 | ||||
| 	// 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 { | ||||
| 	// Use our safe, unique input seed which | ||||
| 	// is already hashed, but will get rehashed. | ||||
| 	// This ensures we don't leak private keys, | ||||
| 	// but also we have cryptographically safe | ||||
| 	// deterministic tokens for comparisons. | ||||
| 	_, _ = hash.Write(m.seed) | ||||
| 
 | ||||
| 	// Include difficulty level in | ||||
| 	// hash input data so if config | ||||
| 	// changes then token invalidates. | ||||
| 	_, _ = hash.Write([]byte{m.diff}) | ||||
| 
 | ||||
| 	// Also seed the generated input with | ||||
| 	// current time rounded to TTL, so with | ||||
| 	// our single comparison handles expiries. | ||||
| 	now := time.Now().Round(m.ttl).Unix() | ||||
| 	_, _ = hash.Write([]byte{ | ||||
| 		byte(now >> 56), | ||||
| 		byte(now >> 48), | ||||
| 		byte(now >> 40), | ||||
| 		byte(now >> 32), | ||||
| 		byte(now >> 24), | ||||
| 		byte(now >> 16), | ||||
| 		byte(now >> 8), | ||||
| 		byte(now), | ||||
| 	}) | ||||
| 
 | ||||
| 	// Finally append unique client request data. | ||||
| 	userAgent := c.Request.Header.Get("User-Agent") | ||||
| 	_, _ = hash.Write(byteutil.S2B(userAgent)) | ||||
| 	clientIP := c.ClientIP() | ||||
| 	_, _ = hash.Write(byteutil.S2B(clientIP)) | ||||
| 
 | ||||
| 	// Return hex encoded hash output. | ||||
| 	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), | ||||
| // 	) | ||||
| // } | ||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue