Packet.hpp 51 KB

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