| 1 |
package managementauth |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"crypto/subtle" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"net" |
| 10 |
"time" |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
passwordPrompt = "ENTER PASSWORD:" |
| 15 |
badPasswordResponse = "ERROR: bad password\r\n" |
| 16 |
passwordAcceptedResponse = "SUCCESS: password is correct\r\n" |
| 17 |
) |
| 18 |
|
| 19 |
// ErrInvalidPassword reports that a management client provided the wrong password. |
| 20 |
var ErrInvalidPassword = errors.New("client provide invalid password") |
| 21 |
|
| 22 |
// Authenticate validates an optional OpenVPN management password exchange. |
| 23 |
func Authenticate(conn net.Conn, scanner *bufio.Scanner, password string, timeout time.Duration) error { |
| 24 |
if password == "" { |
| 25 |
return nil |
| 26 |
} |
| 27 |
|
| 28 |
if err := writeWithDeadline(conn, timeout, passwordPrompt); err != nil { |
| 29 |
return err |
| 30 |
} |
| 31 |
|
| 32 |
passwordLine, err := readPasswordLine(conn, scanner, timeout) |
| 33 |
if err != nil { |
| 34 |
return err |
| 35 |
} |
| 36 |
|
| 37 |
if subtle.ConstantTimeCompare(passwordLine, []byte(password)) == 0 { |
| 38 |
_ = writeWithDeadline(conn, timeout, badPasswordResponse) |
| 39 |
|
| 40 |
return ErrInvalidPassword |
| 41 |
} |
| 42 |
|
| 43 |
return writeWithDeadline(conn, timeout, passwordAcceptedResponse) |
| 44 |
} |
| 45 |
|
| 46 |
func readPasswordLine(conn net.Conn, scanner *bufio.Scanner, timeout time.Duration) ([]byte, error) { |
| 47 |
if err := conn.SetReadDeadline(time.Now().Add(timeout)); err != nil { |
| 48 |
return nil, fmt.Errorf("unable to set read deadline: %w", err) |
| 49 |
} |
| 50 |
|
| 51 |
if !scanner.Scan() { |
| 52 |
err := scanner.Err() |
| 53 |
if err == nil { |
| 54 |
err = io.EOF |
| 55 |
} |
| 56 |
|
| 57 |
return nil, fmt.Errorf("unable to read from client: %w", err) |
| 58 |
} |
| 59 |
|
| 60 |
if err := conn.SetReadDeadline(time.Time{}); err != nil { |
| 61 |
return nil, fmt.Errorf("unable to clear read deadline: %w", err) |
| 62 |
} |
| 63 |
|
| 64 |
return scanner.Bytes(), nil |
| 65 |
} |
| 66 |
|
| 67 |
func writeWithDeadline(conn net.Conn, timeout time.Duration, message string) error { |
| 68 |
if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil { |
| 69 |
return fmt.Errorf("unable to set write deadline: %w", err) |
| 70 |
} |
| 71 |
|
| 72 |
if _, err := conn.Write([]byte(message)); err != nil { |
| 73 |
return fmt.Errorf("unable to write to client: %w", err) |
| 74 |
} |
| 75 |
|
| 76 |
return nil |
| 77 |
} |