Packet.hpp 46 KB

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