Fix the three medium audit findings

- /group ticket del: only the chat creator may remove a group registration
- /node: always dial user-supplied node hosts through the netguard client;
  drop the https://127.0.0.1 prefix exemption
- /app/@{username}: accept only username characters, render the greeting as
  text, add basic security headers

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-14 18:18:41 +00:00
co-authored by Claude Sonnet 5.5
parent 7f89896a6c
commit 8b8b0fa369
7 changed files with 124 additions and 23 deletions
+14
View File
@@ -32,6 +32,7 @@ func NewServer(address string) *Server {
httpServer: srv,
}
apiServer.router = mux.NewRouter()
apiServer.router.Use(securityHeaders)
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[api] Server started at %s", address)
@@ -76,3 +77,16 @@ func WriteResponse(writer http.ResponseWriter, response interface{}) error {
_, err = writer.Write(jsonResponse)
return err
}
// securityHeaders sets the headers that need no change to the pages. A
// stricter Content-Security-Policy would need the inline scripts of the
// userpage templates to move out first.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Content-Security-Policy", "object-src 'none'; base-uri 'none'")
next.ServeHTTP(w, r)
})
}
+2 -2
View File
@@ -270,7 +270,7 @@
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
document.querySelector('#greeting').textContent = "{{.Username}}@ln.tips";
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
@@ -368,7 +368,7 @@
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
document.querySelector('#greeting').textContent = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
+14
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"html/template"
"net/http"
"regexp"
"strings"
"time"
@@ -27,6 +28,11 @@ func New(b *telegram.TipBot) Service {
}
}
// validUsername matches Telegram usernames and the anon id forms (numeric,
// 0x... and 1x...) the LNURL server accepts. The path variable is reflected
// into a page that handles payments, so nothing else is rendered.
var validUsername = regexp.MustCompile(`^[a-z0-9_]{1,64}$`)
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
//go:embed static
@@ -70,6 +76,10 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/@<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering page of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
@@ -95,6 +105,10 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/app/<username>
username := strings.ToLower(mux.Vars(r)["username"])
if !validUsername.MatchString(username) {
http.Error(w, "404 page not found", http.StatusNotFound)
return
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering webapp of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
+42
View File
@@ -0,0 +1,42 @@
package userpage
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/mux"
)
func serve(path string) *httptest.ResponseRecorder {
r := mux.NewRouter()
r.HandleFunc("/app/@{username}", Service{}.UserWebAppHandler)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec
}
func TestWebAppRejectsMarkupInUsername(t *testing.T) {
for _, p := range []string{
"/app/@%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E",
"/app/@a%22%3Balert(1)%2F%2F",
"/app/@" + strings.Repeat("a", 65),
} {
rec := serve(p)
if rec.Code == http.StatusOK || strings.Contains(rec.Body.String(), "onerror") {
t.Errorf("%s: code %d, body %q", p, rec.Code, rec.Body.String())
}
}
}
func TestWebAppRendersValidUsernameAsText(t *testing.T) {
rec := serve("/app/@alice_1")
if rec.Code != http.StatusOK {
t.Fatalf("code %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, `textContent = "alice_1@ln.tips"`) || strings.Contains(body, "#greeting').innerHTML") {
t.Errorf("greeting is not set as text")
}
}
+10 -21
View File
@@ -16,7 +16,6 @@ import (
"net/http"
"net/url"
"strings"
"time"
)
// Much of this is from github.com/fiatjaf/makeinvoice
@@ -30,7 +29,6 @@ type LNDParams struct {
}
func (l LNDParams) getCert() []byte { return l.Cert }
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type LNBitsParams struct {
@@ -41,12 +39,10 @@ type LNBitsParams struct {
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
type BackendParams interface {
getCert() []byte
isTor() bool
isLocal() bool
}
type Params struct {
@@ -65,21 +61,14 @@ type CheckInvoiceParams struct {
Status string
}
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
var client *http.Client
if !useProxy {
// a nil Transport would make the TLS setup below panic
client = &http.Client{
Timeout: 10 * time.Second,
Transport: http.DefaultTransport.(*http.Transport).Clone(),
}
} else {
var err error
client, err = network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
// SetupHttpClient returns the client for a user-supplied node. The host comes
// from a Telegram user, so it always goes through network.GetClient: that
// refuses non-public addresses (netguard) and uses the Tor proxy when one is
// configured. There is deliberately no exemption for local hosts.
func SetupHttpClient(cert []byte) (*http.Client, error) {
client, err := network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
if client.Transport == nil {
client.Transport = http.DefaultTransport.(*http.Transport).Clone()
@@ -108,7 +97,7 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
@@ -244,7 +233,7 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
Client, err := SetupHttpClient(params.Backend.getCert())
if err != nil {
log.Errorf("%s", err.Error())
return CheckInvoiceParams{}, err
+32
View File
@@ -0,0 +1,32 @@
package satdress
import (
"net/http"
"net/http/httptest"
"testing"
)
// A node host chosen by a Telegram user must never reach loopback or private
// addresses, whatever the host string starts with.
func TestSetupHttpClientRefusesNonPublicHosts(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("request reached the loopback server: %s", r.URL)
}))
defer srv.Close()
client, err := SetupHttpClient(nil)
if err != nil {
t.Fatal(err)
}
for _, host := range []string{
srv.URL, // https://127.0.0.1:port, the old "local" prefix
"https://127.0.0.1:1@" + srv.Listener.Addr().String(),
"https://127.0.0.1@10.0.0.5",
"https://localhost:" + srv.URL[len("https://127.0.0.1:"):],
} {
if resp, err := client.Get(host); err == nil {
resp.Body.Close()
t.Errorf("%s was reachable", host)
}
}
}
+10
View File
@@ -427,6 +427,16 @@ func (bot TipBot) handleJoinTicketPayWall(ctx intercept.Context) (intercept.Cont
return ctx, err
}
func (bot TipBot) removeJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type == tb.ChatPrivate {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, fmt.Errorf("not in group")
}
// only the creator of the chat may remove its registration
user := LoadUser(ctx)
if !bot.isOwner(m.Chat, user.Telegram) {
return ctx, fmt.Errorf("not owner")
}
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).Delete(&Group{})
if tx.Error != nil {