Skip to content

Commit 3befd4d

Browse files
committed
fix(email): prevent header injection through notification subjects
Notification subjects include subscription names, which any API key holder can set. A name containing CR/LF could inject headers or replace the body and Content-Type of emails sent to the administrator. - Build the message in one helper shared by the TLS and STARTTLS paths - Strip line breaks from every header value - RFC 2047 encode the subject and sender name, which also fixes non-ASCII subjects - Add tests for injected headers and body, non-ASCII subjects and configured addresses
1 parent cec9485 commit 3befd4d

3 files changed

Lines changed: 113 additions & 24 deletions

File tree

‎.beads/issues.jsonl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@
3030
{"id":"subtrackr-xyz-vhy","title":"Add cleaning-up-stale-branches Claude Code skill","description":"Commit .claude/skills/cleaning-up-stale-branches/SKILL.md (already written and verified, uncommitted in working tree) as part of the next release branch.","status":"closed","priority":3,"issue_type":"task","owner":"191290+bscott@users.noreply.github.com","created_at":"2026-06-10T19:48:01.960181-07:00","created_by":"Brian Scott","updated_at":"2026-08-04T21:35:07.800106-07:00","closed_at":"2026-08-04T21:35:07.800106-07:00","close_reason":"Added verified stale-branch cleanup skill to v0.6.5"}
3131
{"id":"subtrackr-xyz-z1c","title":"Custom schedule intervals (#77, #75)","status":"closed","priority":2,"issue_type":"feature","owner":"191290+bscott@users.noreply.github.com","created_at":"2026-04-15T19:17:23.123268-07:00","created_by":"Brian Scott","updated_at":"2026-04-15T19:53:54.309102-07:00","closed_at":"2026-04-15T19:53:54.309102-07:00","close_reason":"Added custom schedule intervals with single dropdown UI - supports multi-year, biweekly, etc."}
3232
{"id":"subtrackr-xyz-z3x","title":"Password reset link poisoning via Host/X-Forwarded-Host","status":"in_progress","priority":0,"issue_type":"bug","owner":"brian@bscott.dev","created_at":"2026-11-02T11:40:48.034551-08:00","created_by":"Brian Scott","updated_at":"2026-11-02T11:40:57.31708-08:00"}
33+
{"id":"subtrackr-xyz-moc","title":"Email header injection via subscription name in notification subjects","status":"in_progress","priority":0,"issue_type":"bug","owner":"brian@bscott.dev","created_at":"2026-11-02T11:51:55.877953-08:00","created_by":"Brian Scott","updated_at":"2026-11-02T11:51:55.924344-08:00"}

‎internal/service/email.go‎

Lines changed: 38 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ import (
55
"crypto/tls"
66
"fmt"
77
"html/template"
8+
"mime"
89
"net/smtp"
10+
"strings"
911
"subtrackr/internal/models"
1012
)
1113

@@ -97,18 +99,7 @@ func (e *EmailService) SendEmail(subject, body string) error {
9799
return fmt.Errorf("failed to get data writer: %w", err)
98100
}
99101

100-
fromName := config.FromName
101-
if fromName == "" {
102-
fromName = "SubTrackr"
103-
}
104-
105-
message := fmt.Sprintf("From: %s <%s>\r\n", fromName, config.From)
106-
message += fmt.Sprintf("To: %s\r\n", config.To)
107-
message += fmt.Sprintf("Subject: %s\r\n", subject)
108-
message += "MIME-Version: 1.0\r\n"
109-
message += "Content-Type: text/html; charset=UTF-8\r\n"
110-
message += "\r\n"
111-
message += body
102+
message := buildEmailMessage(config, subject, body)
112103

113104
_, err = writer.Write([]byte(message))
114105
if err != nil {
@@ -154,18 +145,7 @@ func (e *EmailService) SendEmail(subject, body string) error {
154145
return fmt.Errorf("failed to get data writer: %w", err)
155146
}
156147

157-
fromName := config.FromName
158-
if fromName == "" {
159-
fromName = "SubTrackr"
160-
}
161-
162-
message := fmt.Sprintf("From: %s <%s>\r\n", fromName, config.From)
163-
message += fmt.Sprintf("To: %s\r\n", config.To)
164-
message += fmt.Sprintf("Subject: %s\r\n", subject)
165-
message += "MIME-Version: 1.0\r\n"
166-
message += "Content-Type: text/html; charset=UTF-8\r\n"
167-
message += "\r\n"
168-
message += body
148+
message := buildEmailMessage(config, subject, body)
169149

170150
_, err = writer.Write([]byte(message))
171151
if err != nil {
@@ -457,3 +437,37 @@ func (e *EmailService) SendCancellationReminder(subscription *models.Subscriptio
457437
subject := fmt.Sprintf("Cancellation Reminder: %s ends in %d %s", subscription.Name, daysUntilCancellation, daysText)
458438
return e.SendEmail(subject, buf.String())
459439
}
440+
441+
// headerLineBreaks matches characters that would end an email header line.
442+
var headerLineBreaks = strings.NewReplacer("\r\n", " ", "\r", " ", "\n", " ")
443+
444+
// sanitizeHeaderValue removes line breaks so a value cannot end its header
445+
// and inject new headers or a replacement body.
446+
func sanitizeHeaderValue(value string) string {
447+
return headerLineBreaks.Replace(value)
448+
}
449+
450+
// encodeHeaderText sanitizes free text for a header and RFC 2047 encodes it
451+
// when it contains non-ASCII characters.
452+
func encodeHeaderText(value string) string {
453+
return mime.QEncoding.Encode("utf-8", sanitizeHeaderValue(value))
454+
}
455+
456+
// buildEmailMessage renders the SMTP message. Subjects often contain
457+
// subscription names, which any API key holder can set, so every header value
458+
// is stripped of line breaks before it is written.
459+
func buildEmailMessage(config *models.SMTPConfig, subject, body string) string {
460+
fromName := config.FromName
461+
if fromName == "" {
462+
fromName = "SubTrackr"
463+
}
464+
465+
message := fmt.Sprintf("From: %s <%s>\r\n", encodeHeaderText(fromName), sanitizeHeaderValue(config.From))
466+
message += fmt.Sprintf("To: %s\r\n", sanitizeHeaderValue(config.To))
467+
message += fmt.Sprintf("Subject: %s\r\n", encodeHeaderText(subject))
468+
message += "MIME-Version: 1.0\r\n"
469+
message += "Content-Type: text/html; charset=UTF-8\r\n"
470+
message += "\r\n"
471+
message += body
472+
return message
473+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package service
2+
3+
import (
4+
"io"
5+
"mime"
6+
"net/mail"
7+
"strings"
8+
"subtrackr/internal/models"
9+
"testing"
10+
11+
"github.com/stretchr/testify/assert"
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
func testSMTPConfig() *models.SMTPConfig {
16+
return &models.SMTPConfig{From: "subtrackr@example.com", To: "admin@example.com", FromName: "SubTrackr"}
17+
}
18+
19+
// headersOf parses a rendered message and returns its headers and body.
20+
func headersOf(t *testing.T, message string) (mail.Header, string) {
21+
t.Helper()
22+
parsed, err := mail.ReadMessage(strings.NewReader(message))
23+
require.NoError(t, err)
24+
body, err := io.ReadAll(parsed.Body)
25+
require.NoError(t, err)
26+
return parsed.Header, string(body)
27+
}
28+
29+
func TestBuildEmailMessage_SubjectCannotInjectHeadersOrBody(t *testing.T) {
30+
// A subscription name planted through the API, as used in alert subjects.
31+
name := "Netflix\r\nBcc: victim@example.com\r\nContent-Type: text/plain\r\n\r\n<a href=https://attacker.example>Verify account</a>"
32+
subject := "High Cost Alert: " + name
33+
34+
message := buildEmailMessage(testSMTPConfig(), subject, "<p>real body</p>")
35+
header, body := headersOf(t, message)
36+
37+
assert.Empty(t, header.Get("Bcc"))
38+
assert.Equal(t, "text/html; charset=UTF-8", header.Get("Content-Type"))
39+
assert.Equal(t, "<p>real body</p>", body)
40+
decoded, err := new(mime.WordDecoder).DecodeHeader(header.Get("Subject"))
41+
require.NoError(t, err)
42+
assert.NotContains(t, decoded, "\r")
43+
assert.NotContains(t, decoded, "\n")
44+
assert.Contains(t, decoded, "Netflix")
45+
}
46+
47+
func TestBuildEmailMessage_EncodesNonASCIISubject(t *testing.T) {
48+
message := buildEmailMessage(testSMTPConfig(), "Renewal Reminder: Café Société renews in 3 days", "x")
49+
header, _ := headersOf(t, message)
50+
51+
assert.True(t, strings.HasPrefix(header.Get("Subject"), "=?utf-8?q?"), header.Get("Subject"))
52+
decoded, err := new(mime.WordDecoder).DecodeHeader(header.Get("Subject"))
53+
require.NoError(t, err)
54+
assert.Equal(t, "Renewal Reminder: Café Société renews in 3 days", decoded)
55+
}
56+
57+
func TestBuildEmailMessage_ASCIISubjectUnchanged(t *testing.T) {
58+
message := buildEmailMessage(testSMTPConfig(), "Renewal Reminder: Netflix renews in 3 days", "x")
59+
header, _ := headersOf(t, message)
60+
61+
assert.Equal(t, "Renewal Reminder: Netflix renews in 3 days", header.Get("Subject"))
62+
assert.Equal(t, "SubTrackr <subtrackr@example.com>", header.Get("From"))
63+
assert.Equal(t, "admin@example.com", header.Get("To"))
64+
}
65+
66+
func TestBuildEmailMessage_SanitizesConfiguredAddresses(t *testing.T) {
67+
config := testSMTPConfig()
68+
config.FromName = "Sub\r\nX-Injected: 1"
69+
config.To = "admin@example.com\r\nX-Injected: 2"
70+
71+
header, _ := headersOf(t, buildEmailMessage(config, "s", "x"))
72+
73+
assert.Empty(t, header.Get("X-Injected"))
74+
}

0 commit comments

Comments
 (0)