Protocol.hpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_PROTOCOL_HPP
  14. #define ZT_PROTOCOL_HPP
  15. #include "Constants.hpp"
  16. #include "AES.hpp"
  17. #include "Salsa20.hpp"
  18. #include "Poly1305.hpp"
  19. #include "LZ4.hpp"
  20. #include "Buf.hpp"
  21. #include "Address.hpp"
  22. #include "Identity.hpp"
  23. // TODO: mlock
  24. /*
  25. * Core ZeroTier protocol packet formats ------------------------------------------------------------------------------
  26. *
  27. * Packet format:
  28. * <[8] 64-bit packet ID / crypto IV>
  29. * <[5] destination ZT address>
  30. * <[5] source ZT address>
  31. * <[1] outer visible flags, cipher, and hop count (bits: FFCCHHH)>
  32. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  33. * [... -- begin encryption envelope -- ...]
  34. * <[1] inner envelope flags (MS 3 bits) and verb (LS 5 bits)>
  35. * [... verb-specific payload ...]
  36. *
  37. * Packets smaller than 28 bytes are invalid and silently discarded.
  38. *
  39. * The hop count field is masked during message authentication computation
  40. * and is thus the only field that is mutable in transit. It's incremented
  41. * when roots or other nodes forward packets and exists to prevent infinite
  42. * forwarding loops and to detect direct paths.
  43. *
  44. * HELLO is normally sent in the clear with the POLY1305_NONE cipher suite
  45. * and with Poly1305 computed on plain text (Salsa20/12 is still used to
  46. * generate a one time use Poly1305 key). As of protocol version 11 HELLO
  47. * also includes a terminating HMAC (last 48 bytes) that significantly
  48. * hardens HELLO authentication beyond what a 64-bit MAC can guarantee.
  49. *
  50. * Fragmented packets begin with a packet header whose fragment bit (bit
  51. * 0x40 in the flags field) is set. This constitutes fragment zero. The
  52. * total number of expected fragments is contained in each subsequent
  53. * fragment packet. Unfragmented packets must not have the fragment bit
  54. * set or the receiver will expect at least one additional fragment.
  55. *
  56. * --
  57. *
  58. * Packet fragment format (fragments beyond 0):
  59. * <[8] packet ID of packet to which this fragment belongs>
  60. * <[5] destination ZT address>
  61. * <[1] 0xff here signals that this is a fragment>
  62. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  63. * <[1] ZT hop count (least significant 3 bits; others are reserved)>
  64. * <[...] fragment data>
  65. *
  66. * The protocol supports a maximum of 16 fragments including fragment 0
  67. * which contains the full packet header (with fragment bit set). Fragments
  68. * thus always carry fragment numbers between 1 and 15. All fragments
  69. * belonging to the same packet must carry the same total fragment count in
  70. * the most significant 4 bits of the fragment numbering field.
  71. *
  72. * All fragments have the same packet ID and destination. The packet ID
  73. * doubles as the grouping identifier for fragment reassembly.
  74. *
  75. * Fragments do not carry their own packet MAC. The entire packet is
  76. * authenticated once it is assembled by the receiver. Incomplete packets
  77. * are discarded after a receiver configured period of time.
  78. *
  79. * --------------------------------------------------------------------------------------------------------------------
  80. */
  81. /*
  82. * Protocol versions
  83. *
  84. * 1 - 0.2.0 ... 0.2.5
  85. * 2 - 0.3.0 ... 0.4.5
  86. * + Added signature and originating peer to multicast frame
  87. * + Double size of multicast frame bloom filter
  88. * 3 - 0.5.0 ... 0.6.0
  89. * + Yet another multicast redesign
  90. * + New crypto completely changes key agreement cipher
  91. * 4 - 0.6.0 ... 1.0.6
  92. * + BREAKING CHANGE: New identity format based on hashcash design
  93. * 5 - 1.1.0 ... 1.1.5
  94. * + Supports echo
  95. * + Supports in-band world (root server definition) updates
  96. * + Clustering! (Though this will work with protocol v4 clients.)
  97. * + Otherwise backward compatible with protocol v4
  98. * 6 - 1.1.5 ... 1.1.10
  99. * + Network configuration format revisions including binary values
  100. * 7 - 1.1.10 ... 1.1.17
  101. * + Introduce trusted paths for local SDN use
  102. * 8 - 1.1.17 ... 1.2.0
  103. * + Multipart network configurations for large network configs
  104. * + Tags and Capabilities
  105. * + inline push of CertificateOfMembership deprecated
  106. * 9 - 1.2.0 ... 1.2.14
  107. * 10 - 1.4.0 ... 1.4.6
  108. * + Contained early pre-alpha versions of multipath, which are deprecated
  109. * 11 - 2.0.0 ... CURRENT
  110. * + New more WAN-efficient P2P-assisted multicast algorithm
  111. * + HELLO and OK(HELLO) include an extra HMAC to harden authentication
  112. * + HELLO and OK(HELLO) can carry structured meta-data
  113. * + Ephemeral keys for forward secrecy and limited key lifetime
  114. * + Old planet/moon stuff is DEAD! Independent roots are easier.
  115. * + AES encryption is now the default
  116. * + New combined Curve25519/NIST P-384 identity type (type 1)
  117. * + Short probe packets to reduce probe bandwidth
  118. * + Aggressive NAT traversal techniques for IPv4 symmetric NATs
  119. * + Remote diagnostics including rewrite of remote tracing
  120. */
  121. #define ZT_PROTO_VERSION 11
  122. /**
  123. * Minimum supported protocol version
  124. */
  125. #define ZT_PROTO_VERSION_MIN 8
  126. /**
  127. * Maximum allowed packet size (can technically be increased up to 16384)
  128. */
  129. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_MIN_UDP_MTU)
  130. /**
  131. * Minimum viable packet length (outer header + verb)
  132. */
  133. #define ZT_PROTO_MIN_PACKET_LENGTH 28
  134. /**
  135. * Index at which the encrypted section of a packet begins
  136. */
  137. #define ZT_PROTO_PACKET_ENCRYPTED_SECTION_START 27
  138. /**
  139. * Index at which packet payload begins (after verb)
  140. */
  141. #define ZT_PROTO_PACKET_PAYLOAD_START 28
  142. /**
  143. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  144. *
  145. * This is a protocol constant. It's the maximum allowed by the length
  146. * of the hop counter -- three bits. A lower limit is specified as
  147. * the actual maximum hop count.
  148. */
  149. #define ZT_PROTO_MAX_HOPS 7
  150. /**
  151. * NONE/Poly1305 (using Salsa20/12 to generate poly1305 key)
  152. */
  153. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  154. /**
  155. * Salsa2012/Poly1305
  156. */
  157. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  158. /**
  159. * No encryption or authentication at all
  160. *
  161. * For trusted paths the MAC field is the trusted path ID.
  162. */
  163. #define ZT_PROTO_CIPHER_SUITE__NONE 2
  164. /**
  165. * AES-GCM-NRH (AES-GCM with nonce reuse hardening) w/AES-256
  166. */
  167. #define ZT_PROTO_CIPHER_SUITE__AES_GCM_NRH 3
  168. /**
  169. * Minimum viable length for a fragment
  170. */
  171. #define ZT_PROTO_MIN_FRAGMENT_LENGTH 16
  172. /**
  173. * Magic number indicating a fragment if present at index 13
  174. */
  175. #define ZT_PROTO_PACKET_FRAGMENT_INDICATOR 0xff
  176. /**
  177. * Index at which fragment indicator is found in fragments
  178. */
  179. #define ZT_PROTO_PACKET_FRAGMENT_INDICATOR_INDEX 13
  180. /**
  181. * Index of flags field in regular packet headers
  182. */
  183. #define ZT_PROTO_PACKET_FLAGS_INDEX 18
  184. /**
  185. * Length of a probe packet
  186. */
  187. #define ZT_PROTO_PROBE_LENGTH 8
  188. /**
  189. * Index at which packet fragment payload starts
  190. */
  191. #define ZT_PROTO_PACKET_FRAGMENT_PAYLOAD_START_AT ZT_PROTO_MIN_FRAGMENT_LENGTH
  192. /**
  193. * Header flag indicating that a packet is fragmented and more fragments should be expected
  194. */
  195. #define ZT_PROTO_FLAG_FRAGMENTED 0x40U
  196. /**
  197. * Mask for obtaining hops from the combined flags, cipher, and hops field
  198. */
  199. #define ZT_PROTO_FLAG_FIELD_HOPS_MASK 0x07U
  200. /**
  201. * Verb flag indicating payload is compressed with LZ4
  202. */
  203. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80U
  204. /**
  205. * Mask to extract just the verb from the verb field, which also includes flags
  206. */
  207. #define ZT_PROTO_VERB_MASK 0x1fU
  208. /**
  209. * Key derivation function label for the keys used with HMAC-384 in HELLO
  210. *
  211. * With the KDF the 'iter' parameter is 0 for the key used for
  212. * HMAC in HELLO and 1 for the one used in OK(HELLO).
  213. */
  214. #define ZT_PROTO_KDF_KEY_LABEL_HELLO_HMAC 'H'
  215. /**
  216. * HELLO exchange meta-data: random 128-bit identifier for each running instance
  217. */
  218. #define ZT_PROTO_HELLO_NODE_META_INSTANCE_ID "i"
  219. /**
  220. * HELLO exchange meta-data: signed locator for this node
  221. */
  222. #define ZT_PROTO_HELLO_NODE_META_LOCATOR "l"
  223. /**
  224. * HELLO exchange meta-data: ephemeral C25519 public key
  225. */
  226. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_C25519 "e0"
  227. /**
  228. * HELLO exchange meta-data: ephemeral NIST P-384 public key
  229. */
  230. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_P384 "e1"
  231. /**
  232. * HELLO exchange meta-data: address(es) of nodes to whom this node will relay
  233. */
  234. #define ZT_PROTO_HELLO_NODE_META_NEIGHBORS "wr"
  235. /**
  236. * HELLO exchange meta-data: X coordinate of your node (sent in OK(HELLO))
  237. */
  238. #define ZT_PROTO_HELLO_NODE_META_LOCATION_X "gX"
  239. /**
  240. * HELLO exchange meta-data: Y coordinate of your node (sent in OK(HELLO))
  241. */
  242. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Y "gY"
  243. /**
  244. * HELLO exchange meta-data: Z coordinate of your node (sent in OK(HELLO))
  245. */
  246. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Z "gZ"
  247. /**
  248. * HELLO exchange meta-data: preferred cipher suite (may be ignored)
  249. */
  250. #define ZT_PROTO_HELLO_NODE_META_PREFERRED_CIPHER_SUITE "c"
  251. namespace ZeroTier {
  252. namespace Protocol {
  253. /**
  254. * Packet verb (message type)
  255. */
  256. enum Verb
  257. {
  258. /**
  259. * No operation
  260. *
  261. * This packet does nothing, but it is sometimes sent as a probe to
  262. * trigger a HELLO exchange as the code will attempt HELLO when it
  263. * receives a packet from an unidentified source.
  264. */
  265. VERB_NOP = 0x00,
  266. /**
  267. * Announcement of a node's existence and vitals:
  268. * <[1] protocol version>
  269. * <[1] software major version (LEGACY)>
  270. * <[1] software minor version (LEGACY)>
  271. * <[2] software revision (LEGACY)>
  272. * <[8] timestamp for determining latency (LEGACY)>
  273. * <[...] binary serialized identity>
  274. * <[...] physical destination address of packet (LEGACY)>
  275. * <[2] 16-bit reserved "encrypted zero" field (LEGACY)>
  276. * <[...] encrypted dictionary>
  277. * <[2] 16-bit length of preceding encrypted dictionary>
  278. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  279. *
  280. * HELLO is sent to initiate a new pairing between two nodes.
  281. *
  282. * HELLO is the only packet ever sent without normal payload encryption,
  283. * though an inner encrypted envelope exists to obscure all fields that
  284. * do not need to be sent in the clear. HELLO's MAC field contains a
  285. * Poly1305 MAC for backward compatibility, and v2.x adds an additional
  286. * HMAC-SHA384 at the end for stronger authentication of sessions. HELLO
  287. * authentication is performed using the long-lived identity key only,
  288. * and the encryption of the inner dictionary field is done using a key
  289. * derived from this identity key explicitly for this purpose.
  290. *
  291. * The main payload of HELLO is the protocol version and the full identity
  292. * of the sender, which includes the sender's public key(s). An encrypted
  293. * dictionary (key/value store) is also included for additional information.
  294. * This is encrypted using AES-CTR with a derived key and using the final
  295. * 96 bits of the packet's HMAC-SHA384 as the CTR IV. (The HMAC authenticates
  296. * the packet prior to this field being encrypted, making this a SIV
  297. * construction much like AES-GMAC-SIV.)
  298. *
  299. * The length of the dictionary field is included immediately after it so
  300. * that it can be decrypted and the HMAC validated without performing any
  301. * parsing of anything else, since it's a good idea to authenticate any
  302. * message as early as possible in any secure protocol.
  303. *
  304. * V1.x will ignore the HMAC and dictionary fields as it doesn't understand
  305. * them, but the packet is constructed so that 1.x nodes will parse what
  306. * they need to communicate with 2.x nodes (without forward secrecy) as long
  307. * as we wish to support this.
  308. *
  309. * Several legacy fields are present as well for the benefit of 1.x nodes.
  310. * These will go away and become simple reserved space once 1.x is no longer
  311. * supported. Some are self-explanatory. The "encrypted zero" is rather
  312. * strange. It's a 16-bit zero value encrypted using Salsa20/12 and the
  313. * long-lived identity key shared by the two peers. It tells 1.x that an
  314. * old encrypted field is no longer there and that it should stop parsing
  315. * the packet at that point.
  316. *
  317. * The following fields are nearly always present and must exist to support
  318. * forward secrecy (in the case of the instance ID, keys, and key revision)
  319. * or federated root membership (in the case of the locator).
  320. *
  321. * TIMESTAMP - node's timestamp in milliseconds (supersedes legacy field)
  322. * INSTANCE_ID - a 64-bit unique value generated on each node start
  323. * EPHEMERAL_C25519 - an ephemeral Curve25519 public key
  324. * EPHEMERAL_P384 - an ephemeral NIST P-384 public key
  325. * EPHEMERAL_REVISION - 64-bit monotonically increasing per-instance counter
  326. * LOCATOR - signed record enumerating this node's trusted contact points
  327. *
  328. * The following optional fields may also be present:
  329. *
  330. * NAME - abitrary short user-defined name for this node
  331. * CONTACT - arbitrary short contact information string for this node
  332. * NEIGHBORS - addresses of node(s) to whom we'll relay (mesh-like routing)
  333. * LOC_X, LOC_Y, LOC_Z - location relative to the nearest large center of mass
  334. * PEER_LOC_X, PEER_LOC_Y, PEER_LOC_Z - where sender thinks peer is located
  335. * SOFTWARE_VENDOR - short name or description of vendor, such as a URL
  336. * SOFTWARE_VERSION - major, minor, revision, and build, and 16-bit integers
  337. * PHYSICAL_DEST - serialized Endpoint to which this message was sent
  338. * VIRTUAL_DEST - ZeroTier address of first hop (if first hop wasn't destination)
  339. * COMPLIANCE - bit mask containing bits for e.g. a FIPS-compliant node
  340. *
  341. * A valid and successfully authenticated HELLO will generate the following
  342. * OK response. It contains an echo of the timestamp supplied by the
  343. * initiating peer, the protocol version, and a dictionary containing
  344. * the same information about the responding peer as the originating peer
  345. * sent.
  346. *
  347. * OK payload:
  348. * <[8] timestamp echoed from original HELLO>
  349. * <[1] protocol version>
  350. * <[1] software major version (LEGACY)>
  351. * <[1] software minor version (LEGACY)>
  352. * <[2] software revision (LEGACY)>
  353. * <[...] physical destination address of packet (LEGACY)>
  354. * <[2] 16-bit reserved zero field (LEGACY)>
  355. * <[...] dictionary>
  356. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  357. */
  358. VERB_HELLO = 0x01,
  359. /**
  360. * Error response:
  361. * <[1] in-re verb>
  362. * <[8] in-re packet ID>
  363. * <[1] error code>
  364. * <[...] error-dependent payload, may be empty>
  365. *
  366. * An ERROR that does not pertain to a specific packet will have its verb
  367. * set to VERB_NOP and its packet ID set to zero.
  368. */
  369. VERB_ERROR = 0x02,
  370. /**
  371. * Success response:
  372. * <[1] in-re verb>
  373. * <[8] in-re packet ID>
  374. * <[...] request-specific payload>
  375. */
  376. VERB_OK = 0x03,
  377. /**
  378. * Query an identity by address:
  379. * <[5] address to look up>
  380. * [<[...] additional addresses to look up>
  381. *
  382. * OK response payload:
  383. * <[...] identity>
  384. * <[...] locator>
  385. * [... additional identity/locator pairs]
  386. *
  387. * If the address is not found, no response is generated. The semantics
  388. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  389. * be performed.
  390. *
  391. * It is possible for an identity but a null/empty locator to be returned
  392. * if no locator is known for a node. Older versions may omit the locator.
  393. */
  394. VERB_WHOIS = 0x04,
  395. /**
  396. * Relay-mediated NAT traversal or firewall punching initiation:
  397. * <[1] flags (unused, currently 0)>
  398. * <[5] ZeroTier address of peer that might be found at this address>
  399. * <[2] 16-bit protocol address port>
  400. * <[1] protocol address length / type>
  401. * <[...] protocol address (network byte order)>
  402. *
  403. * This is sent by a third party node to inform a node of where another
  404. * may be located. These are currently only allowed from roots.
  405. *
  406. * The protocol address format differs from the standard InetAddress
  407. * encoding for legacy reasons, but it's not hard to decode. The following
  408. * values are valid for the protocol address length (type) field:
  409. *
  410. * 4 - IPv4 IP address
  411. * 16 - IPv6 IP address
  412. * 255 - Endpoint object, unmarshaled in place (port ignored)
  413. *
  414. * No OK or ERROR is generated.
  415. */
  416. VERB_RENDEZVOUS = 0x05,
  417. /**
  418. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  419. * <[8] 64-bit network ID>
  420. * <[2] 16-bit ethertype>
  421. * <[...] ethernet payload>
  422. *
  423. * MAC addresses are derived from the packet's source and destination
  424. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  425. * Ethernet framing and other optional flags and features when they
  426. * are not necessary.
  427. *
  428. * ERROR may be generated if a membership certificate is needed for a
  429. * closed network. Payload will be network ID.
  430. */
  431. VERB_FRAME = 0x06,
  432. /**
  433. * Full Ethernet frame with MAC addressing and optional fields:
  434. * <[8] 64-bit network ID>
  435. * <[1] flags>
  436. * <[6] destination MAC or all zero for destination node>
  437. * <[6] source MAC or all zero for node of origin>
  438. * <[2] 16-bit ethertype>
  439. * <[...] ethernet payload>
  440. *
  441. * Flags:
  442. * 0x01 - Certificate of network membership attached (DEPRECATED)
  443. * 0x02 - Most significant bit of subtype (see below)
  444. * 0x04 - Middle bit of subtype (see below)
  445. * 0x08 - Least significant bit of subtype (see below)
  446. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  447. *
  448. * Subtypes (0..7):
  449. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  450. * 0x1 - TEEd outbound frame
  451. * 0x2 - REDIRECTed outbound frame
  452. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  453. * 0x4 - TEEd inbound frame
  454. * 0x5 - REDIRECTed inbound frame
  455. * 0x6 - WATCHed inbound frame
  456. * 0x7 - (reserved for future use)
  457. *
  458. * An extended frame carries full MAC addressing, making it a
  459. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  460. * spoke multicast propagation is requested.
  461. *
  462. * OK payload (if ACK flag is set):
  463. * <[8] 64-bit network ID>
  464. * <[1] flags>
  465. * <[6] destination MAC or all zero for destination node>
  466. * <[6] source MAC or all zero for node of origin>
  467. * <[2] 16-bit ethertype>
  468. */
  469. VERB_EXT_FRAME = 0x07,
  470. /**
  471. * ECHO request (a.k.a. ping):
  472. * <[...] arbitrary payload>
  473. *
  474. * This generates OK with a copy of the transmitted payload. No ERROR
  475. * is generated. Response to ECHO requests is optional and ECHO may be
  476. * ignored if a node detects a possible flood.
  477. */
  478. VERB_ECHO = 0x08,
  479. /**
  480. * Announce interest in multicast group(s):
  481. * <[8] 64-bit network ID>
  482. * <[6] multicast Ethernet address>
  483. * <[4] multicast additional distinguishing information (ADI)>
  484. * [... additional tuples of network/address/adi ...]
  485. *
  486. * LIKEs may be sent to any peer, though a good implementation should
  487. * restrict them to peers on the same network they're for and to network
  488. * controllers and root servers. In the current network, root servers
  489. * will provide the service of final multicast cache.
  490. */
  491. VERB_MULTICAST_LIKE = 0x09,
  492. /**
  493. * Network credentials push:
  494. * [<[...] one or more certificates of membership>]
  495. * <[1] 0x00, null byte marking end of COM array>
  496. * <[2] 16-bit number of capabilities>
  497. * <[...] one or more serialized Capability>
  498. * <[2] 16-bit number of tags>
  499. * <[...] one or more serialized Tags>
  500. * <[2] 16-bit number of revocations>
  501. * <[...] one or more serialized Revocations>
  502. * <[2] 16-bit number of certificates of ownership>
  503. * <[...] one or more serialized CertificateOfOwnership>
  504. *
  505. * This can be sent by anyone at any time to push network credentials.
  506. * These will of course only be accepted if they are properly signed.
  507. * Credentials can be for any number of networks.
  508. *
  509. * The use of a zero byte to terminate the COM section is for legacy
  510. * backward compatibility. Newer fields are prefixed with a length.
  511. *
  512. * OK/ERROR are not generated.
  513. */
  514. VERB_NETWORK_CREDENTIALS = 0x0a,
  515. /**
  516. * Network configuration request:
  517. * <[8] 64-bit network ID>
  518. * <[2] 16-bit length of request meta-data dictionary>
  519. * <[...] string-serialized request meta-data>
  520. * <[8] 64-bit revision of netconf we currently have>
  521. * <[8] 64-bit timestamp of netconf we currently have>
  522. *
  523. * This message requests network configuration from a node capable of
  524. * providing it. Responses can be sent as OK(NETWORK_CONFIG_REQUEST)
  525. * or NETWORK_CONFIG messages. NETWORK_CONFIG can also be sent by
  526. * network controllers or other nodes unsolicited.
  527. *
  528. * OK response payload:
  529. * (same as VERB_NETWORK_CONFIG payload)
  530. *
  531. * ERROR response payload:
  532. * <[8] 64-bit network ID>
  533. */
  534. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  535. /**
  536. * Network configuration data push:
  537. * <[8] 64-bit network ID>
  538. * <[2] 16-bit length of network configuration dictionary chunk>
  539. * <[...] network configuration dictionary (may be incomplete)>
  540. * <[1] 8-bit flags>
  541. * <[8] 64-bit config update ID (should never be 0)>
  542. * <[4] 32-bit total length of assembled dictionary>
  543. * <[4] 32-bit index of chunk>
  544. * [ ... end signed portion ... ]
  545. * <[1] 8-bit reserved field (legacy)>
  546. * <[2] 16-bit length of chunk signature>
  547. * <[...] chunk signature>
  548. *
  549. * Network configurations can come from network controllers or theoretically
  550. * any other node, but each chunk must be signed by the network controller
  551. * that generated it originally. The config update ID is arbitrary and is merely
  552. * used by the receiver to group chunks. Chunk indexes must be sequential and
  553. * the total delivered chunks must yield a total network config equal to the
  554. * specified total length.
  555. *
  556. * Flags:
  557. * 0x01 - Use fast propagation -- rumor mill flood this chunk to other members
  558. *
  559. * An OK should be sent if the config is successfully received and
  560. * accepted.
  561. *
  562. * OK payload:
  563. * <[8] 64-bit network ID>
  564. * <[8] 64-bit config update ID>
  565. */
  566. VERB_NETWORK_CONFIG = 0x0c,
  567. /**
  568. * Request endpoints for multicast distribution:
  569. * <[8] 64-bit network ID>
  570. * <[1] flags>
  571. * <[6] MAC address of multicast group being queried>
  572. * <[4] 32-bit ADI for multicast group being queried>
  573. * <[4] 32-bit requested max number of multicast peers>
  574. *
  575. * This message asks a peer for additional known endpoints that have
  576. * LIKEd a given multicast group. It's sent when the sender wishes
  577. * to send multicast but does not have the desired number of recipient
  578. * peers.
  579. *
  580. * OK response payload: (multiple OKs can be generated)
  581. * <[8] 64-bit network ID>
  582. * <[6] MAC address of multicast group being queried>
  583. * <[4] 32-bit ADI for multicast group being queried>
  584. * <[4] 32-bit total number of known members in this multicast group>
  585. * <[2] 16-bit number of members enumerated in this packet>
  586. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  587. *
  588. * ERROR is not generated; queries that return no response are dropped.
  589. */
  590. VERB_MULTICAST_GATHER = 0x0d,
  591. /** *** DEPRECATED ***
  592. * Multicast frame:
  593. * <[8] 64-bit network ID>
  594. * <[1] flags>
  595. * [<[4] 32-bit implicit gather limit>]
  596. * [<[6] source MAC>]
  597. * <[6] destination MAC (multicast address)>
  598. * <[4] 32-bit multicast ADI (multicast address extension)>
  599. * <[2] 16-bit ethertype>
  600. * <[...] ethernet payload>
  601. *
  602. * Flags:
  603. * 0x01 - Network certificate of membership attached (DEPRECATED)
  604. * 0x02 - Implicit gather limit field is present
  605. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  606. * 0x08 - Please replicate (sent to multicast replicators)
  607. *
  608. * OK and ERROR responses are optional. OK may be generated if there are
  609. * implicit gather results or if the recipient wants to send its own
  610. * updated certificate of network membership to the sender. ERROR may be
  611. * generated if a certificate is needed or if multicasts to this group
  612. * are no longer wanted (multicast unsubscribe).
  613. *
  614. * OK response payload:
  615. * <[8] 64-bit network ID>
  616. * <[6] MAC address of multicast group>
  617. * <[4] 32-bit ADI for multicast group>
  618. * <[1] flags>
  619. * [<[...] network certificate of membership (DEPRECATED)>]
  620. * [<[...] implicit gather results if flag 0x01 is set>]
  621. *
  622. * OK flags (same bits as request flags):
  623. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  624. * 0x02 - OK includes implicit gather results
  625. *
  626. * ERROR response payload:
  627. * <[8] 64-bit network ID>
  628. * <[6] multicast group MAC>
  629. * <[4] 32-bit multicast group ADI>
  630. */
  631. VERB_MULTICAST_FRAME_deprecated = 0x0e,
  632. /**
  633. * Push of potential endpoints for direct communication:
  634. * <[2] 16-bit number of paths>
  635. * <[...] paths>
  636. *
  637. * Path record format:
  638. * <[1] 8-bit path flags>
  639. * <[2] length of extended path characteristics or 0 for none>
  640. * <[...] extended path characteristics>
  641. * <[1] address type>
  642. * <[1] address record length in bytes>
  643. * <[...] address>
  644. *
  645. * Path flags:
  646. * 0x01 - Sender is likely behind a symmetric NAT
  647. * 0x02 - Use BFG1024 algorithm for symmetric NAT-t if conditions met
  648. *
  649. * The receiver may, upon receiving a push, attempt to establish a
  650. * direct link to one or more of the indicated addresses. It is the
  651. * responsibility of the sender to limit which peers it pushes direct
  652. * paths to to those with whom it has a trust relationship. The receiver
  653. * must obey any restrictions provided such as exclusivity or blacklists.
  654. * OK responses to this message are optional.
  655. *
  656. * Note that a direct path push does not imply that learned paths can't
  657. * be used unless they are blacklisted explicitly or unless flag 0x01
  658. * is set.
  659. *
  660. * OK and ERROR are not generated.
  661. */
  662. VERB_PUSH_DIRECT_PATHS = 0x10,
  663. /**
  664. * A message with arbitrary user-definable content:
  665. * <[8] 64-bit arbitrary message type ID>
  666. * [<[...] message payload>]
  667. *
  668. * This can be used to send arbitrary messages over VL1. It generates no
  669. * OK or ERROR and has no special semantics outside of whatever the user
  670. * (via the ZeroTier core API) chooses to give it.
  671. *
  672. * Message type IDs less than or equal to 65535 are reserved for use by
  673. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  674. * implementations.
  675. */
  676. VERB_USER_MESSAGE = 0x14,
  677. /**
  678. * Encapsulate a ZeroTier packet for multicast distribution:
  679. * [... begin signed portion ...]
  680. * <[1] 8-bit flags>
  681. * <[5] 40-bit ZeroTier address of sender>
  682. * <[2] 16-bit length of inner payload>
  683. * <[1] inner payload verb>
  684. * <[...] inner payload data>
  685. * [... end signed portion ...]
  686. * <[2] 16-bit length of signature or 0 if un-signed>
  687. * [<[...] optional signature of multicast>]
  688. * <[...] address (min prefix) list>
  689. */
  690. VERB_MULTICAST = 0x16,
  691. /**
  692. * Encapsulate a full ZeroTier packet in another:
  693. * <[...] raw encapsulated packet>
  694. *
  695. * Encapsulation exists to enable secure relaying as opposed to the usual
  696. * "dumb" relaying. The latter is faster but secure relaying has roles
  697. * where endpoint privacy is desired. Multiply nested ENCAP packets
  698. * could allow ZeroTier to act as an onion router.
  699. *
  700. * When encapsulated packets are forwarded they do have their hop count
  701. * field incremented.
  702. */
  703. VERB_ENCAP = 0x17
  704. // protocol max: 0x1f
  705. };
  706. /**
  707. * Error codes used in ERROR packets.
  708. */
  709. enum ErrorCode
  710. {
  711. /* Invalid request */
  712. ERROR_INVALID_REQUEST = 0x01,
  713. /* Bad/unsupported protocol version */
  714. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  715. /* Unknown object queried */
  716. ERROR_OBJ_NOT_FOUND = 0x03,
  717. /* Verb or use case not supported/enabled by this node */
  718. ERROR_UNSUPPORTED_OPERATION = 0x05,
  719. /* Network access denied; updated credentials needed */
  720. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  721. /* Tried to join network, but you're not a member */
  722. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  723. /* Cannot deliver a forwarded ZeroTier packet (for any reason) */
  724. ERROR_CANNOT_DELIVER = 0x09
  725. };
  726. /**
  727. * EXT_FRAME subtypes, which are packed into three bits in the flags field.
  728. *
  729. * This allows the node to know whether this is a normal frame or one generated
  730. * by a special tee or redirect type flow rule.
  731. */
  732. enum ExtFrameSubtype
  733. {
  734. EXT_FRAME_SUBTYPE_NORMAL = 0x0,
  735. EXT_FRAME_SUBTYPE_TEE_OUTBOUND = 0x1,
  736. EXT_FRAME_SUBTYPE_REDIRECT_OUTBOUND = 0x2,
  737. EXT_FRAME_SUBTYPE_WATCH_OUTBOUND = 0x3,
  738. EXT_FRAME_SUBTYPE_TEE_INBOUND = 0x4,
  739. EXT_FRAME_SUBTYPE_REDIRECT_INBOUND = 0x5,
  740. EXT_FRAME_SUBTYPE_WATCH_INBOUND = 0x6
  741. };
  742. /**
  743. * EXT_FRAME flags
  744. */
  745. enum ExtFrameFlag
  746. {
  747. /**
  748. * A certifiate of membership was included (no longer used but still accepted)
  749. */
  750. EXT_FRAME_FLAG_COM_ATTACHED_deprecated = 0x01,
  751. // bits 0x02, 0x04, and 0x08 are occupied by the 3-bit ExtFrameSubtype value.
  752. /**
  753. * An OK(EXT_FRAME) acknowledgement was requested by the sender.
  754. */
  755. EXT_FRAME_FLAG_ACK_REQUESTED = 0x10
  756. };
  757. /**
  758. * NETWORK_CONFIG (or OK(NETWORK_CONFIG_REQUEST)) flags
  759. */
  760. enum NetworkConfigFlag
  761. {
  762. /**
  763. * Indicates that this network config chunk should be fast propagated via rumor mill flooding.
  764. */
  765. NETWORK_CONFIG_FLAG_FAST_PROPAGATE = 0x01
  766. };
  767. /****************************************************************************/
  768. /*
  769. * These are bit-packed structures for rapid parsing of packets or at least
  770. * the fixed size headers thereof. Not all packet types have these as some
  771. * are full of variable length fields are are more easily parsed through
  772. * incremental decoding.
  773. *
  774. * All fields larger than one byte are in big-endian byte order on the wire.
  775. */
  776. /**
  777. * Normal packet header
  778. *
  779. * @tparam PT Packet payload type (default: uint8_t[])
  780. */
  781. ZT_PACKED_STRUCT(struct Header
  782. {
  783. uint64_t packetId;
  784. uint8_t destination[5];
  785. uint8_t source[5];
  786. uint8_t flags;
  787. uint64_t mac;
  788. // --- begin encrypted envelope ---
  789. uint8_t verb;
  790. });
  791. /**
  792. * Packet fragment header
  793. */
  794. ZT_PACKED_STRUCT(struct FragmentHeader
  795. {
  796. uint64_t packetId;
  797. uint8_t destination[5];
  798. uint8_t fragmentIndicator; // always 0xff for fragments
  799. uint8_t counts; // total: most significant four bits, number: least significant four bits
  800. uint8_t hops; // top 5 bits unused and must be zero
  801. });
  802. ZT_PACKED_STRUCT(struct HELLO
  803. {
  804. Header h;
  805. uint8_t versionProtocol;
  806. uint8_t versionMajor;
  807. uint8_t versionMinor;
  808. uint16_t versionRev;
  809. uint64_t timestamp;
  810. });
  811. ZT_PACKED_STRUCT(struct RENDEZVOUS
  812. {
  813. Header h;
  814. uint8_t flags;
  815. uint8_t peerAddress[5];
  816. uint16_t port;
  817. uint8_t addressLength;
  818. });
  819. ZT_PACKED_STRUCT(struct FRAME
  820. {
  821. Header h;
  822. uint64_t networkId;
  823. uint16_t etherType;
  824. });
  825. ZT_PACKED_STRUCT(struct EXT_FRAME
  826. {
  827. Header h;
  828. uint64_t networkId;
  829. uint8_t flags;
  830. });
  831. ZT_PACKED_STRUCT(struct PUSH_DIRECT_PATHS
  832. {
  833. Header h;
  834. uint16_t numPaths;
  835. });
  836. ZT_PACKED_STRUCT(struct MULTICAST_LIKE
  837. {
  838. ZT_PACKED_STRUCT(struct Entry
  839. {
  840. uint64_t networkId;
  841. uint8_t mac[6];
  842. uint32_t adi;
  843. });
  844. Header h;
  845. });
  846. namespace OK {
  847. /**
  848. * OK response header
  849. *
  850. * @tparam PT OK payload type (default: uint8_t[])
  851. */
  852. ZT_PACKED_STRUCT(struct Header
  853. {
  854. Protocol::Header h;
  855. uint8_t inReVerb;
  856. uint64_t inRePacketId;
  857. });
  858. ZT_PACKED_STRUCT(struct WHOIS
  859. {
  860. OK::Header h;
  861. });
  862. ZT_PACKED_STRUCT(struct ECHO
  863. {
  864. OK::Header h;
  865. });
  866. ZT_PACKED_STRUCT(struct HELLO
  867. {
  868. OK::Header h;
  869. uint64_t timestampEcho;
  870. uint8_t versionProtocol;
  871. uint8_t versionMajor;
  872. uint8_t versionMinor;
  873. uint16_t versionRev;
  874. });
  875. ZT_PACKED_STRUCT(struct EXT_FRAME
  876. {
  877. OK::Header h;
  878. uint64_t networkId;
  879. uint8_t flags;
  880. uint8_t destMac[6];
  881. uint8_t sourceMac[6];
  882. uint16_t etherType;
  883. });
  884. ZT_PACKED_STRUCT(struct NETWORK_CONFIG
  885. {
  886. OK::Header h;
  887. uint64_t networkId;
  888. uint64_t configUpdateId;
  889. });
  890. } // namespace OK
  891. namespace ERROR {
  892. /**
  893. * Error header
  894. *
  895. * The error header comes after the packet header but before type-specific payloads.
  896. *
  897. * @tparam PT Error payload type (default: uint8_t[])
  898. */
  899. ZT_PACKED_STRUCT(struct Header
  900. {
  901. Protocol::Header h;
  902. int8_t inReVerb;
  903. uint64_t inRePacketId;
  904. uint8_t error;
  905. });
  906. ZT_PACKED_STRUCT(struct NEED_MEMBERSHIP_CERTIFICATE
  907. {
  908. ERROR::Header h;
  909. uint64_t networkId;
  910. });
  911. ZT_PACKED_STRUCT(struct UNSUPPORTED_OPERATION__NETWORK_CONFIG_REQUEST
  912. {
  913. ERROR::Header h;
  914. uint64_t networkId;
  915. });
  916. } // namespace ERROR
  917. /****************************************************************************/
  918. /**
  919. * Convenience function to pull packet ID from a raw buffer
  920. *
  921. * @param pkt Packet to read first 8 bytes from
  922. * @param packetSize Packet's actual size in bytes
  923. * @return Packet ID or 0 if packet size is less than 8
  924. */
  925. static ZT_INLINE uint64_t packetId(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= 8) ? Utils::loadBigEndian<uint64_t>(pkt.unsafeData) : 0ULL; }
  926. /**
  927. * @param Packet to extract hops from
  928. * @param packetSize Packet's actual size in bytes
  929. * @return 3-bit hops field embedded in packet flags field
  930. */
  931. static ZT_INLINE uint8_t packetHops(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= ZT_PROTO_PACKET_FLAGS_INDEX) ? (pkt.unsafeData[ZT_PROTO_PACKET_FLAGS_INDEX] & ZT_PROTO_FLAG_FIELD_HOPS_MASK) : 0; }
  932. /**
  933. * @param Packet to extract cipher ID from
  934. * @param packetSize Packet's actual size in bytes
  935. * @return 3-bit cipher field embedded in packet flags field
  936. */
  937. static ZT_INLINE uint8_t packetCipher(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= ZT_PROTO_PACKET_FLAGS_INDEX) ? ((pkt.unsafeData[ZT_PROTO_PACKET_FLAGS_INDEX] >> 3U) & 0x07U) : 0; }
  938. /**
  939. * @return 3-bit hops field embedded in packet flags field
  940. */
  941. static ZT_INLINE uint8_t packetHops(const Header &ph) noexcept { return (ph.flags & 0x07U); }
  942. /**
  943. * @return 3-bit cipher field embedded in packet flags field
  944. */
  945. static ZT_INLINE uint8_t packetCipher(const Header &ph) noexcept { return ((ph.flags >> 3U) & 0x07U); }
  946. /**
  947. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  948. *
  949. * This uses extra data from the packet to mangle the secret, yielding when
  950. * combined with Salsa20's conventional 64-bit nonce an effective nonce that's
  951. * more like 68 bits.
  952. *
  953. * @param in Input key (32 bytes)
  954. * @param out Output buffer (32 bytes)
  955. */
  956. static ZT_INLINE void salsa2012DeriveKey(const uint8_t *const in,uint8_t *const out,const Buf &packet,const unsigned int packetSize) noexcept
  957. {
  958. // IV and source/destination addresses. Using the addresses divides the
  959. // key space into two halves-- A->B and B->A (since order will change).
  960. #ifdef ZT_NO_UNALIGNED_ACCESS
  961. for(int i=0;i<18;++i)
  962. out[i] = in[i] ^ packet.unsafeData[i];
  963. #else
  964. *reinterpret_cast<uint64_t *>(out) = *reinterpret_cast<const uint64_t *>(in) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData);
  965. *reinterpret_cast<uint64_t *>(out + 8) = *reinterpret_cast<const uint64_t *>(in + 8) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData + 8);
  966. *reinterpret_cast<uint16_t *>(out + 16) = *reinterpret_cast<const uint16_t *>(in + 16) ^ *reinterpret_cast<const uint16_t *>(packet.unsafeData + 16);
  967. #endif
  968. // Flags, but with hop count masked off. Hop count is altered by forwarding
  969. // nodes and is the only field that is mutable by unauthenticated third parties.
  970. out[18] = in[18] ^ (packet.unsafeData[18] & 0xf8U);
  971. // Raw packet size in bytes -- thus each packet size defines a new key space.
  972. out[19] = in[19] ^ (uint8_t)packetSize;
  973. out[20] = in[20] ^ (uint8_t)(packetSize >> 8U); // little endian
  974. // Rest of raw key is used unchanged
  975. #ifdef ZT_NO_UNALIGNED_ACCESS
  976. for(int i=21;i<32;++i)
  977. out[i] = in[i];
  978. #else
  979. out[21] = in[21];
  980. out[22] = in[22];
  981. out[23] = in[23];
  982. *reinterpret_cast<uint64_t *>(out + 24) = *reinterpret_cast<const uint64_t *>(in + 24);
  983. #endif
  984. }
  985. /**
  986. * Create a short probe packet for probing a recipient for e.g. NAT traversal and path setup
  987. *
  988. * @param sender Sender identity
  989. * @param recipient Recipient identity
  990. * @param key Long-term shared secret key resulting from sender and recipient agreement
  991. * @return Probe packed into 64-bit integer (in big-endian byte order)
  992. */
  993. uint64_t createProbe(const Identity &sender,const Identity &recipient,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) noexcept;
  994. // Do not use directly
  995. extern std::atomic<uint64_t> _s_packetIdCtr;
  996. /**
  997. * Get a packet ID (and nonce) for a new packet
  998. *
  999. * @return Next packet ID
  1000. */
  1001. static ZT_INLINE uint64_t getPacketId() noexcept { return ++_s_packetIdCtr; }
  1002. /**
  1003. * Encrypt and compute packet MAC
  1004. *
  1005. * @param pkt Packet data to encrypt (in place)
  1006. * @param packetSize Packet size, must be at least ZT_PROTO_MIN_PACKET_LENGTH or crash will occur
  1007. * @param key Key to use for encryption (not per-packet key)
  1008. * @param cipherSuite Cipher suite to use for AEAD encryption or just MAC
  1009. */
  1010. void armor(Buf &pkt,int packetSize,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH],uint8_t cipherSuite) noexcept;
  1011. /**
  1012. * Attempt to compress packet payload
  1013. *
  1014. * This attempts compression and swaps the pointer in 'pkt' for a buffer holding
  1015. * compressed data on success. If compression did not shrink the packet, the original
  1016. * packet size is returned and 'pkt' remains unchanged. If compression is successful
  1017. * the compressed verb flag is also set.
  1018. *
  1019. * @param pkt Packet buffer value/result parameter: pointer may be swapped if compression is successful
  1020. * @param packetSize Total size of packet in bytes (including headers)
  1021. * @return New size of packet after compression or original size of compression wasn't helpful
  1022. */
  1023. int compress(SharedPtr<Buf> &pkt,int packetSize) noexcept;
  1024. } // namespace Protocol
  1025. } // namespace ZeroTier
  1026. #endif