Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

Validate IndieAuth redirect_uri against client_id (#4909)

Gabe Kangas87575c9e70b9
diff --git a/activitypub/controllers/nodeinfo.go b/activitypub/controllers/nodeinfo.go
index 37c59007c1..390024a0fd 100644
--- a/activitypub/controllers/nodeinfo.go
+++ b/activitypub/controllers/nodeinfo.go
@@ -14,6 +14,13 @@ import (
log "github.com/sirupsen/logrus"
)
+const (
+ // softwareName is the name of this server software reported in node info responses.
+ softwareName = "owncast"
+ // protocolActivityPub is the federation protocol name reported in node info responses.
+ protocolActivityPub = "activitypub"
+)
+
// NodeInfoController returns the V1 node info response.
func NodeInfoController(w http.ResponseWriter, r *http.Request) {
type links struct {
@@ -101,7 +108,7 @@ func NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {
Outbound: []string{},
},
Software: software{
- Name: "owncast",
+ Name: softwareName,
Version: config.VersionNumber,
},
Usage: usage{
@@ -113,7 +120,7 @@ func NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {
LocalPosts: int(localPostCount),
},
OpenRegistrations: false,
- Protocols: []string{"activitypub"},
+ Protocols: []string{protocolActivityPub},
Metadata: metadata{
ChatEnabled: !configRepository.GetChatDisabled(),
},
@@ -184,14 +191,14 @@ func XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {
Server: Server{
BaseURL: serverURL,
Version: config.VersionNumber,
- Name: "owncast",
- Software: "owncast",
+ Name: softwareName,
+ Software: softwareName,
},
Services: Services{
- Inbound: []string{"activitypub"},
- Outbound: []string{"activitypub"},
+ Inbound: []string{protocolActivityPub},
+ Outbound: []string{protocolActivityPub},
},
- Protocols: []string{"activitypub"},
+ Protocols: []string{protocolActivityPub},
Version: config.VersionNumber,
Usage: Usage{
Users: Users{
diff --git a/auth/indieauth/client.go b/auth/indieauth/client.go
index 0828d2b4e9..7e2afde5d0 100644
--- a/auth/indieauth/client.go
+++ b/auth/indieauth/client.go
@@ -66,7 +66,7 @@ func StartAuthFlow(authHost, userID, accessToken, displayName string) (*url.URL,
}
// Limit to only secured connections
- if u.Scheme != "https" {
+ if u.Scheme != schemeHTTPS {
return nil, errors.New("only servers secured with https are supported")
}
diff --git a/auth/indieauth/helpers.go b/auth/indieauth/helpers.go
index 159c30a333..ddd1820deb 100644
--- a/auth/indieauth/helpers.go
+++ b/auth/indieauth/helpers.go
@@ -74,7 +74,7 @@ func getAuthEndpointFromURL(urlstring string) (*url.URL, error) {
return nil, errors.Wrap(err, "unable to parse URL")
}
- if htmlDocScrapeURL.Scheme != "https" {
+ if htmlDocScrapeURL.Scheme != schemeHTTPS {
return nil, fmt.Errorf("url must be https")
}
diff --git a/auth/indieauth/indieauth_test.go b/auth/indieauth/indieauth_test.go
index 20c5b59707..89697c9253 100644
--- a/auth/indieauth/indieauth_test.go
+++ b/auth/indieauth/indieauth_test.go
@@ -6,24 +6,41 @@ import (
"github.com/owncast/owncast/utils"
)
+// isolatePendingServerAuthRequests gives a test its own pending-request map
+// and restores the previous contents on cleanup, so tests in this package
+// don't leak state into one another or become order-dependent.
+func isolatePendingServerAuthRequests(t *testing.T) {
+ t.Helper()
+ prev := pendingServerAuthRequests
+ pendingServerAuthRequests = map[string]ServerAuthRequest{}
+ t.Cleanup(func() { pendingServerAuthRequests = prev })
+}
+
func TestLimitGlobalPendingRequests(t *testing.T) {
- // Simulate 10 pending requests
+ isolatePendingServerAuthRequests(t)
+
+ // client_id and redirect_uri must be valid same-host absolute URLs to
+ // pass StartServerAuth's validation; the slug just keeps them unique.
+ clientURLs := func() (string, string) {
+ slug, _ := utils.GenerateRandomString(10)
+ return "https://client.example/" + slug, "https://client.example/" + slug + "/callback"
+ }
+
+ // Simulate maxPendingRequests-1 pending requests.
for i := 0; i < maxPendingRequests-1; i++ {
- cid, _ := utils.GenerateRandomString(10)
- redirectURL, _ := utils.GenerateRandomString(10)
+ cid, redirectURL := clientURLs()
cc, _ := utils.GenerateRandomString(10)
state, _ := utils.GenerateRandomString(10)
me, _ := utils.GenerateRandomString(10)
_, err := StartServerAuth(cid, redirectURL, cc, state, me)
if err != nil {
- t.Error("Registration should be permitted.", i, " of ", len(pendingAuthRequests), err)
+ t.Error("Registration should be permitted.", i, " of ", len(pendingServerAuthRequests), err)
}
}
// This should throw an error
- cid, _ := utils.GenerateRandomString(10)
- redirectURL, _ := utils.GenerateRandomString(10)
+ cid, redirectURL := clientURLs()
cc, _ := utils.GenerateRandomString(10)
state, _ := utils.GenerateRandomString(10)
me, _ := utils.GenerateRandomString(10)
@@ -33,3 +50,41 @@ func TestLimitGlobalPendingRequests(t *testing.T) {
t.Error("Registration should not be permitted.")
}
}
+
+func TestRejectMismatchedRedirectURI(t *testing.T) {
+ isolatePendingServerAuthRequests(t)
+
+ // A redirect_uri on a different host than client_id must be rejected so
+ // the auth endpoint can't be used as an open redirect.
+ if _, err := StartServerAuth("https://client.example", "https://attacker.example/callback", "cc", "state", "me"); err == nil {
+ t.Error("redirect_uri on a foreign host should be rejected")
+ }
+
+ // A same-host redirect_uri is accepted.
+ if _, err := StartServerAuth("https://client.example", "https://client.example/callback", "cc", "state", "me"); err != nil {
+ t.Error("same-host redirect_uri should be permitted:", err)
+ }
+}
+
+func TestRejectNonWebRedirectURI(t *testing.T) {
+ isolatePendingServerAuthRequests(t)
+
+ // Opaque/non-http(s) URIs (javascript:, data:, mailto:) have an empty
+ // hostname; without a scheme+host check, two of them would pass the
+ // host-match comparison and smuggle a hostile target into the redirect.
+ cases := []struct {
+ name string
+ clientID string
+ redirectURI string
+ }{
+ {"javascript scheme", "javascript:alert(1)", "javascript:alert(2)"},
+ {"data scheme", "data:text/html,a", "data:text/html,b"},
+ {"non-web client_id", "https://client.example", "mailto:[email protected]"},
+ }
+
+ for _, tc := range cases {
+ if _, err := StartServerAuth(tc.clientID, tc.redirectURI, "cc", "state", "me"); err == nil {
+ t.Errorf("%s: should be rejected", tc.name)
+ }
+ }
+}
diff --git a/auth/indieauth/server.go b/auth/indieauth/server.go
index 8c0abd79cd..4ad37b5391 100644
--- a/auth/indieauth/server.go
+++ b/auth/indieauth/server.go
@@ -2,6 +2,8 @@ package indieauth
import (
"fmt"
+ "net/url"
+ "strings"
"time"
"github.com/owncast/owncast/persistence/configrepository"
@@ -42,6 +44,11 @@ var pendingServerAuthRequests = map[string]ServerAuthRequest{}
const maxPendingRequests = 100
+const (
+ schemeHTTP = "http"
+ schemeHTTPS = "https"
+)
+
// StartServerAuth will handle the authentication for the admin user of this
// Owncast server. Initiated via a GET of the auth endpoint.
// https://indieweb.org/authorization-endpoint
@@ -50,6 +57,14 @@ func StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*S
return nil, errors.New("Please try again later. Too many pending requests.")
}
+ // Validate the redirect URI against the client ID before the auth
+ // endpoint hands it to the browser. Without this the endpoint is an open
+ // redirect: a crafted redirect_uri would send the generated auth code to
+ // an arbitrary origin.
+ if err := validateClientRedirect(clientID, redirectURI); err != nil {
+ return nil, err
+ }
+
code := shortid.MustGenerate()
r := ServerAuthRequest{
@@ -67,6 +82,48 @@ func StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*S
return &r, nil
}
+// validateClientRedirect enforces the IndieAuth requirement that the
+// redirect_uri belong to the requesting client. Both values must be
+// http(s) URLs with a host, and — because Owncast does not fetch the
+// client's published metadata to discover alternate redirect URIs — the
+// redirect host must match the client_id host. This prevents the
+// authorization endpoint from being used as an open redirect.
+func validateClientRedirect(clientID, redirectURI string) error {
+ client, err := url.Parse(clientID)
+ if err != nil || !isWebURL(client) {
+ return errors.New("invalid client_id")
+ }
+
+ redirect, err := url.Parse(redirectURI)
+ if err != nil || !isWebURL(redirect) {
+ return errors.New("invalid redirect_uri")
+ }
+
+ if !strings.EqualFold(client.Hostname(), redirect.Hostname()) {
+ return errors.New("redirect_uri host does not match client_id host")
+ }
+
+ return nil
+}
+
+// isWebURL reports whether u is an absolute http(s) URL with a non-empty
+// host. Requiring the scheme and host rejects opaque/non-hierarchical URIs
+// such as "javascript:..." or "data:..." — those have an empty hostname, so
+// two of them would otherwise pass the host-match check and slip a hostile
+// target into the redirect Location header.
+func isWebURL(u *url.URL) bool {
+ if u == nil {
+ return false
+ }
+
+ scheme := strings.ToLower(u.Scheme)
+ if scheme != schemeHTTP && scheme != schemeHTTPS {
+ return false
+ }
+
+ return u.Hostname() != ""
+}
+
// CompleteServerAuth will verify that the values provided in the final step
// of the IndieAuth flow are correct, and return some basic profile info.
func CompleteServerAuth(code, redirectURI, clientID string, codeVerifier string) (*ServerProfileResponse, error) {
diff --git a/core/chat/events/actionEvent.go b/core/chat/events/actionEvent.go
index b251b8511c..64d40267b0 100644
--- a/core/chat/events/actionEvent.go
+++ b/core/chat/events/actionEvent.go
@@ -9,10 +9,10 @@ type ActionEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *ActionEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "id": e.ID,
- "timestamp": e.Timestamp,
- "body": e.Body,
- "type": e.GetMessageType(),
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyBody: e.Body,
+ payloadKeyType: e.GetMessageType(),
}
}
diff --git a/core/chat/events/events.go b/core/chat/events/events.go
index 604cfcac6c..e3eeb2d4e0 100644
--- a/core/chat/events/events.go
+++ b/core/chat/events/events.go
@@ -27,6 +27,14 @@ import (
// EventPayload is a generic key/value map for sending out to chat clients.
type EventPayload map[string]interface{}
+// Shared JSON payload keys used when building outbound chat event payloads.
+const (
+ payloadKeyType = "type"
+ payloadKeyUser = "user"
+ payloadKeyTimestamp = "timestamp"
+ payloadKeyBody = "body"
+)
+
// OutboundEvent represents an event that is sent out to all listeners of the chat server.
type OutboundEvent interface {
GetBroadcastPayload() EventPayload
diff --git a/core/chat/events/fediverseEngagementEvent.go b/core/chat/events/fediverseEngagementEvent.go
index 375071bad7..cf9d9a0fcf 100644
--- a/core/chat/events/fediverseEngagementEvent.go
+++ b/core/chat/events/fediverseEngagementEvent.go
@@ -18,14 +18,14 @@ func (e *FediverseEngagementEvent) GetBroadcastPayload() EventPayload {
configRepository := configrepository.Get()
return EventPayload{
- "id": e.ID,
- "timestamp": e.Timestamp,
- "body": e.Body,
- "image": e.Image,
- "type": e.Type,
- "title": e.UserAccountName,
- "link": e.Link,
- "user": EventPayload{
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyBody: e.Body,
+ "image": e.Image,
+ payloadKeyType: e.Type,
+ "title": e.UserAccountName,
+ "link": e.Link,
+ payloadKeyUser: EventPayload{
"displayName": configRepository.GetServerName(),
},
}
diff --git a/core/chat/events/nameChangeEvent.go b/core/chat/events/nameChangeEvent.go
index e5659a18fa..8420e18f6f 100644
--- a/core/chat/events/nameChangeEvent.go
+++ b/core/chat/events/nameChangeEvent.go
@@ -25,10 +25,10 @@ type NameChangeBroadcast struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *NameChangeBroadcast) GetBroadcastPayload() EventPayload {
return EventPayload{
- "id": e.ID,
- "timestamp": e.Timestamp,
- "user": e.User,
- "oldName": e.Oldname,
- "type": UserNameChanged,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyUser: e.User,
+ "oldName": e.Oldname,
+ payloadKeyType: UserNameChanged,
}
}
diff --git a/core/chat/events/setMessageVisibilityEvent.go b/core/chat/events/setMessageVisibilityEvent.go
index 6d82d6b0ae..db2c5314d3 100644
--- a/core/chat/events/setMessageVisibilityEvent.go
+++ b/core/chat/events/setMessageVisibilityEvent.go
@@ -12,11 +12,11 @@ type SetMessageVisibilityEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *SetMessageVisibilityEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "type": VisibiltyUpdate,
- "id": e.ID,
- "timestamp": e.Timestamp,
- "ids": e.MessageIDs,
- "visible": e.Visible,
+ payloadKeyType: VisibiltyUpdate,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ "ids": e.MessageIDs,
+ "visible": e.Visible,
}
}
diff --git a/core/chat/events/systemMessageEvent.go b/core/chat/events/systemMessageEvent.go
index 61a20d9740..f02749d3ca 100644
--- a/core/chat/events/systemMessageEvent.go
+++ b/core/chat/events/systemMessageEvent.go
@@ -15,11 +15,11 @@ func (e *SystemMessageEvent) GetBroadcastPayload() EventPayload {
configRepository := configrepository.Get()
return EventPayload{
- "id": e.ID,
- "timestamp": e.Timestamp,
- "body": e.Body,
- "type": SystemMessageSent,
- "user": EventPayload{
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyBody: e.Body,
+ payloadKeyType: SystemMessageSent,
+ payloadKeyUser: EventPayload{
"displayName": configRepository.GetServerName(),
},
}
diff --git a/core/chat/events/userDisabledEvent.go b/core/chat/events/userDisabledEvent.go
index d869210efd..cc10bdacee 100644
--- a/core/chat/events/userDisabledEvent.go
+++ b/core/chat/events/userDisabledEvent.go
@@ -9,9 +9,9 @@ type UserDisabledEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *UserDisabledEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "type": ErrorUserDisabled,
- "id": e.ID,
- "timestamp": e.Timestamp,
- "user": e.User,
+ payloadKeyType: ErrorUserDisabled,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyUser: e.User,
}
}
diff --git a/core/chat/events/userJoinedEvent.go b/core/chat/events/userJoinedEvent.go
index 475b74ce54..b1ed8721ca 100644
--- a/core/chat/events/userJoinedEvent.go
+++ b/core/chat/events/userJoinedEvent.go
@@ -9,9 +9,9 @@ type UserJoinedEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *UserJoinedEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "type": UserJoined,
- "id": e.ID,
- "timestamp": e.Timestamp,
- "user": e.User,
+ payloadKeyType: UserJoined,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyUser: e.User,
}
}
diff --git a/core/chat/events/userMessageEvent.go b/core/chat/events/userMessageEvent.go
index f0dd95e915..6c4d219661 100644
--- a/core/chat/events/userMessageEvent.go
+++ b/core/chat/events/userMessageEvent.go
@@ -10,12 +10,12 @@ type UserMessageEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *UserMessageEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "id": e.ID,
- "timestamp": e.Timestamp,
- "body": e.Body,
- "user": e.User,
- "type": MessageSent,
- "visible": e.HiddenAt == nil,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyBody: e.Body,
+ payloadKeyUser: e.User,
+ payloadKeyType: MessageSent,
+ "visible": e.HiddenAt == nil,
}
}
diff --git a/core/chat/events/userPartEvent.go b/core/chat/events/userPartEvent.go
index f0ef14b7d3..ab3934b7e1 100644
--- a/core/chat/events/userPartEvent.go
+++ b/core/chat/events/userPartEvent.go
@@ -9,9 +9,9 @@ type UserPartEvent struct {
// GetBroadcastPayload will return the object to send to all chat users.
func (e *UserPartEvent) GetBroadcastPayload() EventPayload {
return EventPayload{
- "type": UserParted,
- "id": e.ID,
- "timestamp": e.Timestamp,
- "user": e.User,
+ payloadKeyType: UserParted,
+ "id": e.ID,
+ payloadKeyTimestamp: e.Timestamp,
+ payloadKeyUser: e.User,
}
}
diff --git a/core/transcoder/codecs.go b/core/transcoder/codecs.go
index b6e3e3bfa2..c4f1caf9ca 100644
--- a/core/transcoder/codecs.go
+++ b/core/transcoder/codecs.go
@@ -1,5 +1,3 @@
-//nolint:goconst
-
package transcoder
import (
@@ -10,6 +8,18 @@ import (
log "github.com/sirupsen/logrus"
)
+// ffmpeg x264-style encoding preset names, ordered from fastest to slowest.
+const (
+ presetUltrafast = "ultrafast"
+ presetSuperfast = "superfast"
+ presetVeryfast = "veryfast"
+ presetFaster = "faster"
+ presetFast = "fast"
+)
+
+// codecNameVAAPI is the ffmpeg identifier for the VA-API hardware codec/device.
+const codecNameVAAPI = "vaapi"
+
// Codec represents a supported codec on the system.
type Codec interface {
Name() string
@@ -26,7 +36,7 @@ type Codec interface {
var supportedCodecs = map[string]string{
(&Libx264Codec{}).Name(): "libx264",
(&OmxCodec{}).Name(): "omx",
- (&VaapiCodec{}).Name(): "vaapi",
+ (&VaapiCodec{}).Name(): codecNameVAAPI,
(&QuicksyncCodec{}).Name(): "qsv",
(&NvencCodec{}).Name(): "NVIDIA nvenc",
(&VideoToolboxCodec{}).Name(): "videotoolbox",
@@ -85,11 +95,11 @@ func (c *Libx264Codec) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *Libx264Codec) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "ultrafast",
- 1: "superfast",
- 2: "veryfast",
- 3: "faster",
- 4: "fast",
+ 0: presetUltrafast,
+ 1: presetSuperfast,
+ 2: presetVeryfast,
+ 3: presetFaster,
+ 4: presetFast,
}
preset, ok := presetMapping[l]
@@ -150,11 +160,11 @@ func (c *OmxCodec) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *OmxCodec) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "ultrafast",
- 1: "superfast",
- 2: "veryfast",
- 3: "faster",
- 4: "fast",
+ 0: presetUltrafast,
+ 1: presetSuperfast,
+ 2: presetVeryfast,
+ 3: presetFaster,
+ 4: presetFast,
}
preset, ok := presetMapping[l]
@@ -183,8 +193,8 @@ func (c *VaapiCodec) DisplayName() string {
// GlobalFlags are the global flags used with this codec in the transcoder.
func (c *VaapiCodec) GlobalFlags() []string {
flags := []string{
- "-hwaccel", "vaapi",
- "-hwaccel_output_format", "vaapi",
+ "-hwaccel", codecNameVAAPI,
+ "-hwaccel_output_format", codecNameVAAPI,
"-vaapi_device", "/dev/dri/renderD128",
}
@@ -193,7 +203,7 @@ func (c *VaapiCodec) GlobalFlags() []string {
// PixelFormat is the pixel format required for this codec.
func (c *VaapiCodec) PixelFormat() string {
- return "vaapi"
+ return codecNameVAAPI
}
// Scaler is the scaler used for resizing the video in the transcoder.
@@ -219,11 +229,11 @@ func (c *VaapiCodec) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *VaapiCodec) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "ultrafast",
- 1: "superfast",
- 2: "veryfast",
- 3: "faster",
- 4: "fast",
+ 0: presetUltrafast,
+ 1: presetSuperfast,
+ 2: presetVeryfast,
+ 3: presetFaster,
+ 4: presetFast,
}
preset, ok := presetMapping[l]
@@ -357,8 +367,8 @@ func (c *QuicksyncCodec) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *QuicksyncCodec) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "veryfast",
- 1: "fast",
+ 0: presetVeryfast,
+ 1: presetFast,
2: "medium",
3: "slow",
4: "veryslow",
@@ -420,11 +430,11 @@ func (c *Video4Linux) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *Video4Linux) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "ultrafast",
- 1: "superfast",
- 2: "veryfast",
- 3: "faster",
- 4: "fast",
+ 0: presetUltrafast,
+ 1: presetSuperfast,
+ 2: presetVeryfast,
+ 3: presetFaster,
+ 4: presetFast,
}
preset, ok := presetMapping[l]
@@ -486,11 +496,11 @@ func (c *VideoToolboxCodec) VariantFlags(v *HLSVariant) []string {
// GetPresetForLevel returns the string preset for this codec given an integer level.
func (c *VideoToolboxCodec) GetPresetForLevel(l int) string {
presetMapping := map[int]string{
- 0: "ultrafast",
- 1: "superfast",
- 2: "veryfast",
- 3: "faster",
- 4: "fast",
+ 0: presetUltrafast,
+ 1: presetSuperfast,
+ 2: presetVeryfast,
+ 3: presetFaster,
+ 4: presetFast,
}
preset, ok := presetMapping[l]
diff --git a/core/transcoder/transcoder.go b/core/transcoder/transcoder.go
index 3448a9aac2..fe71174333 100644
--- a/core/transcoder/transcoder.go
+++ b/core/transcoder/transcoder.go
@@ -19,6 +19,9 @@ import (
"github.com/owncast/owncast/utils"
)
+// ffmpegFlagMap is the ffmpeg stream selection flag.
+const ffmpegFlagMap = "-map"
+
var _commandExec *exec.Cmd
type execInfo struct {
@@ -411,14 +414,15 @@ func (v *HLSVariant) SetVideoBitrate(bitrate int) {
func (v *HLSVariant) getVideoQualityString(t *Transcoder) []string {
if v.isVideoPassthrough {
return []string{
- "-map", "v:0", fmt.Sprintf("-c:v:%d", v.index), "copy",
+ ffmpegFlagMap, "v:0", fmt.Sprintf("-c:v:%d", v.index), "copy",
}
}
gop := v.framerate * t.currentLatencyLevel.SecondsPerSegment // force an i-frame every segment
cmd := make([]string, 0, 20)
- cmd = append(cmd,
- "-map", "v:0",
+ cmd = append(
+ cmd,
+ ffmpegFlagMap, "v:0",
fmt.Sprintf("-c:v:%d", v.index), t.codec.Name(), // Video codec used for this variant
fmt.Sprintf("-b:v:%d", v.index), fmt.Sprintf("%dk", v.getAllocatedVideoBitrate()), // The average bitrate for this variant allowing space for audio
fmt.Sprintf("-maxrate:v:%d", v.index), fmt.Sprintf("%dk", v.getMaxVideoBitrate()), // The max bitrate allowed for this variant
@@ -451,14 +455,14 @@ func (v *HLSVariant) SetAudioBitrate(bitrate string) {
func (v *HLSVariant) getAudioQualityString() []string {
if v.isAudioPassthrough {
return []string{
- "-map", "a:0?", fmt.Sprintf("-c:a:%d", v.index), "copy",
+ ffmpegFlagMap, "a:0?", fmt.Sprintf("-c:a:%d", v.index), "copy",
}
}
// libfdk_aac is not a part of every ffmpeg install, so use "aac" instead
encoderCodec := "aac"
return []string{
- "-map", "a:0?",
+ ffmpegFlagMap, "a:0?",
fmt.Sprintf("-c:a:%d", v.index), encoderCodec,
fmt.Sprintf("-b:a:%d", v.index), v.audioBitrate,
}
diff --git a/webserver/handlers/auth/indieauth/server.go b/webserver/handlers/auth/indieauth/server.go
index 8d3444b9f7..574dcc3e5b 100644
--- a/webserver/handlers/auth/indieauth/server.go
+++ b/webserver/handlers/auth/indieauth/server.go
@@ -55,7 +55,12 @@ func HandleAuthEndpointGet(w http.ResponseWriter, r *http.Request) {
redirectParams.Set("state", request.State)
u.RawQuery = redirectParams.Encode()
- http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect)
+ // The redirect target is the client's redirect_uri, which
+ // ia.StartServerAuth above validated to be an http(s) URL whose host
+ // matches the client_id host. The endpoint is also gated behind
+ // RequireAdminAuth. gosec's taint analysis can't see the cross-function
+ // validation, so the open-redirect warning here is a false positive.
+ http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect) //nolint:gosec // G710: redirect_uri validated against client_id in StartServerAuth
}
func HandleAuthEndpointPost(w http.ResponseWriter, r *http.Request) {
diff --git a/webserver/handlers/hls.go b/webserver/handlers/hls.go
index 2ba4ec3504..73ff20f7b3 100644
--- a/webserver/handlers/hls.go
+++ b/webserver/handlers/hls.go
@@ -52,5 +52,10 @@ func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {
}
middleware.EnableCors(w)
+ // fullPath is built from r.URL.Path, which is normalized and cleaned by the
+ // http.ServeMux that routes to this handler (stripping ".." traversal
+ // segments), and is further constrained to .m3u8/.ts files under
+ // config.HLSStoragePath via the extension check above and filepath.Join.
+ //nolint:gosec // G703: requested path is normalized and confined to HLSStoragePath.
http.ServeFile(w, r, fullPath)
}
diff --git a/webserver/handlers/images.go b/webserver/handlers/images.go
index 993b78917d..ecf721df8b 100644
--- a/webserver/handlers/images.go
+++ b/webserver/handlers/images.go
@@ -15,6 +15,9 @@ const (
contentTypeGIF = "image/gif"
)
+// thumbnailFilename is the filename of the generated stream thumbnail image.
+const thumbnailFilename = "thumbnail.jpg"
+
var previewThumbCache = ttlcache.New(
ttlcache.WithTTL[string, []byte](15),
ttlcache.WithCapacity[string, []byte](1),
@@ -23,7 +26,7 @@ var previewThumbCache = ttlcache.New(
// GetThumbnail will return the thumbnail image as a response.
func GetThumbnail(w http.ResponseWriter, r *http.Request) {
- imageFilename := "thumbnail.jpg"
+ imageFilename := thumbnailFilename
imagePath := filepath.Join(config.TempDir, imageFilename)
httpCacheTime := utils.GetCacheDurationSecondsForPath(imagePath)
inMemoryCacheTime := time.Duration(15) * time.Second
diff --git a/webserver/handlers/index.go b/webserver/handlers/index.go
index 67199ff2bc..503360292e 100644
--- a/webserver/handlers/index.go
+++ b/webserver/handlers/index.go
@@ -93,8 +93,8 @@ func renderIndexHtml(w http.ResponseWriter, nonce string) {
Summary: configRepository.GetServerSummary(),
RequestedURL: fmt.Sprintf("%s%s", configRepository.GetServerURL(), "/"),
TagsString: strings.Join(configRepository.GetServerMetadataTags(), ","),
- ThumbnailURL: "thumbnail.jpg",
- Thumbnail: "thumbnail.jpg",
+ ThumbnailURL: thumbnailFilename,
+ Thumbnail: thumbnailFilename,
Image: "logo/external",
StatusJSON: string(sb),
ServerConfigJSON: string(cb),
@@ -174,7 +174,7 @@ func handleScraperMetadataPage(w http.ResponseWriter, r *http.Request) {
// If the thumbnail does not exist or we're offline then just use the logo image
var thumbnailURL string
- if status.Online && utils.DoesFileExists(filepath.Join(config.DataDirectory, "tmp", "thumbnail.jpg")) {
+ if status.Online && utils.DoesFileExists(filepath.Join(config.DataDirectory, "tmp", thumbnailFilename)) {
thumbnail, err := url.Parse(fmt.Sprintf("%s://%s%s", scheme, r.Host, "/thumbnail.jpg"))
if err != nil {
log.Errorln(err)
diff --git a/webserver/router/router.go b/webserver/router/router.go
index 7d9fca84c6..3750dafc9a 100644
--- a/webserver/router/router.go
+++ b/webserver/router/router.go
@@ -10,8 +10,6 @@ import (
"github.com/go-chi/chi/v5"
chiMW "github.com/go-chi/chi/v5/middleware"
log "github.com/sirupsen/logrus"
- "golang.org/x/net/http2"
- "golang.org/x/net/http2/h2c"
"github.com/owncast/owncast/activitypub"
aphandlers "github.com/owncast/owncast/activitypub/controllers"
@@ -66,8 +64,7 @@ func Start(enableVerboseLogging bool) error {
// Create a custom mux handler to intercept the /debug/vars endpoint.
// This is a hack because Prometheus enables this endpoint by default
// due to its use of expvar and we do not want this exposed.
- h2s := &http2.Server{}
- http2Handler := h2c.NewHandler(r, h2s)
+ rootHandler := r
m := http.NewServeMux()
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
@@ -79,18 +76,25 @@ func Start(enableVerboseLogging bool) error {
// Redirect /embed/chat
http.Redirect(w, r, "/embed/chat/readonly", http.StatusTemporaryRedirect)
default:
- http2Handler.ServeHTTP(w, r)
+ rootHandler.ServeHTTP(w, r)
}
})
port := config.WebServerPort
ip := config.WebServerIP
+ // Allow cleartext (unencrypted) HTTP/2 in addition to HTTP/1, replacing the
+ // previously used and now-deprecated golang.org/x/net/http2/h2c wrapper.
+ protocols := new(http.Protocols)
+ protocols.SetHTTP1(true)
+ protocols.SetUnencryptedHTTP2(true)
+
compress, _ := httpcompression.DefaultAdapter() // Use the default configuration
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", ip, port),
ReadHeaderTimeout: 4 * time.Second,
Handler: compress(m),
+ Protocols: protocols,
}
if ip != "0.0.0.0" {