ntp.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Copyright 2016 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. //
  7. //******************************************************************************
  8. package layers
  9. import (
  10. "encoding/binary"
  11. "errors"
  12. "github.com/google/gopacket"
  13. )
  14. //******************************************************************************
  15. //
  16. // Network Time Protocol (NTP) Decoding Layer
  17. // ------------------------------------------
  18. // This file provides a GoPacket decoding layer for NTP.
  19. //
  20. //******************************************************************************
  21. //
  22. // About The Network Time Protocol (NTP)
  23. // -------------------------------------
  24. // NTP is a protocol that enables computers on the internet to set their
  25. // clocks to the correct time (or to a time that is acceptably close to the
  26. // correct time). NTP runs on top of UDP.
  27. //
  28. // There have been a series of versions of the NTP protocol. The latest
  29. // version is V4 and is specified in RFC 5905:
  30. // http://www.ietf.org/rfc/rfc5905.txt
  31. //
  32. //******************************************************************************
  33. //
  34. // References
  35. // ----------
  36. //
  37. // Wikipedia's NTP entry:
  38. // https://en.wikipedia.org/wiki/Network_Time_Protocol
  39. // This is the best place to get an overview of NTP.
  40. //
  41. // Network Time Protocol Home Website:
  42. // http://www.ntp.org/
  43. // This appears to be the official website of NTP.
  44. //
  45. // List of current NTP Protocol RFCs:
  46. // http://www.ntp.org/rfc.html
  47. //
  48. // RFC 958: "Network Time Protocol (NTP)" (1985)
  49. // https://tools.ietf.org/html/rfc958
  50. // This is the original NTP specification.
  51. //
  52. // RFC 1305: "Network Time Protocol (Version 3) Specification, Implementation and Analysis" (1992)
  53. // https://tools.ietf.org/html/rfc1305
  54. // The protocol was updated in 1992 yielding NTP V3.
  55. //
  56. // RFC 5905: "Network Time Protocol Version 4: Protocol and Algorithms Specification" (2010)
  57. // https://www.ietf.org/rfc/rfc5905.txt
  58. // The protocol was updated in 2010 yielding NTP V4.
  59. // V4 is backwards compatible with all previous versions of NTP.
  60. //
  61. // RFC 5906: "Network Time Protocol Version 4: Autokey Specification"
  62. // https://tools.ietf.org/html/rfc5906
  63. // This document addresses the security of the NTP protocol
  64. // and is probably not relevant to this package.
  65. //
  66. // RFC 5907: "Definitions of Managed Objects for Network Time Protocol Version 4 (NTPv4)"
  67. // https://tools.ietf.org/html/rfc5907
  68. // This document addresses the management of NTP servers and
  69. // is probably not relevant to this package.
  70. //
  71. // RFC 5908: "Network Time Protocol (NTP) Server Option for DHCPv6"
  72. // https://tools.ietf.org/html/rfc5908
  73. // This document addresses the use of NTP in DHCPv6 and is
  74. // probably not relevant to this package.
  75. //
  76. // "Let's make a NTP Client in C"
  77. // https://lettier.github.io/posts/2016-04-26-lets-make-a-ntp-client-in-c.html
  78. // This web page contains useful information about the details of NTP,
  79. // including an NTP record struture in C, and C code.
  80. //
  81. // "NTP Packet Header (NTP Reference Implementation) (Computer Network Time Synchronization)"
  82. // http://what-when-how.com/computer-network-time-synchronization/
  83. // ntp-packet-header-ntp-reference-implementation-computer-network-time-synchronization/
  84. // This web page contains useful information on the details of NTP.
  85. //
  86. // "Technical information - NTP Data Packet"
  87. // https://www.meinbergglobal.com/english/info/ntp-packet.htm
  88. // This page has a helpful diagram of an NTP V4 packet.
  89. //
  90. //******************************************************************************
  91. //
  92. // Obsolete References
  93. // -------------------
  94. //
  95. // RFC 1119: "RFC-1119 "Network Time Protocol (Version 2) Specification and Implementation" (1989)
  96. // https://tools.ietf.org/html/rfc1119
  97. // Version 2 was drafted in 1989.
  98. // It is unclear whether V2 was ever implememented or whether the
  99. // ideas ended up in V3 (which was implemented in 1992).
  100. //
  101. // RFC 1361: "Simple Network Time Protocol (SNTP)"
  102. // https://tools.ietf.org/html/rfc1361
  103. // This document is obsoleted by RFC 1769 and is included only for completeness.
  104. //
  105. // RFC 1769: "Simple Network Time Protocol (SNTP)"
  106. // https://tools.ietf.org/html/rfc1769
  107. // This document is obsoleted by RFC 2030 and RFC 4330 and is included only for completeness.
  108. //
  109. // RFC 2030: "Simple Network Time Protocol (SNTP) Version 4 for IPv4, IPv6 and OSI"
  110. // https://tools.ietf.org/html/rfc2030
  111. // This document is obsoleted by RFC 4330 and is included only for completeness.
  112. //
  113. // RFC 4330: "Simple Network Time Protocol (SNTP) Version 4 for IPv4, IPv6 and OSI"
  114. // https://tools.ietf.org/html/rfc4330
  115. // This document is obsoleted by RFC 5905 and is included only for completeness.
  116. //
  117. //******************************************************************************
  118. //
  119. // Endian And Bit Numbering Issues
  120. // -------------------------------
  121. //
  122. // Endian and bit numbering issues can be confusing. Here is some
  123. // clarification:
  124. //
  125. // ENDIAN: Values are sent big endian.
  126. // https://en.wikipedia.org/wiki/Endianness
  127. //
  128. // BIT NUMBERING: Bits are numbered 0 upwards from the most significant
  129. // bit to the least significant bit. This means that if there is a 32-bit
  130. // value, the most significant bit is called bit 0 and the least
  131. // significant bit is called bit 31.
  132. //
  133. // See RFC 791 Appendix B for more discussion.
  134. //
  135. //******************************************************************************
  136. //
  137. // NTP V3 and V4 Packet Format
  138. // ---------------------------
  139. // NTP packets are UDP packets whose payload contains an NTP record.
  140. //
  141. // The NTP RFC defines the format of the NTP record.
  142. //
  143. // There have been four versions of the protocol:
  144. //
  145. // V1 in 1985
  146. // V2 in 1989
  147. // V3 in 1992
  148. // V4 in 2010
  149. //
  150. // It is clear that V1 and V2 are obsolete, and there is no need to
  151. // cater for these formats.
  152. //
  153. // V3 and V4 essentially use the same format, with V4 adding some optional
  154. // fields on the end. So this package supports the V3 and V4 formats.
  155. //
  156. // The current version of NTP (NTP V4)'s RFC (V4 - RFC 5905) contains
  157. // the following diagram for the NTP record format:
  158. // 0 1 2 3
  159. // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  160. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  161. // |LI | VN |Mode | Stratum | Poll | Precision |
  162. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  163. // | Root Delay |
  164. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  165. // | Root Dispersion |
  166. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  167. // | Reference ID |
  168. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  169. // | |
  170. // + Reference Timestamp (64) +
  171. // | |
  172. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  173. // | |
  174. // + Origin Timestamp (64) +
  175. // | |
  176. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  177. // | |
  178. // + Receive Timestamp (64) +
  179. // | |
  180. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  181. // | |
  182. // + Transmit Timestamp (64) +
  183. // | |
  184. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  185. // | |
  186. // . .
  187. // . Extension Field 1 (variable) .
  188. // . .
  189. // | |
  190. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  191. // | |
  192. // . .
  193. // . Extension Field 2 (variable) .
  194. // . .
  195. // | |
  196. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  197. // | Key Identifier |
  198. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  199. // | |
  200. // | dgst (128) |
  201. // | |
  202. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  203. // From http://www.ietf.org/rfc/rfc5905.txt
  204. //
  205. // The fields "Extension Field 1 (variable)" and later are optional fields,
  206. // and so we can set a minimum NTP record size of 48 bytes.
  207. //
  208. const ntpMinimumRecordSizeInBytes int = 48
  209. //******************************************************************************
  210. // NTP Type
  211. // --------
  212. // Type NTP implements the DecodingLayer interface. Each NTP object
  213. // represents in a structured form the NTP record present as the UDP
  214. // payload in an NTP UDP packet.
  215. //
  216. type NTPLeapIndicator uint8
  217. type NTPVersion uint8
  218. type NTPMode uint8
  219. type NTPStratum uint8
  220. type NTPLog2Seconds int8
  221. type NTPFixed16Seconds uint32
  222. type NTPReferenceID uint32
  223. type NTPTimestamp uint64
  224. type NTP struct {
  225. BaseLayer // Stores the packet bytes and payload bytes.
  226. LeapIndicator NTPLeapIndicator // [0,3]. Indicates whether leap second(s) is to be added.
  227. Version NTPVersion // [0,7]. Version of the NTP protocol.
  228. Mode NTPMode // [0,7]. Mode.
  229. Stratum NTPStratum // [0,255]. Stratum of time server in the server tree.
  230. Poll NTPLog2Seconds // [-128,127]. The maximum interval between successive messages, in log2 seconds.
  231. Precision NTPLog2Seconds // [-128,127]. The precision of the system clock, in log2 seconds.
  232. RootDelay NTPFixed16Seconds // [0,2^32-1]. Total round trip delay to the reference clock in seconds times 2^16.
  233. RootDispersion NTPFixed16Seconds // [0,2^32-1]. Total dispersion to the reference clock, in seconds times 2^16.
  234. ReferenceID NTPReferenceID // ID code of reference clock [0,2^32-1].
  235. ReferenceTimestamp NTPTimestamp // Most recent timestamp from the reference clock.
  236. OriginTimestamp NTPTimestamp // Local time when request was sent from local host.
  237. ReceiveTimestamp NTPTimestamp // Local time (on server) that request arrived at server host.
  238. TransmitTimestamp NTPTimestamp // Local time (on server) that request departed server host.
  239. // FIX: This package should analyse the extension fields and represent the extension fields too.
  240. ExtensionBytes []byte // Just put extensions in a byte slice.
  241. }
  242. //******************************************************************************
  243. // LayerType returns the layer type of the NTP object, which is LayerTypeNTP.
  244. func (d *NTP) LayerType() gopacket.LayerType {
  245. return LayerTypeNTP
  246. }
  247. //******************************************************************************
  248. // decodeNTP analyses a byte slice and attempts to decode it as an NTP
  249. // record of a UDP packet.
  250. //
  251. // If it succeeds, it loads p with information about the packet and returns nil.
  252. // If it fails, it returns an error (non nil).
  253. //
  254. // This function is employed in layertypes.go to register the NTP layer.
  255. func decodeNTP(data []byte, p gopacket.PacketBuilder) error {
  256. // Attempt to decode the byte slice.
  257. d := &NTP{}
  258. err := d.DecodeFromBytes(data, p)
  259. if err != nil {
  260. return err
  261. }
  262. // If the decoding worked, add the layer to the packet and set it
  263. // as the application layer too, if there isn't already one.
  264. p.AddLayer(d)
  265. p.SetApplicationLayer(d)
  266. return nil
  267. }
  268. //******************************************************************************
  269. // DecodeFromBytes analyses a byte slice and attempts to decode it as an NTP
  270. // record of a UDP packet.
  271. //
  272. // Upon succeeds, it loads the NTP object with information about the packet
  273. // and returns nil.
  274. // Upon failure, it returns an error (non nil).
  275. func (d *NTP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  276. // If the data block is too short to be a NTP record, then return an error.
  277. if len(data) < ntpMinimumRecordSizeInBytes {
  278. df.SetTruncated()
  279. return errors.New("NTP packet too short")
  280. }
  281. // RFC 5905 does not appear to define a maximum NTP record length.
  282. // The protocol allows "extension fields" to be included in the record,
  283. // and states about these fields:"
  284. //
  285. // "While the minimum field length containing required fields is
  286. // four words (16 octets), a maximum field length remains to be
  287. // established."
  288. //
  289. // For this reason, the packet length is not checked here for being too long.
  290. // NTP type embeds type BaseLayer which contains two fields:
  291. // Contents is supposed to contain the bytes of the data at this level.
  292. // Payload is supposed to contain the payload of this level.
  293. // Here we set the baselayer to be the bytes of the NTP record.
  294. d.BaseLayer = BaseLayer{Contents: data[:len(data)]}
  295. // Extract the fields from the block of bytes.
  296. // To make sense of this, refer to the packet diagram
  297. // above and the section on endian conventions.
  298. // The first few fields are all packed into the first 32 bits. Unpack them.
  299. f := data[0]
  300. d.LeapIndicator = NTPLeapIndicator((f & 0xC0) >> 6)
  301. d.Version = NTPVersion((f & 0x38) >> 3)
  302. d.Mode = NTPMode(f & 0x07)
  303. d.Stratum = NTPStratum(data[1])
  304. d.Poll = NTPLog2Seconds(data[2])
  305. d.Precision = NTPLog2Seconds(data[3])
  306. // The remaining fields can just be copied in big endian order.
  307. d.RootDelay = NTPFixed16Seconds(binary.BigEndian.Uint32(data[4:8]))
  308. d.RootDispersion = NTPFixed16Seconds(binary.BigEndian.Uint32(data[8:12]))
  309. d.ReferenceID = NTPReferenceID(binary.BigEndian.Uint32(data[12:16]))
  310. d.ReferenceTimestamp = NTPTimestamp(binary.BigEndian.Uint64(data[16:24]))
  311. d.OriginTimestamp = NTPTimestamp(binary.BigEndian.Uint64(data[24:32]))
  312. d.ReceiveTimestamp = NTPTimestamp(binary.BigEndian.Uint64(data[32:40]))
  313. d.TransmitTimestamp = NTPTimestamp(binary.BigEndian.Uint64(data[40:48]))
  314. // This layer does not attempt to analyse the extension bytes.
  315. // But if there are any, we'd like the user to know. So we just
  316. // place them all in an ExtensionBytes field.
  317. d.ExtensionBytes = data[48:]
  318. // Return no error.
  319. return nil
  320. }
  321. // SerializeTo writes the serialized form of this layer into the
  322. // SerializationBuffer, implementing gopacket.SerializableLayer.
  323. // See the docs for gopacket.SerializableLayer for more info.
  324. func (d *NTP) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
  325. data, err := b.PrependBytes(ntpMinimumRecordSizeInBytes)
  326. if err != nil {
  327. return err
  328. }
  329. // Pack the first few fields into the first 32 bits.
  330. h := uint8(0)
  331. h |= (uint8(d.LeapIndicator) << 6) & 0xC0
  332. h |= (uint8(d.Version) << 3) & 0x38
  333. h |= (uint8(d.Mode)) & 0x07
  334. data[0] = byte(h)
  335. data[1] = byte(d.Stratum)
  336. data[2] = byte(d.Poll)
  337. data[3] = byte(d.Precision)
  338. // The remaining fields can just be copied in big endian order.
  339. binary.BigEndian.PutUint32(data[4:8], uint32(d.RootDelay))
  340. binary.BigEndian.PutUint32(data[8:12], uint32(d.RootDispersion))
  341. binary.BigEndian.PutUint32(data[12:16], uint32(d.ReferenceID))
  342. binary.BigEndian.PutUint64(data[16:24], uint64(d.ReferenceTimestamp))
  343. binary.BigEndian.PutUint64(data[24:32], uint64(d.OriginTimestamp))
  344. binary.BigEndian.PutUint64(data[32:40], uint64(d.ReceiveTimestamp))
  345. binary.BigEndian.PutUint64(data[40:48], uint64(d.TransmitTimestamp))
  346. ex, err := b.AppendBytes(len(d.ExtensionBytes))
  347. if err != nil {
  348. return err
  349. }
  350. copy(ex, d.ExtensionBytes)
  351. return nil
  352. }
  353. //******************************************************************************
  354. // CanDecode returns a set of layers that NTP objects can decode.
  355. // As NTP objects can only decide the NTP layer, we can return just that layer.
  356. // Apparently a single layer type implements LayerClass.
  357. func (d *NTP) CanDecode() gopacket.LayerClass {
  358. return LayerTypeNTP
  359. }
  360. //******************************************************************************
  361. // NextLayerType specifies the next layer that GoPacket should attempt to
  362. // analyse after this (NTP) layer. As NTP packets do not contain any payload
  363. // bytes, there are no further layers to analyse.
  364. func (d *NTP) NextLayerType() gopacket.LayerType {
  365. return gopacket.LayerTypeZero
  366. }
  367. //******************************************************************************
  368. // NTP packets do not carry any data payload, so the empty byte slice is retured.
  369. // In Go, a nil slice is functionally identical to an empty slice, so we
  370. // return nil to avoid a heap allocation.
  371. func (d *NTP) Payload() []byte {
  372. return nil
  373. }
  374. //******************************************************************************
  375. //* End Of NTP File *
  376. //******************************************************************************