Packet.hpp 49 KB

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