Protocol.hpp 34 KB

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