turn.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package server
  2. import (
  3. "fmt"
  4. "net"
  5. "github.com/pion/stun"
  6. "github.com/pion/turn/v2/internal/allocation"
  7. "github.com/pion/turn/v2/internal/ipnet"
  8. "github.com/pion/turn/v2/internal/proto"
  9. )
  10. // // https://tools.ietf.org/html/rfc5766#section-6.2
  11. func handleAllocateRequest(r Request, m *stun.Message) error {
  12. r.Log.Debugf("received AllocateRequest from %s", r.SrcAddr.String())
  13. // 1. The server MUST require that the request be authenticated. This
  14. // authentication MUST be done using the long-term credential
  15. // mechanism of [https://tools.ietf.org/html/rfc5389#section-10.2.2]
  16. // unless the client and server agree to use another mechanism through
  17. // some procedure outside the scope of this document.
  18. messageIntegrity, hasAuth, err := authenticateRequest(r, m, stun.MethodAllocate)
  19. if !hasAuth {
  20. return err
  21. }
  22. fiveTuple := &allocation.FiveTuple{
  23. SrcAddr: r.SrcAddr,
  24. DstAddr: r.Conn.LocalAddr(),
  25. Protocol: allocation.UDP,
  26. }
  27. requestedPort := 0
  28. reservationToken := ""
  29. badRequestMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeBadRequest})
  30. insufficentCapacityMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeInsufficientCapacity})
  31. // 2. The server checks if the 5-tuple is currently in use by an
  32. // existing allocation. If yes, the server rejects the request with
  33. // a 437 (Allocation Mismatch) error.
  34. if alloc := r.AllocationManager.GetAllocation(fiveTuple); alloc != nil {
  35. id, attrs := alloc.GetResponseCache()
  36. if id != m.TransactionID {
  37. msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeAllocMismatch})
  38. return buildAndSendErr(r.Conn, r.SrcAddr, errRelayAlreadyAllocatedForFiveTuple, msg...)
  39. }
  40. // a retry allocation
  41. msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassSuccessResponse), append(attrs, messageIntegrity)...)
  42. return buildAndSend(r.Conn, r.SrcAddr, msg...)
  43. }
  44. // 3. The server checks if the request contains a REQUESTED-TRANSPORT
  45. // attribute. If the REQUESTED-TRANSPORT attribute is not included
  46. // or is malformed, the server rejects the request with a 400 (Bad
  47. // Request) error. Otherwise, if the attribute is included but
  48. // specifies a protocol other that UDP, the server rejects the
  49. // request with a 442 (Unsupported Transport Protocol) error.
  50. var requestedTransport proto.RequestedTransport
  51. if err = requestedTransport.GetFrom(m); err != nil {
  52. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  53. } else if requestedTransport.Protocol != proto.ProtoUDP {
  54. msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeUnsupportedTransProto})
  55. return buildAndSendErr(r.Conn, r.SrcAddr, errRequestedTransportMustBeUDP, msg...)
  56. }
  57. // 4. The request may contain a DONT-FRAGMENT attribute. If it does,
  58. // but the server does not support sending UDP datagrams with the DF
  59. // bit set to 1 (see Section 12), then the server treats the DONT-
  60. // FRAGMENT attribute in the Allocate request as an unknown
  61. // comprehension-required attribute.
  62. if m.Contains(stun.AttrDontFragment) {
  63. msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeUnknownAttribute}, &stun.UnknownAttributes{stun.AttrDontFragment})
  64. return buildAndSendErr(r.Conn, r.SrcAddr, errNoDontFragmentSupport, msg...)
  65. }
  66. // 5. The server checks if the request contains a RESERVATION-TOKEN
  67. // attribute. If yes, and the request also contains an EVEN-PORT
  68. // attribute, then the server rejects the request with a 400 (Bad
  69. // Request) error. Otherwise, it checks to see if the token is
  70. // valid (i.e., the token is in range and has not expired and the
  71. // corresponding relayed transport address is still available). If
  72. // the token is not valid for some reason, the server rejects the
  73. // request with a 508 (Insufficient Capacity) error.
  74. var reservationTokenAttr proto.ReservationToken
  75. if err = reservationTokenAttr.GetFrom(m); err == nil {
  76. var evenPort proto.EvenPort
  77. if err = evenPort.GetFrom(m); err == nil {
  78. return buildAndSendErr(r.Conn, r.SrcAddr, errRequestWithReservationTokenAndEvenPort, badRequestMsg...)
  79. }
  80. }
  81. // 6. The server checks if the request contains an EVEN-PORT attribute.
  82. // If yes, then the server checks that it can satisfy the request
  83. // (i.e., can allocate a relayed transport address as described
  84. // below). If the server cannot satisfy the request, then the
  85. // server rejects the request with a 508 (Insufficient Capacity)
  86. // error.
  87. var evenPort proto.EvenPort
  88. if err = evenPort.GetFrom(m); err == nil {
  89. randomPort := 0
  90. randomPort, err = r.AllocationManager.GetRandomEvenPort()
  91. if err != nil {
  92. return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficentCapacityMsg...)
  93. }
  94. requestedPort = randomPort
  95. reservationToken = randSeq(8)
  96. }
  97. // 7. At any point, the server MAY choose to reject the request with a
  98. // 486 (Allocation Quota Reached) error if it feels the client is
  99. // trying to exceed some locally defined allocation quota. The
  100. // server is free to define this allocation quota any way it wishes,
  101. // but SHOULD define it based on the username used to authenticate
  102. // the request, and not on the client's transport address.
  103. // 8. Also at any point, the server MAY choose to reject the request
  104. // with a 300 (Try Alternate) error if it wishes to redirect the
  105. // client to a different server. The use of this error code and
  106. // attribute follow the specification in [RFC5389].
  107. lifetimeDuration := allocationLifeTime(m)
  108. a, err := r.AllocationManager.CreateAllocation(
  109. fiveTuple,
  110. r.Conn,
  111. requestedPort,
  112. lifetimeDuration)
  113. if err != nil {
  114. return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficentCapacityMsg...)
  115. }
  116. // Once the allocation is created, the server replies with a success
  117. // response. The success response contains:
  118. // * An XOR-RELAYED-ADDRESS attribute containing the relayed transport
  119. // address.
  120. // * A LIFETIME attribute containing the current value of the time-to-
  121. // expiry timer.
  122. // * A RESERVATION-TOKEN attribute (if a second relayed transport
  123. // address was reserved).
  124. // * An XOR-MAPPED-ADDRESS attribute containing the client's IP address
  125. // and port (from the 5-tuple).
  126. srcIP, srcPort, err := ipnet.AddrIPPort(r.SrcAddr)
  127. if err != nil {
  128. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  129. }
  130. relayIP, relayPort, err := ipnet.AddrIPPort(a.RelayAddr)
  131. if err != nil {
  132. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  133. }
  134. responseAttrs := []stun.Setter{
  135. &proto.RelayedAddress{
  136. IP: relayIP,
  137. Port: relayPort,
  138. },
  139. &proto.Lifetime{
  140. Duration: lifetimeDuration,
  141. },
  142. &stun.XORMappedAddress{
  143. IP: srcIP,
  144. Port: srcPort,
  145. },
  146. }
  147. if reservationToken != "" {
  148. r.AllocationManager.CreateReservation(reservationToken, relayPort)
  149. responseAttrs = append(responseAttrs, proto.ReservationToken([]byte(reservationToken)))
  150. }
  151. msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassSuccessResponse), append(responseAttrs, messageIntegrity)...)
  152. a.SetResponseCache(m.TransactionID, responseAttrs)
  153. return buildAndSend(r.Conn, r.SrcAddr, msg...)
  154. }
  155. func handleRefreshRequest(r Request, m *stun.Message) error {
  156. r.Log.Debugf("received RefreshRequest from %s", r.SrcAddr.String())
  157. messageIntegrity, hasAuth, err := authenticateRequest(r, m, stun.MethodRefresh)
  158. if !hasAuth {
  159. return err
  160. }
  161. lifetimeDuration := allocationLifeTime(m)
  162. fiveTuple := &allocation.FiveTuple{
  163. SrcAddr: r.SrcAddr,
  164. DstAddr: r.Conn.LocalAddr(),
  165. Protocol: allocation.UDP,
  166. }
  167. if lifetimeDuration != 0 {
  168. a := r.AllocationManager.GetAllocation(fiveTuple)
  169. if a == nil {
  170. return fmt.Errorf("%w %v:%v", errNoAllocationFound, r.SrcAddr, r.Conn.LocalAddr())
  171. }
  172. a.Refresh(lifetimeDuration)
  173. } else {
  174. r.AllocationManager.DeleteAllocation(fiveTuple)
  175. }
  176. return buildAndSend(r.Conn, r.SrcAddr, buildMsg(m.TransactionID, stun.NewType(stun.MethodRefresh, stun.ClassSuccessResponse), []stun.Setter{
  177. &proto.Lifetime{
  178. Duration: lifetimeDuration,
  179. },
  180. messageIntegrity,
  181. }...)...)
  182. }
  183. func handleCreatePermissionRequest(r Request, m *stun.Message) error {
  184. r.Log.Debugf("received CreatePermission from %s", r.SrcAddr.String())
  185. a := r.AllocationManager.GetAllocation(&allocation.FiveTuple{
  186. SrcAddr: r.SrcAddr,
  187. DstAddr: r.Conn.LocalAddr(),
  188. Protocol: allocation.UDP,
  189. })
  190. if a == nil {
  191. return fmt.Errorf("%w %v:%v", errNoAllocationFound, r.SrcAddr, r.Conn.LocalAddr())
  192. }
  193. messageIntegrity, hasAuth, err := authenticateRequest(r, m, stun.MethodCreatePermission)
  194. if !hasAuth {
  195. return err
  196. }
  197. addCount := 0
  198. if err := m.ForEach(stun.AttrXORPeerAddress, func(m *stun.Message) error {
  199. var peerAddress proto.PeerAddress
  200. if err := peerAddress.GetFrom(m); err != nil {
  201. return err
  202. }
  203. r.Log.Debugf("adding permission for %s", fmt.Sprintf("%s:%d",
  204. peerAddress.IP.String(), peerAddress.Port))
  205. a.AddPermission(allocation.NewPermission(
  206. &net.UDPAddr{
  207. IP: peerAddress.IP,
  208. Port: peerAddress.Port,
  209. },
  210. r.Log,
  211. ))
  212. addCount++
  213. return nil
  214. }); err != nil {
  215. addCount = 0
  216. }
  217. respClass := stun.ClassSuccessResponse
  218. if addCount == 0 {
  219. respClass = stun.ClassErrorResponse
  220. }
  221. return buildAndSend(r.Conn, r.SrcAddr, buildMsg(m.TransactionID, stun.NewType(stun.MethodCreatePermission, respClass), []stun.Setter{messageIntegrity}...)...)
  222. }
  223. func handleSendIndication(r Request, m *stun.Message) error {
  224. r.Log.Debugf("received SendIndication from %s", r.SrcAddr.String())
  225. a := r.AllocationManager.GetAllocation(&allocation.FiveTuple{
  226. SrcAddr: r.SrcAddr,
  227. DstAddr: r.Conn.LocalAddr(),
  228. Protocol: allocation.UDP,
  229. })
  230. if a == nil {
  231. return fmt.Errorf("%w %v:%v", errNoAllocationFound, r.SrcAddr, r.Conn.LocalAddr())
  232. }
  233. dataAttr := proto.Data{}
  234. if err := dataAttr.GetFrom(m); err != nil {
  235. return err
  236. }
  237. peerAddress := proto.PeerAddress{}
  238. if err := peerAddress.GetFrom(m); err != nil {
  239. return err
  240. }
  241. msgDst := &net.UDPAddr{IP: peerAddress.IP, Port: peerAddress.Port}
  242. if perm := a.GetPermission(msgDst); perm == nil {
  243. return fmt.Errorf("%w: %v", errNoPermission, msgDst)
  244. }
  245. l, err := a.RelaySocket.WriteTo(dataAttr, msgDst)
  246. if l != len(dataAttr) {
  247. return fmt.Errorf("%w %d != %d (expected) err: %v", errShortWrite, l, len(dataAttr), err)
  248. }
  249. return err
  250. }
  251. func handleChannelBindRequest(r Request, m *stun.Message) error {
  252. r.Log.Debugf("received ChannelBindRequest from %s", r.SrcAddr.String())
  253. a := r.AllocationManager.GetAllocation(&allocation.FiveTuple{
  254. SrcAddr: r.SrcAddr,
  255. DstAddr: r.Conn.LocalAddr(),
  256. Protocol: allocation.UDP,
  257. })
  258. if a == nil {
  259. return fmt.Errorf("%w %v:%v", errNoAllocationFound, r.SrcAddr, r.Conn.LocalAddr())
  260. }
  261. badRequestMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodChannelBind, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeBadRequest})
  262. messageIntegrity, hasAuth, err := authenticateRequest(r, m, stun.MethodChannelBind)
  263. if !hasAuth {
  264. return err
  265. }
  266. var channel proto.ChannelNumber
  267. if err = channel.GetFrom(m); err != nil {
  268. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  269. }
  270. peerAddr := proto.PeerAddress{}
  271. if err = peerAddr.GetFrom(m); err != nil {
  272. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  273. }
  274. r.Log.Debugf("binding channel %d to %s",
  275. channel,
  276. fmt.Sprintf("%s:%d", peerAddr.IP.String(), peerAddr.Port))
  277. err = a.AddChannelBind(allocation.NewChannelBind(
  278. channel,
  279. &net.UDPAddr{IP: peerAddr.IP, Port: peerAddr.Port},
  280. r.Log,
  281. ), r.ChannelBindTimeout)
  282. if err != nil {
  283. return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...)
  284. }
  285. return buildAndSend(r.Conn, r.SrcAddr, buildMsg(m.TransactionID, stun.NewType(stun.MethodChannelBind, stun.ClassSuccessResponse), []stun.Setter{messageIntegrity}...)...)
  286. }
  287. func handleChannelData(r Request, c *proto.ChannelData) error {
  288. r.Log.Debugf("received ChannelData from %s", r.SrcAddr.String())
  289. a := r.AllocationManager.GetAllocation(&allocation.FiveTuple{
  290. SrcAddr: r.SrcAddr,
  291. DstAddr: r.Conn.LocalAddr(),
  292. Protocol: allocation.UDP,
  293. })
  294. if a == nil {
  295. return fmt.Errorf("%w %v:%v", errNoAllocationFound, r.SrcAddr, r.Conn.LocalAddr())
  296. }
  297. channel := a.GetChannelByNumber(c.Number)
  298. if channel == nil {
  299. return fmt.Errorf("%w %x", errNoSuchChannelBind, uint16(c.Number))
  300. }
  301. l, err := a.RelaySocket.WriteTo(c.Data, channel.Peer)
  302. if err != nil {
  303. return fmt.Errorf("%w: %s", errFailedWriteSocket, err.Error())
  304. } else if l != len(c.Data) {
  305. return fmt.Errorf("%w %d != %d (expected)", errShortWrite, l, len(c.Data))
  306. }
  307. return nil
  308. }