Skip to content

Commit

Permalink
Merge pull request #1522 from subbyte/authlog
Browse files Browse the repository at this point in the history
Improve RTSP server authentication handling and auditing
  • Loading branch information
AlexxIT authored Feb 18, 2025
2 parents 97891d3 + 02ac3a6 commit b3f83fd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
5 changes: 4 additions & 1 deletion internal/rtsp/rtsp.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rtsp

import (
"errors"
"io"
"net"
"net/url"
Expand Down Expand Up @@ -237,7 +238,9 @@ func tcpHandler(conn *rtsp.Conn) {
})

if err := conn.Accept(); err != nil {
if err != io.EOF {
if errors.Is(err, rtsp.FailedAuth) {
log.Warn().Str("remote_addr", conn.Connection.RemoteAddr).Msg("[rtsp] failed authentication")
} else if err != io.EOF {
log.WithLevel(level).Err(err).Caller().Send()
}
if closer != nil {
Expand Down
11 changes: 9 additions & 2 deletions pkg/rtsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"github.com/AlexxIT/go2rtc/pkg/tcp"
)

var FailedAuth = errors.New("failed authentication")

func NewServer(conn net.Conn) *Conn {
return &Conn{
Connection: core.Connection{
Expand Down Expand Up @@ -45,7 +47,7 @@ func (c *Conn) Accept() error {

c.Fire(req)

if !c.auth.Validate(req) {
if valid, empty := c.auth.Validate(req); !valid {
res := &tcp.Response{
Status: "401 Unauthorized",
Header: map[string][]string{"Www-Authenticate": {`Basic realm="go2rtc"`}},
Expand All @@ -54,7 +56,12 @@ func (c *Conn) Accept() error {
if err = c.WriteResponse(res); err != nil {
return err
}
continue
if empty {
// eliminate false positive: ffmpeg sends first request without
// authorization header even if the user provides credentials
continue
}
return FailedAuth
}

// Receiver: OPTIONS > DESCRIBE > SETUP... > PLAY > TEARDOWN
Expand Down
8 changes: 4 additions & 4 deletions pkg/tcp/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,22 +85,22 @@ func (a *Auth) Write(req *Request) {
}
}

func (a *Auth) Validate(req *Request) bool {
func (a *Auth) Validate(req *Request) (valid, empty bool) {
if a == nil {
return true
return true, true
}

header := req.Header.Get("Authorization")
if header == "" {
return false
return false, true
}

if a.Method == AuthUnknown {
a.Method = AuthBasic
a.header = "Basic " + B64(a.user, a.pass)
}

return header == a.header
return header == a.header, false
}

func (a *Auth) ReadNone(res *Response) bool {
Expand Down

0 comments on commit b3f83fd

Please sign in to comment.