Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@
**Learning:** `ip.IsPrivate()` and `ip.IsLoopback()` are not sufficient to block all local traffic. The concept of "Unspecified" addresses (all zeros) must also be explicitly handled when validating IPs for SSRF protection in Go.

**Prevention:** When implementing a safe dialer to prevent SSRF, always include `ip.IsUnspecified()` in the list of blocked IP characteristics, in addition to private, loopback, and link-local addresses.

- 2024-03-01: [XSS via go-readability] go-readability output is not safe for direct rendering and must be sanitized using bluemonday before outputting HTML.
38 changes: 34 additions & 4 deletions api/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"codeberg.org/readeck/go-readability/v2"
"github.com/mattn/godown"
"github.com/microcosm-cc/bluemonday"
"golang.org/x/net/html"
)

Expand Down Expand Up @@ -78,6 +79,15 @@ var (
*/
ReadabilityParser = readability.NewParser()

/**
* HTMLSanitizer is the shared instance of the bluemonday HTML sanitizer.
*
* It uses the UGCPolicy to allow common, safe HTML tags and attributes
* while stripping out potentially malicious content like scripts and
* event handlers (e.g., onclick, onerror) to prevent XSS attacks.
*/
HTMLSanitizer = bluemonday.UGCPolicy()

// httpClient used for fetching remote articles with timeouts and redirect policy
httpClient = &http.Client{
Transport: &http.Transport{
Expand Down Expand Up @@ -310,19 +320,29 @@ func Handler(w http.ResponseWriter, r *http.Request) {
*/
type formatHandler func(w http.ResponseWriter, article readability.Article, buf *bytes.Buffer)

/**
* sanitizeHTML strips malicious content from an HTML byte slice.
*/
func sanitizeHTML(content []byte) []byte {
return HTMLSanitizer.SanitizeBytes(content)
}

/**
* formatHTML renders the article using the standard HTML template.
* This is the default view for human consumption.
*/
func formatHTML(w http.ResponseWriter, article readability.Article, contentBuf *bytes.Buffer) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")

sanitizedContent := sanitizeHTML(contentBuf.Bytes())

// inject safe HTML content
data := struct {
Title string
Content template.HTML
}{
Title: article.Title(),
Content: template.HTML(contentBuf.String()),
Content: template.HTML(sanitizedContent),
}
if err := DefaultTemplate.Execute(w, data); err != nil {
// at this point, we can't write a JSON error, so we log it
Expand All @@ -336,7 +356,11 @@ func formatHTML(w http.ResponseWriter, article readability.Article, contentBuf *
*/
func formatMarkdown(w http.ResponseWriter, _ readability.Article, buf *bytes.Buffer) {
w.Header().Set("Content-Type", "text/markdown")
if err := godown.Convert(w, buf, nil); err != nil {

sanitizedContent := sanitizeHTML(buf.Bytes())
sanitizedBuf := bytes.NewBuffer(sanitizedContent)

if err := godown.Convert(w, sanitizedBuf, nil); err != nil {
log.Printf("error converting to markdown: %v", err)
}
}
Expand All @@ -347,9 +371,12 @@ func formatMarkdown(w http.ResponseWriter, _ readability.Article, buf *bytes.Buf
*/
func formatJSON(w http.ResponseWriter, article readability.Article, buf *bytes.Buffer) {
w.Header().Set("Content-Type", "application/json")

sanitizedContent := sanitizeHTML(buf.Bytes())

if err := json.NewEncoder(w).Encode(map[string]string{
"title": article.Title(),
"content": buf.String(),
"content": string(sanitizedContent),
}); err != nil {
log.Printf("error encoding json: %v", err)
}
Expand All @@ -360,7 +387,10 @@ func formatJSON(w http.ResponseWriter, article readability.Article, buf *bytes.B
*/
func formatText(w http.ResponseWriter, _ readability.Article, buf *bytes.Buffer) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := w.Write(buf.Bytes()); err != nil {

sanitizedContent := sanitizeHTML(buf.Bytes())

if _, err := w.Write(sanitizedContent); err != nil {
log.Printf("error writing text response: %v", err)
}
}
Expand Down
39 changes: 39 additions & 0 deletions api/xss_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package handler

import (
"bytes"
"strings"
"testing"
)

// mockArticle implements readability.Article for testing
type mockArticle struct {
title string
html string
}

func (m mockArticle) Title() string {
return m.title
}

func (m mockArticle) RenderHTML(w *bytes.Buffer) error {
w.WriteString(m.html)
return nil
}

func TestXSSHTMLSanitization(t *testing.T) {
// A mock article with malicious content
maliciousHTML := `<p>Hello</p><script>alert("xss")</script><img src="x" onerror="alert('xss')">`
article := mockArticle{title: "Test", html: maliciousHTML}

buf := &bytes.Buffer{}
if err := article.RenderHTML(buf); err != nil {
t.Fatalf("failed to render html: %v", err)
}

sanitizedHTML := sanitizeHTML(buf.Bytes())

if strings.Contains(string(sanitizedHTML), "<script>") || strings.Contains(string(sanitizedHTML), "onerror") {
t.Errorf("HTML was not sanitized correctly: %s", sanitizedHTML)
}
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@ go 1.24.7
require (
codeberg.org/readeck/go-readability/v2 v2.1.1
github.com/mattn/godown v0.0.1
github.com/microcosm-cc/bluemonday v1.0.27
golang.org/x/net v0.48.0
)

require (
github.com/andybalholm/cascadia v1.3.3 // indirect
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c // indirect
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
golang.org/x/text v0.32.0 // indirect
)
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
codeberg.org/readeck/go-readability/v2 v2.1.0 h1:1T72CzXu4nrZr/DA1A5fAkaVsTMx/LSALPkSSZY+NWI=
codeberg.org/readeck/go-readability/v2 v2.1.0/go.mod h1:x3WG9GpWWnkRb7ajP1NmOKSHbafxNUb736lrDZXeXrs=
codeberg.org/readeck/go-readability/v2 v2.1.1 h1:1tEwxFuUqDRP5JABzDHXGWRx5p9S7TElS3U8qQwXC5Y=
codeberg.org/readeck/go-readability/v2 v2.1.1/go.mod h1:x3WG9GpWWnkRb7ajP1NmOKSHbafxNUb736lrDZXeXrs=
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
Expand All @@ -18,12 +18,16 @@ github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c/go.mod h1:oVDCh3qjJM
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7wCLuiqMaUh5SJkkzI2gDs+FgLs=
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/godown v0.0.1 h1:39uk50ufLVQFs0eapIJVX5fCS74a1Fs2g5f1MVqIHdE=
github.com/mattn/godown v0.0.1/go.mod h1:/ivCKurgV/bx6yqtP/Jtc2Xmrv3beCYBvlfAUl4X5g4=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
Expand Down