Packet.hpp 55 KB

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