auth.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package oscar
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log/slog"
  9. "net"
  10. "sync"
  11. "time"
  12. "github.com/mk6i/retro-aim-server/config"
  13. "github.com/mk6i/retro-aim-server/state"
  14. "github.com/mk6i/retro-aim-server/wire"
  15. "github.com/google/uuid"
  16. "github.com/patrickmn/go-cache"
  17. "golang.org/x/time/rate"
  18. )
  19. type AuthService interface {
  20. BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error)
  21. BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, newUserFn func(screenName state.DisplayScreenName) (state.User, error)) (wire.SNACMessage, error)
  22. FLAPLogin(ctx context.Context, frame wire.FLAPSignonFrame, newUserFn func(screenName state.DisplayScreenName) (state.User, error)) (wire.TLVRestBlock, error)
  23. RegisterBOSSession(ctx context.Context, authCookie []byte) (*state.Session, error)
  24. RetrieveBOSSession(ctx context.Context, authCookie []byte) (*state.Session, error)
  25. RegisterChatSession(ctx context.Context, authCookie []byte) (*state.Session, error)
  26. Signout(ctx context.Context, sess *state.Session)
  27. SignoutChat(ctx context.Context, sess *state.Session)
  28. }
  29. // IPRateLimiter enforces a per-IP rate limit using a token bucket algorithm.
  30. // It caches individual rate limiters by IP address and supports tagging requests
  31. // as originating from the BUCP or FLAP auth.
  32. //
  33. // The limiter uses an in-memory cache with TTL expiration, so rate limits reset
  34. // after the TTL if no activity is observed for a given IP.
  35. type IPRateLimiter struct {
  36. cache *cache.Cache // In-memory cache mapping IPs to rate limiters with optional BUCP tag
  37. rate rate.Limit // Requests allowed per second
  38. burst int // Maximum burst size allowed
  39. }
  40. type rateLimitEntry struct {
  41. isBUCP bool
  42. limiter *rate.Limiter
  43. }
  44. // NewIPRateLimiter initializes a new IPRateLimiter with the specified rate,
  45. // burst size, and TTL for each IP's limiter. Entries expire after 2×TTL.
  46. func NewIPRateLimiter(rate rate.Limit, burst int, ttl time.Duration) *IPRateLimiter {
  47. return &IPRateLimiter{
  48. cache: cache.New(ttl, 2*ttl),
  49. rate: rate,
  50. burst: burst,
  51. }
  52. }
  53. // SetBUCP marks the rate limiter for the given IP as originating from BUCP auth
  54. // (default FLAP auth).
  55. func (l *IPRateLimiter) SetBUCP(ip string) {
  56. limiter, found := l.cache.Get(ip)
  57. if !found {
  58. limiter = &rateLimitEntry{
  59. isBUCP: true,
  60. limiter: rate.NewLimiter(l.rate, l.burst),
  61. }
  62. l.cache.Set(ip, limiter, cache.DefaultExpiration)
  63. }
  64. limiter.(*rateLimitEntry).isBUCP = true
  65. }
  66. // Allow checks if a request from the given IP is allowed under its rate limit.
  67. // It returns whether the request is allowed and whether the connection uses
  68. // BUCP auth.
  69. func (l *IPRateLimiter) Allow(ip string) (allowed bool, isBUCP bool) {
  70. limiter, found := l.cache.Get(ip)
  71. if !found {
  72. limiter = &rateLimitEntry{
  73. limiter: rate.NewLimiter(l.rate, l.burst),
  74. }
  75. l.cache.Set(ip, limiter, cache.DefaultExpiration)
  76. }
  77. entry := limiter.(*rateLimitEntry)
  78. return entry.limiter.Allow(), entry.isBUCP
  79. }
  80. // AuthServer is an authentication server for both FLAP (AIM v1.0-3.0) and BUCP
  81. // (AIM v3.5-5.9) authentication flows.
  82. type AuthServer struct {
  83. AuthService
  84. config.Config
  85. Logger *slog.Logger
  86. *IPRateLimiter
  87. }
  88. // Start starts the authentication server and listens for new connections.
  89. func (rt AuthServer) Start(ctx context.Context) error {
  90. addr := net.JoinHostPort("", rt.Config.AuthPort)
  91. listener, err := net.Listen("tcp", addr)
  92. if err != nil {
  93. return fmt.Errorf("unable to start auth server: %w", err)
  94. }
  95. go func() {
  96. <-ctx.Done()
  97. listener.Close()
  98. }()
  99. rt.Logger.Info("starting server", "listen_host", addr, "oscar_host", rt.Config.OSCARHost)
  100. wg := sync.WaitGroup{}
  101. for {
  102. conn, err := listener.Accept()
  103. if err != nil {
  104. if errors.Is(err, net.ErrClosed) {
  105. break
  106. }
  107. rt.Logger.Error("accept failed", "err", err.Error())
  108. continue
  109. }
  110. wg.Add(1)
  111. go func() {
  112. defer wg.Done()
  113. connCtx := context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  114. rt.Logger.DebugContext(connCtx, "accepted connection")
  115. if err := rt.handleNewConnection(connCtx, conn); err != nil {
  116. rt.Logger.Info("user session failed", "err", err.Error())
  117. }
  118. }()
  119. }
  120. if !waitForShutdown(&wg) {
  121. rt.Logger.Error("shutdown complete, but connections didn't close cleanly")
  122. } else {
  123. rt.Logger.Info("shutdown complete")
  124. }
  125. return nil
  126. }
  127. func (rt AuthServer) handleNewConnection(ctx context.Context, conn net.Conn) error {
  128. defer conn.Close()
  129. flapc := wire.NewFlapClient(100, conn, conn)
  130. ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  131. if err != nil {
  132. rt.Logger.Error("failed to parse remote address", "err", err.Error())
  133. return err
  134. }
  135. if ok, isBUCP := rt.Allow(ip); !ok {
  136. rt.Logger.Error("user rate limited at login", "remote", ip)
  137. tlv := wire.TLVRestBlock{
  138. TLVList: []wire.TLV{
  139. wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, wire.LoginErrRateLimitExceeded),
  140. },
  141. }
  142. // gives wrong response if you quickly switch between BUCP/FLAP clients
  143. if isBUCP {
  144. return flapc.SendSNAC(
  145. wire.SNACFrame{
  146. FoodGroup: wire.BUCP,
  147. SubGroup: wire.BUCPLoginResponse,
  148. },
  149. wire.SNAC_0x17_0x03_BUCPLoginResponse{
  150. TLVRestBlock: tlv,
  151. },
  152. )
  153. } else {
  154. return flapc.SendSignoffFrame(tlv)
  155. }
  156. }
  157. // auth must complete within the next 30 seconds
  158. if err := conn.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
  159. return fmt.Errorf("failed to set deadline: %w", err)
  160. }
  161. if err := flapc.SendSignonFrame(nil); err != nil {
  162. return err
  163. }
  164. signonFrame, err := flapc.ReceiveSignonFrame()
  165. if err != nil {
  166. return err
  167. }
  168. // decide whether the client is using BUCP or FLAP authentication based on
  169. // the presence of the screen name TLV. this block used to check for the
  170. // presence of the roasted password TLV, however that proved an unreliable
  171. // indicator of FLAP-auth because older ICQ clients appear to omit the
  172. // roasted password TLV when the password is not stored client-side.
  173. if _, hasScreenName := signonFrame.Uint16BE(wire.LoginTLVTagsScreenName); hasScreenName {
  174. return rt.processFLAPAuth(ctx, signonFrame, flapc)
  175. }
  176. rt.SetBUCP(ip)
  177. return rt.processBUCPAuth(ctx, flapc)
  178. }
  179. func (rt AuthServer) processFLAPAuth(ctx context.Context, signonFrame wire.FLAPSignonFrame, flapc *wire.FlapClient) error {
  180. tlv, err := rt.AuthService.FLAPLogin(ctx, signonFrame, state.NewStubUser)
  181. if err != nil {
  182. return err
  183. }
  184. return flapc.SendSignoffFrame(tlv)
  185. }
  186. func (rt AuthServer) processBUCPAuth(ctx context.Context, flapc *wire.FlapClient) error {
  187. frames := 0
  188. for {
  189. frame, err := flapc.ReceiveFLAP()
  190. if err != nil {
  191. return err
  192. }
  193. if frames > 10 {
  194. // a lot of frames received, the client is misbehaving
  195. return fmt.Errorf("too many auth flap packets received")
  196. }
  197. frames++
  198. switch frame.FrameType {
  199. case wire.FLAPFrameSignoff:
  200. rt.Logger.Debug("signed off mid-login")
  201. return io.EOF // client disconnected
  202. case wire.FLAPFrameKeepAlive:
  203. rt.Logger.Debug("received flap keepalive frame")
  204. case wire.FLAPFrameData:
  205. buf := bytes.NewReader(frame.Payload)
  206. fr := wire.SNACFrame{}
  207. if err := wire.UnmarshalBE(&fr, buf); err != nil {
  208. return err
  209. }
  210. switch {
  211. case fr.FoodGroup == wire.BUCP && fr.SubGroup == wire.BUCPChallengeRequest:
  212. challengeRequest := wire.SNAC_0x17_0x06_BUCPChallengeRequest{}
  213. if err := wire.UnmarshalBE(&challengeRequest, buf); err != nil {
  214. return err
  215. }
  216. outSNAC, err := rt.BUCPChallenge(ctx, challengeRequest, uuid.New)
  217. if err != nil {
  218. return err
  219. }
  220. if err := flapc.SendSNAC(outSNAC.Frame, outSNAC.Body); err != nil {
  221. return err
  222. }
  223. if outSNAC.Frame.SubGroup == wire.BUCPLoginResponse {
  224. screenName, _ := challengeRequest.String(wire.LoginTLVTagsScreenName)
  225. rt.Logger.Debug("failed BUCP challenge: user does not exist", "screen_name", screenName)
  226. return nil // account does not exist
  227. }
  228. case fr.FoodGroup == wire.BUCP && fr.SubGroup == wire.BUCPLoginRequest:
  229. loginRequest := wire.SNAC_0x17_0x02_BUCPLoginRequest{}
  230. if err := wire.UnmarshalBE(&loginRequest, buf); err != nil {
  231. return err
  232. }
  233. outSNAC, err := rt.BUCPLogin(ctx, loginRequest, state.NewStubUser)
  234. if err != nil {
  235. return err
  236. }
  237. return flapc.SendSNAC(outSNAC.Frame, outSNAC.Body)
  238. default:
  239. rt.Logger.Debug("unexpected SNAC received during login",
  240. "foodgroup", wire.FoodGroupName(fr.FoodGroup),
  241. "subgroup", wire.SubGroupName(fr.FoodGroup, fr.SubGroup))
  242. return io.EOF
  243. }
  244. default:
  245. rt.Logger.Debug("unexpected frame type received during login", "type", frame.FrameType)
  246. return io.EOF
  247. }
  248. }
  249. }