Skip to content

Commit

Permalink
server: Allow authentication only once
Browse files Browse the repository at this point in the history
Closes #151.
  • Loading branch information
foxcpp committed Jul 22, 2021
1 parent 17a4bee commit df83e63
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
11 changes: 8 additions & 3 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type Conn struct {

fromReceived bool
recipients []string
didAuth bool
}

func newConn(c net.Conn, s *Server) *Conn {
Expand Down Expand Up @@ -501,6 +502,10 @@ func (c *Conn) handleAuth(arg string) {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Please introduce yourself first.")
return
}
if c.didAuth {
c.WriteResponse(503, EnhancedCode{5, 5, 1}, "Already authenticated")
return
}

parts := strings.Fields(arg)
if len(parts) == 0 {
Expand Down Expand Up @@ -573,9 +578,8 @@ func (c *Conn) handleAuth(arg string) {
}
}

if c.Session() != nil {
c.WriteResponse(235, EnhancedCode{2, 0, 0}, "Authentication succeeded")
}
c.WriteResponse(235, EnhancedCode{2, 0, 0}, "Authentication succeeded")
c.didAuth = true
}

func (c *Conn) handleStartTLS() {
Expand Down Expand Up @@ -610,6 +614,7 @@ func (c *Conn) handleStartTLS() {
session.Logout()
c.SetSession(nil)
}
c.didAuth = false
c.reset()
}

Expand Down
32 changes: 32 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,38 @@ func testServerAuthenticated(t *testing.T) (be *backend, s *smtp.Server, c net.C
return
}

func TestServerAuthTwice(t *testing.T) {
_, _, c, scanner, caps := testServerEhlo(t)

if _, ok := caps["AUTH PLAIN"]; !ok {
t.Fatal("AUTH PLAIN capability is missing when auth is enabled")
}

io.WriteString(c, "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n")
scanner.Scan()
if !strings.HasPrefix(scanner.Text(), "235 ") {
t.Fatal("Invalid AUTH response:", scanner.Text())
}

io.WriteString(c, "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n")
scanner.Scan()
if !strings.HasPrefix(scanner.Text(), "503 ") {
t.Fatal("Invalid AUTH response:", scanner.Text())
}

io.WriteString(c, "RSET\r\n")
scanner.Scan()
if !strings.HasPrefix(scanner.Text(), "250 ") {
t.Fatal("Invalid AUTH response:", scanner.Text())
}

io.WriteString(c, "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n")
scanner.Scan()
if !strings.HasPrefix(scanner.Text(), "503 ") {
t.Fatal("Invalid AUTH response:", scanner.Text())
}
}

func TestServerCancelSASL(t *testing.T) {
_, _, c, scanner, caps := testServerEhlo(t)

Expand Down

0 comments on commit df83e63

Please sign in to comment.