Packet.hpp 51 KB

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