Packet.hpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_N_PACKET_HPP
  14. #define ZT_N_PACKET_HPP
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <stdio.h>
  18. #include <string>
  19. #include <iostream>
  20. #include "Constants.hpp"
  21. #include "Address.hpp"
  22. #include "Poly1305.hpp"
  23. #include "Salsa20.hpp"
  24. #include "Utils.hpp"
  25. #include "Buffer.hpp"
  26. /**
  27. * Protocol version -- incremented only for major changes
  28. *
  29. * 1 - 0.2.0 ... 0.2.5
  30. * 2 - 0.3.0 ... 0.4.5
  31. * + Added signature and originating peer to multicast frame
  32. * + Double size of multicast frame bloom filter
  33. * 3 - 0.5.0 ... 0.6.0
  34. * + Yet another multicast redesign
  35. * + New crypto completely changes key agreement cipher
  36. * 4 - 0.6.0 ... 1.0.6
  37. * + BREAKING CHANGE: New identity format based on hashcash design
  38. * 5 - 1.1.0 ... 1.1.5
  39. * + Supports echo
  40. * + Supports in-band world (root server definition) updates
  41. * + Clustering! (Though this will work with protocol v4 clients.)
  42. * + Otherwise backward compatible with protocol v4
  43. * 6 - 1.1.5 ... 1.1.10
  44. * + Network configuration format revisions including binary values
  45. * 7 - 1.1.10 ... 1.1.17
  46. * + Introduce trusted paths for local SDN use
  47. * 8 - 1.1.17 ... 1.2.0
  48. * + Multipart network configurations for large network configs
  49. * + Tags and Capabilities
  50. * + ZT_ALWAYS_INLINE push of CertificateOfMembership deprecated
  51. * 9 - 1.2.0 ... 1.2.14
  52. * 10 - 1.4.0 ... 1.6.0
  53. * + Multipath capability and load balancing
  54. * 11 - 2.0.0 ... CURRENT
  55. * + Peer-to-peer multicast replication (optional)
  56. * + Old planet/moon stuff is DEAD!
  57. * + AES-256-GMAC-CTR encryption is now the default
  58. * + NIST P-384 (type 1) identities now supported
  59. * + WILL_RELAY allows mesh-like operation
  60. * + Ephemeral keys are now negotiated opportunistically
  61. */
  62. #define ZT_PROTO_VERSION 11
  63. /**
  64. * Minimum supported protocol version
  65. */
  66. #define ZT_PROTO_VERSION_MIN 6
  67. /**
  68. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  69. *
  70. * This is a protocol constant. It's the maximum allowed by the length
  71. * of the hop counter -- three bits. See node/Constants.hpp for the
  72. * pragmatic forwarding limit, which is typically lower.
  73. */
  74. #define ZT_PROTO_MAX_HOPS 7
  75. /**
  76. * NONE/Poly1305 (using Salsa20/12 to generate poly1305 key)
  77. */
  78. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  79. /**
  80. * Salsa2012/Poly1305
  81. */
  82. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  83. /**
  84. * No encryption or authentication at all
  85. *
  86. * For trusted paths the MAC field is the trusted path ID.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__NONE 2
  89. /**
  90. * AES-GMAC_SIV with AES-256
  91. */
  92. #define ZT_PROTO_CIPHER_SUITE__AES256_GMAC_SIV 3
  93. /**
  94. * Header flag indicating that a packet is fragmented
  95. *
  96. * If this flag is set, the receiver knows to expect more than one fragment.
  97. * See Packet::Fragment for details.
  98. */
  99. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  100. /**
  101. * Verb flag indicating payload is compressed with LZ4
  102. */
  103. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  104. // Field indexes in packet header
  105. #define ZT_PACKET_IDX_IV 0
  106. #define ZT_PACKET_IDX_DEST 8
  107. #define ZT_PACKET_IDX_SOURCE 13
  108. #define ZT_PACKET_IDX_FLAGS 18
  109. #define ZT_PACKET_IDX_MAC 19
  110. #define ZT_PACKET_IDX_VERB 27
  111. #define ZT_PACKET_IDX_PAYLOAD 28
  112. /**
  113. * Packet buffer size (can be changed)
  114. */
  115. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_DEFAULT_PHYSMTU)
  116. /**
  117. * Minimum viable packet length (a.k.a. header length)
  118. */
  119. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  120. // Indexes of fields in fragment header
  121. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  122. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  123. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  124. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  125. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  126. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  127. /**
  128. * Magic number found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR
  129. */
  130. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  131. /**
  132. * Minimum viable fragment length
  133. */
  134. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  135. // Field indices for parsing verbs -------------------------------------------
  136. // Some verbs have variable-length fields. Those aren't fully defined here
  137. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  138. // See their respective handler functions.
  139. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  140. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  141. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  142. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  143. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  144. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  145. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  146. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  147. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  148. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  149. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  150. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  151. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  152. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  153. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  154. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  155. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  156. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  157. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  158. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  159. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  160. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  161. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  162. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  163. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  164. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  165. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  166. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  167. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  168. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  169. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  170. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  171. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  172. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  173. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  174. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  175. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  176. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  177. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  178. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  179. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  180. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  181. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT + 4)
  182. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  183. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  184. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  185. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  186. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  187. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  188. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  189. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  190. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  191. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  192. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  193. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  194. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  195. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  196. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  197. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  198. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  199. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  200. // ---------------------------------------------------------------------------
  201. namespace ZeroTier {
  202. /**
  203. * ZeroTier packet
  204. *
  205. * Packet format:
  206. * <[8] 64-bit packet ID / crypto IV>
  207. * <[5] destination ZT address>
  208. * <[5] source ZT address>
  209. * <[1] flags/cipher/hops>
  210. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  211. * [... -- begin encryption envelope -- ...]
  212. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  213. * [... verb-specific payload ...]
  214. *
  215. * Packets smaller than 28 bytes are invalid and silently discarded.
  216. *
  217. * The 64-bit packet ID is a strongly random value used as a crypto IV.
  218. * Its least significant 3 bits are also used as a monotonically increasing
  219. * (and looping) counter for sending packets to a particular recipient. This
  220. * can be used for link quality monitoring and reporting and has no crypto
  221. * impact as it does not increase the likelihood of an IV collision. (The
  222. * crypto we use is not sensitive to the nature of the IV, only that it does
  223. * not repeat.)
  224. *
  225. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  226. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  227. * and H is hop count.
  228. *
  229. * The three-bit hop count is the only part of a packet that is mutable in
  230. * transit without invalidating the MAC. All other bits in the packet are
  231. * immutable. This is because intermediate nodes can increment the hop
  232. * count up to 7 (protocol max).
  233. *
  234. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  235. * sent in the clear, as it's the "here is my public key" message.
  236. */
  237. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  238. {
  239. public:
  240. /**
  241. * A packet fragment
  242. *
  243. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  244. * is sent with its normal header with the fragmented flag set. Remaining
  245. * fragments are sent this way.
  246. *
  247. * The fragmented bit indicates that there is at least one fragment. Fragments
  248. * themselves contain the total, so the receiver must "learn" this from the
  249. * first fragment it receives.
  250. *
  251. * Fragments are sent with the following format:
  252. * <[8] packet ID of packet whose fragment this belongs to>
  253. * <[5] destination ZT address>
  254. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  255. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  256. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  257. * <[...] fragment data>
  258. *
  259. * The protocol supports a maximum of 16 fragments. If a fragment is received
  260. * before its main packet header, it should be cached for a brief period of
  261. * time to see if its parent arrives. Loss of any fragment constitutes packet
  262. * loss; there is no retransmission mechanism. The receiver must wait for full
  263. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  264. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  265. */
  266. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  267. {
  268. public:
  269. ZT_ALWAYS_INLINE Fragment() :
  270. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>() {}
  271. template<unsigned int C2>
  272. ZT_ALWAYS_INLINE Fragment(const Buffer<C2> &b) :
  273. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b) {}
  274. ZT_ALWAYS_INLINE Fragment(const void *data,unsigned int len) :
  275. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len) {}
  276. /**
  277. * Initialize from a packet
  278. *
  279. * @param p Original assembled packet
  280. * @param fragStart Start of fragment (raw index in packet data)
  281. * @param fragLen Length of fragment in bytes
  282. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  283. * @param fragTotal Total number of fragments (including 0)
  284. */
  285. ZT_ALWAYS_INLINE Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  286. {
  287. init(p,fragStart,fragLen,fragNo,fragTotal);
  288. }
  289. /**
  290. * Initialize from a packet
  291. *
  292. * @param p Original assembled packet
  293. * @param fragStart Start of fragment (raw index in packet data)
  294. * @param fragLen Length of fragment in bytes
  295. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  296. * @param fragTotal Total number of fragments (including 0)
  297. */
  298. ZT_ALWAYS_INLINE void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  299. {
  300. if ((fragStart + fragLen) > p.size())
  301. throw ZT_EXCEPTION_OUT_OF_BOUNDS;
  302. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  303. // NOTE: this copies both the IV/packet ID and the destination address.
  304. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  305. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  306. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  307. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  308. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  309. }
  310. /**
  311. * Get this fragment's destination
  312. *
  313. * @return Destination ZT address
  314. */
  315. ZT_ALWAYS_INLINE Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  316. /**
  317. * @return True if fragment is of a valid length
  318. */
  319. ZT_ALWAYS_INLINE bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  320. /**
  321. * @return ID of packet this is a fragment of
  322. */
  323. ZT_ALWAYS_INLINE uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  324. /**
  325. * @return Total number of fragments in packet
  326. */
  327. ZT_ALWAYS_INLINE unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  328. /**
  329. * @return Fragment number of this fragment
  330. */
  331. ZT_ALWAYS_INLINE unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  332. /**
  333. * @return Fragment ZT hop count
  334. */
  335. ZT_ALWAYS_INLINE unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  336. /**
  337. * Increment this packet's hop count
  338. */
  339. ZT_ALWAYS_INLINE unsigned int incrementHops()
  340. {
  341. return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1));
  342. }
  343. /**
  344. * @return Length of payload in bytes
  345. */
  346. ZT_ALWAYS_INLINE unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  347. /**
  348. * @return Raw packet payload
  349. */
  350. ZT_ALWAYS_INLINE const unsigned char *payload() const { return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  351. };
  352. /**
  353. * ZeroTier protocol verbs
  354. */
  355. enum Verb /* Max value: 32 (5 bits) */
  356. {
  357. /**
  358. * No operation (ignored, no reply)
  359. */
  360. VERB_NOP = 0x00,
  361. /**
  362. * Announcement of a node's existence and vitals:
  363. * <[1] protocol version>
  364. * <[1] software major version>
  365. * <[1] software minor version>
  366. * <[2] software revision>
  367. * <[8] timestamp for determining latency>
  368. * <[...] binary serialized identity (see Identity)>
  369. * <[...] physical destination address of packet>
  370. *
  371. * HELLO is sent in the clear as it is how peers share their identity
  372. * public keys.
  373. *
  374. * Destination address is the actual wire address to which the packet
  375. * was sent. See InetAddress::serialize() for format.
  376. *
  377. * OK payload:
  378. * <[8] HELLO timestamp field echo>
  379. * <[1] protocol version>
  380. * <[1] software major version>
  381. * <[1] software minor version>
  382. * <[2] software revision>
  383. * <[...] physical destination address of packet>
  384. *
  385. * With the exception of the timestamp, the other fields pertain to the
  386. * respondent who is sending OK and are not echoes.
  387. *
  388. * ERROR has no payload.
  389. */
  390. VERB_HELLO = 0x01,
  391. /**
  392. * Error response:
  393. * <[1] in-re verb>
  394. * <[8] in-re packet ID>
  395. * <[1] error code>
  396. * <[...] error-dependent payload>
  397. *
  398. * If this is not in response to a single packet then verb can be
  399. * NOP and packet ID can be zero.
  400. */
  401. VERB_ERROR = 0x02,
  402. /**
  403. * Success response:
  404. * <[1] in-re verb>
  405. * <[8] in-re packet ID>
  406. * <[...] request-specific payload>
  407. */
  408. VERB_OK = 0x03,
  409. /**
  410. * Query an identity by address:
  411. * <[5] address to look up>
  412. * [<[...] additional addresses to look up>
  413. *
  414. * OK response payload:
  415. * <[...] binary serialized identity>
  416. * [<[...] additional binary serialized identities>]
  417. *
  418. * If querying a cluster, duplicate OK responses may occasionally occur.
  419. * These must be tolerated, which is easy since they'll have info you
  420. * already have.
  421. *
  422. * If the address is not found, no response is generated. The semantics
  423. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  424. * be performed.
  425. */
  426. VERB_WHOIS = 0x04,
  427. /**
  428. * Relay-mediated NAT traversal or firewall punching initiation:
  429. * <[1] flags (unused, currently 0)>
  430. * <[5] ZeroTier address of peer that might be found at this address>
  431. * <[2] 16-bit protocol address port>
  432. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  433. * <[...] protocol address (network byte order)>
  434. *
  435. * An upstream node can send this to inform both sides of a relay of
  436. * information they might use to establish a direct connection.
  437. *
  438. * Upon receipt a peer sends HELLO to establish a direct link.
  439. *
  440. * No OK or ERROR is generated.
  441. */
  442. VERB_RENDEZVOUS = 0x05,
  443. /**
  444. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  445. * <[8] 64-bit network ID>
  446. * <[2] 16-bit ethertype>
  447. * <[...] ethernet payload>
  448. *
  449. * MAC addresses are derived from the packet's source and destination
  450. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  451. * Ethernet framing and other optional flags and features when they
  452. * are not necessary.
  453. *
  454. * ERROR may be generated if a membership certificate is needed for a
  455. * closed network. Payload will be network ID.
  456. */
  457. VERB_FRAME = 0x06,
  458. /**
  459. * Full Ethernet frame with MAC addressing and optional fields:
  460. * <[8] 64-bit network ID>
  461. * <[1] flags>
  462. * <[6] destination MAC or all zero for destination node>
  463. * <[6] source MAC or all zero for node of origin>
  464. * <[2] 16-bit ethertype>
  465. * <[...] ethernet payload>
  466. *
  467. * Flags:
  468. * 0x01 - Certificate of network membership attached (DEPRECATED)
  469. * 0x02 - Most significant bit of subtype (see below)
  470. * 0x04 - Middle bit of subtype (see below)
  471. * 0x08 - Least significant bit of subtype (see below)
  472. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  473. *
  474. * Subtypes (0..7):
  475. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  476. * 0x1 - TEEd outbound frame
  477. * 0x2 - REDIRECTed outbound frame
  478. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  479. * 0x4 - TEEd inbound frame
  480. * 0x5 - REDIRECTed inbound frame
  481. * 0x6 - WATCHed inbound frame
  482. * 0x7 - (reserved for future use)
  483. *
  484. * An extended frame carries full MAC addressing, making it a
  485. * superset of VERB_FRAME. It is used for bridged traffic,
  486. * redirected or observed traffic via rules, and can in theory
  487. * be used for multicast though MULTICAST_FRAME exists for that
  488. * purpose and has additional options and capabilities.
  489. *
  490. * OK payload (if ACK flag is set):
  491. * <[8] 64-bit network ID>
  492. */
  493. VERB_EXT_FRAME = 0x07,
  494. /**
  495. * ECHO request (a.k.a. ping):
  496. * <[...] arbitrary payload>
  497. *
  498. * This generates OK with a copy of the transmitted payload. No ERROR
  499. * is generated. Response to ECHO requests is optional and ECHO may be
  500. * ignored if a node detects a possible flood.
  501. */
  502. VERB_ECHO = 0x08,
  503. /**
  504. * Announce interest in multicast group(s):
  505. * <[8] 64-bit network ID>
  506. * <[6] multicast Ethernet address>
  507. * <[4] multicast additional distinguishing information (ADI)>
  508. * [... additional tuples of network/address/adi ...]
  509. *
  510. * OK/ERROR are not generated.
  511. */
  512. VERB_MULTICAST_LIKE = 0x09,
  513. /**
  514. * Network credentials push:
  515. * [<[...] one or more certificates of membership>]
  516. * <[1] 0x00, null byte marking end of COM array>
  517. * <[2] 16-bit number of capabilities>
  518. * <[...] one or more serialized Capability>
  519. * <[2] 16-bit number of tags>
  520. * <[...] one or more serialized Tags>
  521. * <[2] 16-bit number of revocations>
  522. * <[...] one or more serialized Revocations>
  523. * <[2] 16-bit number of certificates of ownership>
  524. * <[...] one or more serialized CertificateOfOwnership>
  525. *
  526. * This can be sent by anyone at any time to push network credentials.
  527. * These will of course only be accepted if they are properly signed.
  528. * Credentials can be for any number of networks.
  529. *
  530. * The use of a zero byte to terminate the COM section is for legacy
  531. * backward compatibility. Newer fields are prefixed with a length.
  532. *
  533. * OK/ERROR are not generated.
  534. */
  535. VERB_NETWORK_CREDENTIALS = 0x0a,
  536. /**
  537. * Network configuration request:
  538. * <[8] 64-bit network ID>
  539. * <[2] 16-bit length of request meta-data dictionary>
  540. * <[...] string-serialized request meta-data>
  541. * <[8] 64-bit revision of netconf we currently have>
  542. * <[8] 64-bit timestamp of netconf we currently have>
  543. *
  544. * This message requests network configuration from a node capable of
  545. * providing it.
  546. *
  547. * Responses to this are always whole configs intended for the recipient.
  548. * For patches and other updates a NETWORK_CONFIG is sent instead.
  549. *
  550. * It would be valid and correct as of 1.2.0 to use NETWORK_CONFIG always,
  551. * but OK(NETWORK_CONFIG_REQUEST) should be sent for compatibility.
  552. *
  553. * OK response payload:
  554. * <[8] 64-bit network ID>
  555. * <[2] 16-bit length of network configuration dictionary chunk>
  556. * <[...] network configuration dictionary (may be incomplete)>
  557. * [ ... end of legacy single chunk response ... ]
  558. * <[1] 8-bit flags>
  559. * <[8] 64-bit config update ID (should never be 0)>
  560. * <[4] 32-bit total length of assembled dictionary>
  561. * <[4] 32-bit index of chunk>
  562. * [ ... end signed portion ... ]
  563. * <[1] 8-bit chunk signature type>
  564. * <[2] 16-bit length of chunk signature>
  565. * <[...] chunk signature>
  566. *
  567. * The chunk signature signs the entire payload of the OK response.
  568. * Currently only one signature type is supported: ed25519 (1).
  569. *
  570. * Each config chunk is signed to prevent memory exhaustion or
  571. * traffic crowding DOS attacks against config fragment assembly.
  572. *
  573. * If the packet is from the network controller it is permitted to end
  574. * before the config update ID or other chunking related or signature
  575. * fields. This is to support older controllers that don't include
  576. * these fields and may be removed in the future.
  577. *
  578. * ERROR response payload:
  579. * <[8] 64-bit network ID>
  580. */
  581. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  582. /**
  583. * Network configuration data push:
  584. * <[8] 64-bit network ID>
  585. * <[2] 16-bit length of network configuration dictionary chunk>
  586. * <[...] network configuration dictionary (may be incomplete)>
  587. * <[1] 8-bit flags>
  588. * <[8] 64-bit config update ID (should never be 0)>
  589. * <[4] 32-bit total length of assembled dictionary>
  590. * <[4] 32-bit index of chunk>
  591. * [ ... end signed portion ... ]
  592. * <[1] 8-bit chunk signature type>
  593. * <[2] 16-bit length of chunk signature>
  594. * <[...] chunk signature>
  595. *
  596. * This is a direct push variant for network config updates. It otherwise
  597. * carries the same payload as OK(NETWORK_CONFIG_REQUEST) and has the same
  598. * semantics.
  599. *
  600. * The legacy mode missing the additional chunking fields is not supported
  601. * here.
  602. *
  603. * Flags:
  604. * 0x01 - Use fast propagation
  605. *
  606. * An OK should be sent if the config is successfully received and
  607. * accepted.
  608. *
  609. * OK payload:
  610. * <[8] 64-bit network ID>
  611. * <[8] 64-bit config update ID>
  612. */
  613. VERB_NETWORK_CONFIG = 0x0c,
  614. /**
  615. * Request endpoints for multicast distribution:
  616. * <[8] 64-bit network ID>
  617. * <[1] flags (unused, must be 0)>
  618. * <[6] MAC address of multicast group being queried>
  619. * <[4] 32-bit ADI for multicast group being queried>
  620. * <[4] 32-bit requested max number of multicast peers>
  621. *
  622. * More than one OK response can occur if the response is broken up across
  623. * multiple packets or if querying a clustered node.
  624. *
  625. * OK response payload:
  626. * <[8] 64-bit network ID>
  627. * <[6] MAC address of multicast group being queried>
  628. * <[4] 32-bit ADI for multicast group being queried>
  629. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  630. * <[4] 32-bit total number of known members in this multicast group>
  631. * <[2] 16-bit number of members enumerated in this packet>
  632. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  633. *
  634. * ERROR is not generated; queries that return no response are dropped.
  635. */
  636. VERB_MULTICAST_GATHER = 0x0d,
  637. /**
  638. * Multicast frame:
  639. * <[8] 64-bit network ID>
  640. * <[1] flags>
  641. * [<[...] network certificate of membership (DEPRECATED)>]
  642. * [<[4] 32-bit implicit gather limit (DEPRECATED)>]
  643. * [<[5] ZeroTier address of originating sender (including w/0x08)>]
  644. * [<[2] 16-bit bloom filter multiplier>]
  645. * [<[2] 16-bit length of propagation bloom filter in bytes]
  646. * [<[...] propagation bloom filter>]
  647. * [<[6] source MAC>]
  648. * <[6] destination MAC (multicast address)>
  649. * <[4] 32-bit multicast ADI (multicast address extension)>
  650. * <[2] 16-bit ethertype>
  651. * <[...] ethernet payload>
  652. * [<[2] 16-bit length of signature>]
  653. * [<[...] signature (algorithm depends on sender identity)>]
  654. *
  655. * Flags:
  656. * 0x01 - Network certificate of membership attached (DEPRECATED)
  657. * 0x02 - Implicit gather limit field is present (DEPRECATED)
  658. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  659. * 0x08 - Propagation bloom filter is included
  660. * 0x10 - Signature by sending identity is included
  661. *
  662. * Version 1.x only supports sender-side replication. Version 2.x also
  663. * supports peer to peer and hub and spoke models. For that there is
  664. * a new field: a bloom filter that tracks recipients by ZeroTier address.
  665. *
  666. * Bits in the bloom filter are set by multiplying the address by the
  667. * indicated multiplier and then taking that modulo the number of bits
  668. * in the filter. Both the length of the filter and this multiplier are
  669. * variable and can be selected based on the sender's knowledge of
  670. * the total recipient set to minimize the chance of collision, as a
  671. * collision would result in a multicast not reaching one particular
  672. * recipient. The algorithm for selecting these is not defined by the
  673. * protocol.
  674. *
  675. * The ZeroTier address of the originating sender is also included
  676. * before the bloom filter if flag bit 0x08 is set.
  677. *
  678. * Version 2.x also supports an optional signature of the packet's
  679. * payload by the sending ZeroTier node. This can be used to validate
  680. * multicasts propagated cooperatively, since unlike sender side
  681. * replication the message MAC alone cannot be used for this. This
  682. * imposes a non-trivial CPU cost on the sender and so it's optional.
  683. * Note that the bloom filter itself is not included in the signature
  684. * because it can be changed in transit.
  685. *
  686. * OK is not sent.
  687. *
  688. * ERROR_MULTICAST_STFU is generated if a recipient no longer wishes to
  689. * receive these multicasts. It's essentially a source quench. Its
  690. * payload is:
  691. *
  692. * ERROR response payload:
  693. * <[8] 64-bit network ID>
  694. * <[6] multicast group MAC>
  695. * <[4] 32-bit multicast group ADI>
  696. */
  697. VERB_MULTICAST_FRAME = 0x0e,
  698. /**
  699. * Push of potential endpoints for direct communication:
  700. * <[2] 16-bit number of paths>
  701. * <[...] paths>
  702. *
  703. * Path record format:
  704. * <[1] 8-bit path flags>
  705. * <[2] length of extended path characteristics or 0 for none>
  706. * <[...] extended path characteristics>
  707. * <[1] address type>
  708. * <[1] address length in bytes>
  709. * <[...] address>
  710. *
  711. * Path record flags:
  712. * 0x01 - Forget this path if currently known (not implemented yet)
  713. *
  714. * The receiver may, upon receiving a push, attempt to establish a
  715. * direct link to one or more of the indicated addresses. It is the
  716. * responsibility of the sender to limit which peers it pushes direct
  717. * paths to to those with whom it has a trust relationship. The receiver
  718. * must obey any restrictions provided such as exclusivity or blacklists.
  719. * OK responses to this message are optional.
  720. *
  721. * Note that a direct path push does not imply that learned paths can't
  722. * be used unless they are blacklisted explicitly or unless flag 0x01
  723. * is set.
  724. *
  725. * OK and ERROR are not generated.
  726. */
  727. VERB_PUSH_DIRECT_PATHS = 0x10,
  728. /**
  729. * An acknowledgment of receipt of a series of recent packets from another
  730. * peer. This is used to calculate relative throughput values and to detect
  731. * packet loss. Only VERB_FRAME and VERB_EXT_FRAME packets are counted.
  732. *
  733. * ACK response format:
  734. * <[4] 32-bit number of bytes received since last ACK>
  735. *
  736. * Upon receipt of this packet, the local peer will verify that the correct
  737. * number of bytes were received by the remote peer. If these values do
  738. * not agree that could be an indicator of packet loss.
  739. *
  740. * Additionally, the local peer knows the interval of time that has
  741. * elapsed since the last received ACK. With this information it can compute
  742. * a rough estimate of the current throughput.
  743. *
  744. * This is sent at a maximum rate of once per every ZT_PATH_ACK_INTERVAL
  745. */
  746. VERB_ACK = 0x12,
  747. /**
  748. * A packet containing timing measurements useful for estimating path quality.
  749. * Composed of a list of <packet ID:internal sojourn time> pairs for an
  750. * arbitrary set of recent packets. This is used to sample for latency and
  751. * packet delay variance (PDV, "jitter").
  752. *
  753. * QoS record format:
  754. *
  755. * <[8] 64-bit packet ID of previously-received packet>
  756. * <[1] 8-bit packet sojourn time>
  757. * <...repeat until end of max 1400 byte packet...>
  758. *
  759. * The number of possible records per QoS packet is: (1400 * 8) / 72 = 155
  760. * This packet should be sent very rarely (every few seconds) as it can be
  761. * somewhat large if the connection is saturated. Future versions might use
  762. * a bloom table to probabilistically determine these values in a vastly
  763. * more space-efficient manner.
  764. *
  765. * Note: The 'internal packet sojourn time' is a slight misnomer as it is a
  766. * measure of the amount of time between when a packet was received and the
  767. * egress time of its tracking QoS packet.
  768. *
  769. * This is sent at a maximum rate of once per every ZT_PATH_QOS_INTERVAL
  770. */
  771. VERB_QOS_MEASUREMENT = 0x13,
  772. /**
  773. * A message with arbitrary user-definable content:
  774. * <[8] 64-bit arbitrary message type ID>
  775. * [<[...] message payload>]
  776. *
  777. * This can be used to send arbitrary messages over VL1. It generates no
  778. * OK or ERROR and has no special semantics outside of whatever the user
  779. * (via the ZeroTier core API) chooses to give it.
  780. *
  781. * Message type IDs less than or equal to 65535 are reserved for use by
  782. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  783. * implementations.
  784. */
  785. VERB_USER_MESSAGE = 0x14,
  786. /**
  787. * A trace for remote debugging or diagnostics:
  788. * <[...] null-terminated dictionary containing trace information>
  789. * [<[...] additional null-terminated dictionaries>]
  790. *
  791. * This message contains a remote trace event. Remote trace events can
  792. * be sent to observers configured at the network level for those that
  793. * pertain directly to activity on a network, or to global observers if
  794. * locally configured.
  795. */
  796. VERB_REMOTE_TRACE = 0x15,
  797. /**
  798. * A signed locator for this node:
  799. * <[8] 64-bit flags>
  800. * <[2] 16-bit length of locator>
  801. * <[...] serialized locator>
  802. *
  803. * This message is sent in response to OK(HELLO) and can be pushed
  804. * opportunitistically. Its payload is a signed Locator object that
  805. * attests to where and how this Node may be reached. A locator can
  806. * contain static IPs/ports or other ZeroTier nodes that can be used
  807. * to reach this one.
  808. *
  809. * These Locator objects can be stored e.g. by roots in LF to publish
  810. * node reachability. Since they're signed any node can verify that
  811. * the originating node approves of their content.
  812. */
  813. VERB_SET_LOCATOR = 0x16,
  814. /**
  815. * A list of peers this node will relay traffic to/from:
  816. * <[2] 16-bit number of peers>
  817. * <[16] 128-bit hash of node public key>
  818. * <[2] 16-bit latency to node or 0 if unspecified>
  819. * <[4] 32-bit max bandwidth in megabits or 0 if unspecified>
  820. * [<[...] additional hash,latency,bandwidth tuples>]
  821. *
  822. * This messages can be pushed to indicate that this peer is willing
  823. * to relay traffic to other peers. It contains a list of 128-bit
  824. * hashes (the first 128 bits of a SHA512) of identity public keys
  825. * of currently reachable and willing-to-relay-for nodes.
  826. *
  827. * This can be used to initiate mesh-like behavior in ZeroTier. The
  828. * peers for which this node is willing to relay are reported as
  829. * hashes of their identity public keys. This prevents this message
  830. * from revealing explicit information about linked peers. The
  831. * receiving peer can only "see" a will-relay entry if it knows the
  832. * identity of the peer it is trying to reach.
  833. */
  834. VERB_WILL_RELAY = 0x17,
  835. /**
  836. * A push of one or more ephemeral key pairs:
  837. * <[1] 8-bit length of random padding>
  838. * <[...] random padding>
  839. * <[1] 8-bit number of keys in message>
  840. * [... begin keys ...]
  841. * <[1] 8-bit key type>
  842. * <[...] public key (length determined by type)>
  843. * [<[...] additional keys ...>]
  844. * [... end keys ...]
  845. *
  846. * This verb is used to push ephemeral keys. A node replies to each
  847. * ephemeral key push with an OK message containing its own current
  848. * ephemeral keys that it wants to use for p2p communication.
  849. *
  850. * These are ephemeral public keys. Currently keys of type C25519
  851. * and P-384 are supported and both will be pushed.
  852. *
  853. * If more than one key is pushed, key agreement is performed using
  854. * all keys for which both peers pushed the same key type. The raw
  855. * results of these keys are then hashed together in order of key
  856. * type ID with SHA384 to yield a session key. If the desired session
  857. * key is shorter than 384 bits the first N bits are used.
  858. *
  859. * The random padding component can be used to ranomize the length
  860. * of these packets so adversaries can't easily selectively block
  861. * ephemeral key exchange by exploiting a fixed packet length.
  862. *
  863. * OK response payload:
  864. * <[...] responder's keys, same format as verb payload>
  865. */
  866. VERB_EPHEMERAL_KEY = 0x18
  867. };
  868. /**
  869. * Error codes for VERB_ERROR
  870. */
  871. enum ErrorCode
  872. {
  873. /* No error, not actually used in transit */
  874. ERROR_NONE = 0x00,
  875. /* Invalid request */
  876. ERROR_INVALID_REQUEST = 0x01,
  877. /* Bad/unsupported protocol version */
  878. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  879. /* Unknown object queried */
  880. ERROR_OBJ_NOT_FOUND = 0x03,
  881. /* HELLO pushed an identity whose address is already claimed */
  882. ERROR_IDENTITY_COLLISION = 0x04,
  883. /* Verb or use case not supported/enabled by this node */
  884. ERROR_UNSUPPORTED_OPERATION = 0x05,
  885. /* Network membership certificate update needed */
  886. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  887. /* Tried to join network, but you're not a member */
  888. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  889. /* Multicasts to this group are not wanted */
  890. ERROR_MULTICAST_STFU = 0x08,
  891. /* Cannot deliver a forwarded ZeroTier packet (e.g. hops exceeded, no routes) */
  892. /* Payload: <packet ID>, <destination>, <... additional packet ID / destinations> */
  893. ERROR_CANNOT_DELIVER = 0x09
  894. };
  895. template<unsigned int C2>
  896. ZT_ALWAYS_INLINE Packet(const Buffer<C2> &b) :
  897. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  898. {
  899. }
  900. ZT_ALWAYS_INLINE Packet(const void *data,unsigned int len) :
  901. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  902. {
  903. }
  904. /**
  905. * Construct a new empty packet with a unique random packet ID
  906. *
  907. * Flags and hops will be zero. Other fields and data region are undefined.
  908. * Use the header access methods (setDestination() and friends) to fill out
  909. * the header. Payload should be appended; initial size is header size.
  910. */
  911. ZT_ALWAYS_INLINE Packet() :
  912. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  913. {
  914. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  915. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  916. }
  917. /**
  918. * Make a copy of a packet with a new initialization vector and destination address
  919. *
  920. * This can be used to take one draft prototype packet and quickly make copies to
  921. * encrypt for different destinations.
  922. *
  923. * @param prototype Prototype packet
  924. * @param dest Destination ZeroTier address for new packet
  925. */
  926. ZT_ALWAYS_INLINE Packet(const Packet &prototype,const Address &dest) :
  927. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  928. {
  929. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  930. setDestination(dest);
  931. }
  932. /**
  933. * Construct a new empty packet with a unique random packet ID
  934. *
  935. * @param dest Destination ZT address
  936. * @param source Source ZT address
  937. * @param v Verb
  938. */
  939. ZT_ALWAYS_INLINE Packet(const Address &dest,const Address &source,const Verb v) :
  940. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  941. {
  942. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  943. setDestination(dest);
  944. setSource(source);
  945. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  946. setVerb(v);
  947. }
  948. /**
  949. * Reset this packet structure for reuse in place
  950. *
  951. * @param dest Destination ZT address
  952. * @param source Source ZT address
  953. * @param v Verb
  954. */
  955. ZT_ALWAYS_INLINE void reset(const Address &dest,const Address &source,const Verb v)
  956. {
  957. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  958. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  959. setDestination(dest);
  960. setSource(source);
  961. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  962. setVerb(v);
  963. }
  964. /**
  965. * Generate a new IV / packet ID in place
  966. *
  967. * This can be used to re-use a packet buffer multiple times to send
  968. * technically different but otherwise identical copies of the same
  969. * packet.
  970. */
  971. ZT_ALWAYS_INLINE void newInitializationVector() { setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId()); }
  972. /**
  973. * Set this packet's destination
  974. *
  975. * @param dest ZeroTier address of destination
  976. */
  977. ZT_ALWAYS_INLINE void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  978. /**
  979. * Set this packet's source
  980. *
  981. * @param source ZeroTier address of source
  982. */
  983. ZT_ALWAYS_INLINE void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  984. /**
  985. * Get this packet's destination
  986. *
  987. * @return Destination ZT address
  988. */
  989. ZT_ALWAYS_INLINE Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  990. /**
  991. * Get this packet's source
  992. *
  993. * @return Source ZT address
  994. */
  995. ZT_ALWAYS_INLINE Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  996. /**
  997. * @return True if packet is of valid length
  998. */
  999. ZT_ALWAYS_INLINE bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  1000. /**
  1001. * @return True if packet is fragmented (expect fragments)
  1002. */
  1003. ZT_ALWAYS_INLINE bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  1004. /**
  1005. * Set this packet's fragmented flag
  1006. *
  1007. * @param f Fragmented flag value
  1008. */
  1009. ZT_ALWAYS_INLINE void setFragmented(bool f)
  1010. {
  1011. if (f)
  1012. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  1013. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  1014. }
  1015. /**
  1016. * @return True if compressed (result only valid if unencrypted)
  1017. */
  1018. ZT_ALWAYS_INLINE bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  1019. /**
  1020. * @return ZeroTier forwarding hops (0 to 7)
  1021. */
  1022. ZT_ALWAYS_INLINE unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  1023. /**
  1024. * Increment this packet's hop count
  1025. */
  1026. ZT_ALWAYS_INLINE unsigned char incrementHops()
  1027. {
  1028. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1029. const unsigned char h = (b + 1) & 0x07;
  1030. b = (b & 0xf8) | h;
  1031. return (unsigned int)h;
  1032. }
  1033. /**
  1034. * @return Cipher suite selector: 0 - 7 (see #defines)
  1035. */
  1036. ZT_ALWAYS_INLINE unsigned int cipher() const
  1037. {
  1038. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  1039. }
  1040. /**
  1041. * Set this packet's cipher suite
  1042. */
  1043. ZT_ALWAYS_INLINE void setCipher(unsigned int c)
  1044. {
  1045. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1046. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  1047. }
  1048. /**
  1049. * Get the trusted path ID for this packet (only meaningful if cipher is trusted path)
  1050. *
  1051. * @return Trusted path ID (from MAC field)
  1052. */
  1053. ZT_ALWAYS_INLINE uint64_t trustedPathId() const { return at<uint64_t>(ZT_PACKET_IDX_MAC); }
  1054. /**
  1055. * Set this packet's trusted path ID and set the cipher spec to trusted path
  1056. *
  1057. * @param tpid Trusted path ID
  1058. */
  1059. ZT_ALWAYS_INLINE void setTrusted(const uint64_t tpid)
  1060. {
  1061. setCipher(ZT_PROTO_CIPHER_SUITE__NONE);
  1062. setAt(ZT_PACKET_IDX_MAC,tpid);
  1063. }
  1064. /**
  1065. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  1066. *
  1067. * Note that the least significant 3 bits of this ID will change when armor()
  1068. * is called to armor the packet for transport. This is because armor() will
  1069. * mask the last 3 bits against the send counter for QoS monitoring use prior
  1070. * to actually using the IV to encrypt and MAC the packet. Be aware of this
  1071. * when grabbing the packetId of a new packet prior to armor/send.
  1072. *
  1073. * @return Packet ID
  1074. */
  1075. ZT_ALWAYS_INLINE uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  1076. /**
  1077. * Set packet verb
  1078. *
  1079. * This also has the side-effect of clearing any verb flags, such as
  1080. * compressed, and so must only be done during packet composition.
  1081. *
  1082. * @param v New packet verb
  1083. */
  1084. ZT_ALWAYS_INLINE void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  1085. /**
  1086. * @return Packet verb (not including flag bits)
  1087. */
  1088. ZT_ALWAYS_INLINE Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  1089. /**
  1090. * @return Length of packet payload
  1091. */
  1092. ZT_ALWAYS_INLINE unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1093. /**
  1094. * @return Raw packet payload
  1095. */
  1096. ZT_ALWAYS_INLINE const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1097. /**
  1098. * Armor packet for transport
  1099. *
  1100. * @param key 32-byte key
  1101. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1102. */
  1103. void armor(const void *key,bool encryptPayload);
  1104. /**
  1105. * Verify and (if encrypted) decrypt packet
  1106. *
  1107. * This does not handle trusted path mode packets and will return false
  1108. * for these. These are handled in IncomingPacket if the sending physical
  1109. * address and MAC field match a trusted path.
  1110. *
  1111. * @param key 32-byte key
  1112. * @return False if packet is invalid or failed MAC authenticity check
  1113. */
  1114. bool dearmor(const void *key);
  1115. /**
  1116. * Attempt to compress payload if not already (must be unencrypted)
  1117. *
  1118. * This requires that the payload at least contain the verb byte already
  1119. * set. The compressed flag in the verb is set if compression successfully
  1120. * results in a size reduction. If no size reduction occurs, compression
  1121. * is not done and the flag is left cleared.
  1122. *
  1123. * @return True if compression occurred
  1124. */
  1125. bool compress();
  1126. /**
  1127. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1128. *
  1129. * If payload is compressed, it is decompressed and the compressed verb
  1130. * flag is cleared. Otherwise nothing is done and true is returned.
  1131. *
  1132. * @return True if data is now decompressed and valid, false on error
  1133. */
  1134. bool uncompress();
  1135. private:
  1136. static const unsigned char ZERO_KEY[32];
  1137. static uint64_t nextPacketId();
  1138. /**
  1139. * Deterministically mangle a 256-bit crypto key based on packet
  1140. *
  1141. * This uses extra data from the packet to mangle the secret, giving us an
  1142. * effective IV that is somewhat more than 64 bits. This is "free" for
  1143. * Salsa20 since it has negligible key setup time so using a different
  1144. * key each time is fine.
  1145. *
  1146. * @param in Input key (32 bytes)
  1147. * @param out Output buffer (32 bytes)
  1148. */
  1149. ZT_ALWAYS_INLINE void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1150. {
  1151. const unsigned char *d = (const unsigned char *)data();
  1152. // IV and source/destination addresses. Using the addresses divides the
  1153. // key space into two halves-- A->B and B->A (since order will change).
  1154. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1155. out[i] = in[i] ^ d[i];
  1156. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1157. // nodes. It's one of the only parts of a packet modifiable by people
  1158. // without the key.
  1159. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1160. // Raw packet size in bytes -- thus each packet size defines a new
  1161. // key space.
  1162. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1163. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1164. // Rest of raw key is used unchanged
  1165. for(unsigned int i=21;i<32;++i)
  1166. out[i] = in[i];
  1167. }
  1168. };
  1169. } // namespace ZeroTier
  1170. #endif