Packet.hpp 50 KB

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