Packet.hpp 53 KB

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