Packet.hpp 46 KB

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