|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/hmac" |
| 6 | + "crypto/sha256" |
| 7 | + "encoding/hex" |
| 8 | + "fmt" |
| 9 | + "github.com/google/uuid" |
| 10 | + "net" |
| 11 | + "slices" |
| 12 | + "strconv" |
| 13 | + "strings" |
| 14 | +) |
| 15 | + |
| 16 | +// Authenticator represents an object responsible for handling client authentication and generating and validating answers. |
| 17 | +// |
| 18 | +// Fields: |
| 19 | +// - k []byte: the secret key used for generating answers and validating answers. |
| 20 | +// - pr *RangeInclusive: the range of ports used for finding free ports during authentication. |
| 21 | +// - db *TcpClientRepository: the repository for accessing TCP client data. |
| 22 | +// |
| 23 | +// Methods: |
| 24 | +// - GenerateAnswer(ch uuid.UUID) string: generates an answer for a challenge. |
| 25 | +// - ValidateAnswer(ch uuid.UUID, ans string) bool: validates an answer for a challenge. |
| 26 | +// - PerformServerHandshake(stream *Codec) error: performs the server handshake with the client. |
| 27 | +// - handleClientAuth(stream *Codec, id string) error: handles the client authentication process. |
| 28 | +// - findFreePort() (uint16, error): finds a free port within the specified range. |
| 29 | +type Authenticator struct { |
| 30 | + k []byte |
| 31 | + pr *RangeInclusive |
| 32 | + db *TcpClientRepository |
| 33 | +} |
| 34 | + |
| 35 | +// NewAuthenticator creates a new instance of the Authenticator struct and initializes it with the provided parameters. |
| 36 | +// The secret parameter is used to generate the authentication key, which is a SHA-256 hash of the secret. |
| 37 | +// The db parameter is a reference to a TcpClientRepository, which is used to interact with the client database. |
| 38 | +// The pr parameter is a reference to a RangeInclusive struct, which represents the range of ports that can be used. |
| 39 | +// The function returns a pointer to the newly created Authenticator instance. |
| 40 | +func NewAuthenticator(secret string, db *TcpClientRepository, pr *RangeInclusive) *Authenticator { |
| 41 | + h := sha256.Sum256([]byte(secret)) |
| 42 | + return &Authenticator{k: h[:], pr: pr, db: db} |
| 43 | +} |
| 44 | + |
| 45 | +// GenerateAnswer generates an answer using the HMAC-SHA256 algorithm. |
| 46 | +// It takes a uuid.UUID as a challenge, appends it to the key provided during |
| 47 | +// Authenticator initialization, and computes the HMAC-SHA256 hash. The result |
| 48 | +// is then encoded to a hexadecimal string and returned. |
| 49 | +func (a *Authenticator) GenerateAnswer(ch uuid.UUID) string { |
| 50 | + m := hmac.New(sha256.New, a.k) |
| 51 | + m.Write(ch[:]) |
| 52 | + return hex.EncodeToString(m.Sum(nil)) |
| 53 | +} |
| 54 | + |
| 55 | +// ValidateAnswer validates the answer provided by the client for a challenge. |
| 56 | +// It decodes the answer from a hex-string to bytes and computes the HMAC of |
| 57 | +// the challenge using the provided key. Then it checks if the computed HMAC |
| 58 | +// is equal to the decoded answer. Returns true if the answer is valid, false |
| 59 | +// otherwise. |
| 60 | +func (a *Authenticator) ValidateAnswer(ch uuid.UUID, ans string) bool { |
| 61 | + b, err := hex.DecodeString(ans) |
| 62 | + if err != nil { |
| 63 | + return false |
| 64 | + } |
| 65 | + m := hmac.New(sha256.New, a.k) |
| 66 | + m.Write(ch[:]) |
| 67 | + em := m.Sum(nil) |
| 68 | + return hmac.Equal(em, b) |
| 69 | +} |
| 70 | + |
| 71 | +// PerformServerHandshake performs the server-side handshake process with a client. |
| 72 | +// It sends a challenge message to the client, receives the client's response, |
| 73 | +// validates it, and handles the authentication process if the response is valid. |
| 74 | +// If the handshake fails at any step, an error is returned. |
| 75 | +func (a *Authenticator) PerformServerHandshake(stream *Codec) error { |
| 76 | + ch := uuid.New() |
| 77 | + if err := stream.Send(ServerMessage{Type: MtChallenge, Challenge: ch}); err != nil { |
| 78 | + return err |
| 79 | + } |
| 80 | + |
| 81 | + var msg ClientMessage |
| 82 | + ctx, cancel := context.WithTimeout(context.Background(), NetworkTimeout) |
| 83 | + defer cancel() |
| 84 | + |
| 85 | + if err := stream.Recv(ctx, &msg); err != nil { |
| 86 | + return err |
| 87 | + } |
| 88 | + |
| 89 | + if msg.Type == MtAuthenticate && a.ValidateAnswer(ch, msg.Authenticate) { |
| 90 | + if err := a.handleClientAuth(stream, msg.ClientId); err != nil { |
| 91 | + return err |
| 92 | + } |
| 93 | + } else { |
| 94 | + return ErrInvalidSecret |
| 95 | + } |
| 96 | + |
| 97 | + return nil |
| 98 | +} |
| 99 | + |
| 100 | +// `handleClientAuth` handles the authentication of a client. It validates the client ID, retrieves the client information from the database, generates a free port if necessary, stores the client information in the database, and sends the free port to the client through the stream. |
| 101 | +func (a *Authenticator) handleClientAuth(stream *Codec, id string) error { |
| 102 | + if strings.TrimSpace(id) == "" { |
| 103 | + return ErrInvalidClientId |
| 104 | + } |
| 105 | + |
| 106 | + c, ex, err := a.db.GetByClientID(id) |
| 107 | + if err != nil { |
| 108 | + return err |
| 109 | + } |
| 110 | + |
| 111 | + var p uint16 |
| 112 | + if !ex { |
| 113 | + bl, err := a.db.GetAllPorts() |
| 114 | + if err != nil { |
| 115 | + return err |
| 116 | + } |
| 117 | + p, err = a.findFreePort(bl) |
| 118 | + if err != nil { |
| 119 | + return err |
| 120 | + } |
| 121 | + err = a.db.Create(&TCPClient{ID: p, ClientID: id, Port: p}) |
| 122 | + if err != nil { |
| 123 | + return err |
| 124 | + } |
| 125 | + } else { |
| 126 | + p = c.Port |
| 127 | + } |
| 128 | + |
| 129 | + return stream.Send(ServerMessage{Type: MtFreePort, Port: p}) |
| 130 | +} |
| 131 | + |
| 132 | +// findFreePort finds a free port within the range of min and max ports specified in the Authenticator's RangeInclusive property. |
| 133 | +// It tries to listen on each port in the range and returns the first port that is available. |
| 134 | +// If no port is available, it returns an error indicating that no port was found in the specified range. |
| 135 | +func (a *Authenticator) findFreePort(skip []uint16) (uint16, error) { |
| 136 | + for p := a.pr.min; p <= a.pr.max; p++ { |
| 137 | + if slices.Contains(skip, p) { |
| 138 | + continue |
| 139 | + } |
| 140 | + l, err := net.Listen("tcp", ":"+strconv.Itoa(int(p))) |
| 141 | + if err == nil { |
| 142 | + l.Close() |
| 143 | + return p, nil |
| 144 | + } |
| 145 | + } |
| 146 | + return 0, fmt.Errorf("no available port found in the range %d-%d", a.pr.min, a.pr.max) |
| 147 | +} |
0 commit comments