Protocol.hpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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: signed locator for this node
  216. */
  217. #define ZT_PROTO_HELLO_NODE_META_LOCATOR "l"
  218. /**
  219. * HELLO exchange meta-data: ephemeral C25519 public key
  220. */
  221. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_KEY_C25519 "e0"
  222. /**
  223. * HELLO exchange meta-data: ephemeral NIST P-384 public key
  224. */
  225. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_KEY_P384 "e1"
  226. /**
  227. * HELLO exchange meta-data: address(es) of nodes to whom this node will relay
  228. */
  229. #define ZT_PROTO_HELLO_NODE_META_WILL_RELAY_TO "wr"
  230. /**
  231. * HELLO exchange meta-data: X coordinate of your node (sent in OK(HELLO))
  232. */
  233. #define ZT_PROTO_HELLO_NODE_META_LOCATION_X "gX"
  234. /**
  235. * HELLO exchange meta-data: Y coordinate of your node (sent in OK(HELLO))
  236. */
  237. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Y "gY"
  238. /**
  239. * HELLO exchange meta-data: Z coordinate of your node (sent in OK(HELLO))
  240. */
  241. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Z "gZ"
  242. /**
  243. * HELLO exchange meta-data: preferred cipher suite (may be ignored)
  244. */
  245. #define ZT_PROTO_HELLO_NODE_META_PREFERRED_CIPHER_SUITE "c"
  246. namespace ZeroTier {
  247. namespace Protocol {
  248. /**
  249. * Packet verb (message type)
  250. */
  251. enum Verb
  252. {
  253. /**
  254. * No operation
  255. *
  256. * This packet does nothing, but it is sometimes sent as a probe to
  257. * trigger a HELLO exchange as the code will attempt HELLO when it
  258. * receives a packet from an unidentified source.
  259. */
  260. VERB_NOP = 0x00,
  261. /**
  262. * Announcement of a node's existence and vitals:
  263. * <[1] protocol version>
  264. * <[1] software major version>
  265. * <[1] software minor version>
  266. * <[2] software revision>
  267. * <[8] timestamp for determining latency>
  268. * <[...] binary serialized identity>
  269. * <[...] physical destination address of packet>
  270. * [... begin encrypted region ...]
  271. * <[2] 16-bit reserved (legacy) field, always 0>
  272. * <[2] 16-bit length of meta-data dictionary>
  273. * <[...] meta-data dictionary>
  274. * <[2] 16-bit length of any additional fields>
  275. * [... end encrypted region ...]
  276. * <[48] HMAC-SHA384 of packet (with hops field masked to 0)>
  277. *
  278. * HELLO is sent using the POLY1305_NONE cipher setting (MAC but
  279. * no encryption) and as of protocol version 11 contains an extra
  280. * HMAC-SHA384 MAC for additional authentication hardening.
  281. *
  282. * The physical desgination address is the raw InetAddress to which the
  283. * packet was sent, regardless of any relaying used.
  284. *
  285. * HELLO packets have an encrypted section that is encrypted with
  286. * Salsa20/12 using the two peers' long-term negotiated keys and with
  287. * the packet ID (with least significant 3 bits masked to 0 for legacy
  288. * reasons) as the Salsa20/12 IV. This encryption is technically not
  289. * necessary but serves to protect the privacy of locators and other
  290. * fields for a little added defense in depth. Note to auditors: for FIPS
  291. * or other auditing purposes this crypto can be ignored as its
  292. * compromise poses no risk to peer or network authentication or transport
  293. * data privacy. HMAC is computed after this encryption is performed and
  294. * is verified before decryption is performed.
  295. *
  296. * A valid and successfully authenticated HELLO will generate the following
  297. * OK response which contains much of the same information about the
  298. * responding peer.
  299. *
  300. * OK payload:
  301. * <[8] timestamp echoed from original HELLO packet>
  302. * <[1] protocol version>
  303. * <[1] software major version>
  304. * <[1] software minor version>
  305. * <[2] software revision>
  306. * <[...] physical destination address of packet>
  307. * <[2] 16-bit reserved (legacy) field, currently must be 0>
  308. * <[2] 16-bit length of meta-data dictionary>
  309. * <[...] meta-data dictionary>
  310. * <[2] 16-bit length of any additional fields>
  311. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  312. */
  313. VERB_HELLO = 0x01,
  314. /**
  315. * Error response:
  316. * <[1] in-re verb>
  317. * <[8] in-re packet ID>
  318. * <[1] error code>
  319. * <[...] error-dependent payload, may be empty>
  320. *
  321. * An ERROR that does not pertain to a specific packet will have its verb
  322. * set to VERB_NOP and its packet ID set to zero.
  323. */
  324. VERB_ERROR = 0x02,
  325. /**
  326. * Success response:
  327. * <[1] in-re verb>
  328. * <[8] in-re packet ID>
  329. * <[...] request-specific payload>
  330. */
  331. VERB_OK = 0x03,
  332. /**
  333. * Query an identity by address:
  334. * <[5] address to look up>
  335. * [<[...] additional addresses to look up>
  336. *
  337. * OK response payload:
  338. * <[...] identity>
  339. * <[...] locator>
  340. * [... additional identity/locator pairs]
  341. *
  342. * If the address is not found, no response is generated. The semantics
  343. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  344. * be performed.
  345. *
  346. * It is possible for an identity but a null/empty locator to be returned
  347. * if no locator is known for a node. Older versions may omit the locator.
  348. */
  349. VERB_WHOIS = 0x04,
  350. /**
  351. * Relay-mediated NAT traversal or firewall punching initiation:
  352. * <[1] flags (unused, currently 0)>
  353. * <[5] ZeroTier address of peer that might be found at this address>
  354. * <[2] 16-bit protocol address port>
  355. * <[1] protocol address length / type>
  356. * <[...] protocol address (network byte order)>
  357. *
  358. * This is sent by a third party node to inform a node of where another
  359. * may be located. These are currently only allowed from roots.
  360. *
  361. * The protocol address format differs from the standard InetAddress
  362. * encoding for legacy reasons, but it's not hard to decode. The following
  363. * values are valid for the protocol address length (type) field:
  364. *
  365. * 4 - IPv4 IP address
  366. * 16 - IPv6 IP address
  367. * 255 - Endpoint object, unmarshaled in place (port ignored)
  368. *
  369. * No OK or ERROR is generated.
  370. */
  371. VERB_RENDEZVOUS = 0x05,
  372. /**
  373. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  374. * <[8] 64-bit network ID>
  375. * <[2] 16-bit ethertype>
  376. * <[...] ethernet payload>
  377. *
  378. * MAC addresses are derived from the packet's source and destination
  379. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  380. * Ethernet framing and other optional flags and features when they
  381. * are not necessary.
  382. *
  383. * ERROR may be generated if a membership certificate is needed for a
  384. * closed network. Payload will be network ID.
  385. */
  386. VERB_FRAME = 0x06,
  387. /**
  388. * Full Ethernet frame with MAC addressing and optional fields:
  389. * <[8] 64-bit network ID>
  390. * <[1] flags>
  391. * <[6] destination MAC or all zero for destination node>
  392. * <[6] source MAC or all zero for node of origin>
  393. * <[2] 16-bit ethertype>
  394. * <[...] ethernet payload>
  395. *
  396. * Flags:
  397. * 0x01 - Certificate of network membership attached (DEPRECATED)
  398. * 0x02 - Most significant bit of subtype (see below)
  399. * 0x04 - Middle bit of subtype (see below)
  400. * 0x08 - Least significant bit of subtype (see below)
  401. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  402. *
  403. * Subtypes (0..7):
  404. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  405. * 0x1 - TEEd outbound frame
  406. * 0x2 - REDIRECTed outbound frame
  407. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  408. * 0x4 - TEEd inbound frame
  409. * 0x5 - REDIRECTed inbound frame
  410. * 0x6 - WATCHed inbound frame
  411. * 0x7 - (reserved for future use)
  412. *
  413. * An extended frame carries full MAC addressing, making it a
  414. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  415. * spoke multicast propagation is requested.
  416. *
  417. * OK payload (if ACK flag is set):
  418. * <[8] 64-bit network ID>
  419. * <[1] flags>
  420. * <[6] destination MAC or all zero for destination node>
  421. * <[6] source MAC or all zero for node of origin>
  422. * <[2] 16-bit ethertype>
  423. */
  424. VERB_EXT_FRAME = 0x07,
  425. /**
  426. * ECHO request (a.k.a. ping):
  427. * <[...] arbitrary payload>
  428. *
  429. * This generates OK with a copy of the transmitted payload. No ERROR
  430. * is generated. Response to ECHO requests is optional and ECHO may be
  431. * ignored if a node detects a possible flood.
  432. */
  433. VERB_ECHO = 0x08,
  434. /**
  435. * Announce interest in multicast group(s):
  436. * <[8] 64-bit network ID>
  437. * <[6] multicast Ethernet address>
  438. * <[4] multicast additional distinguishing information (ADI)>
  439. * [... additional tuples of network/address/adi ...]
  440. *
  441. * LIKEs may be sent to any peer, though a good implementation should
  442. * restrict them to peers on the same network they're for and to network
  443. * controllers and root servers. In the current network, root servers
  444. * will provide the service of final multicast cache.
  445. */
  446. VERB_MULTICAST_LIKE = 0x09,
  447. /**
  448. * Network credentials push:
  449. * [<[...] one or more certificates of membership>]
  450. * <[1] 0x00, null byte marking end of COM array>
  451. * <[2] 16-bit number of capabilities>
  452. * <[...] one or more serialized Capability>
  453. * <[2] 16-bit number of tags>
  454. * <[...] one or more serialized Tags>
  455. * <[2] 16-bit number of revocations>
  456. * <[...] one or more serialized Revocations>
  457. * <[2] 16-bit number of certificates of ownership>
  458. * <[...] one or more serialized CertificateOfOwnership>
  459. *
  460. * This can be sent by anyone at any time to push network credentials.
  461. * These will of course only be accepted if they are properly signed.
  462. * Credentials can be for any number of networks.
  463. *
  464. * The use of a zero byte to terminate the COM section is for legacy
  465. * backward compatibility. Newer fields are prefixed with a length.
  466. *
  467. * OK/ERROR are not generated.
  468. */
  469. VERB_NETWORK_CREDENTIALS = 0x0a,
  470. /**
  471. * Network configuration request:
  472. * <[8] 64-bit network ID>
  473. * <[2] 16-bit length of request meta-data dictionary>
  474. * <[...] string-serialized request meta-data>
  475. * <[8] 64-bit revision of netconf we currently have>
  476. * <[8] 64-bit timestamp of netconf we currently have>
  477. *
  478. * This message requests network configuration from a node capable of
  479. * providing it. Responses can be sent as OK(NETWORK_CONFIG_REQUEST)
  480. * or NETWORK_CONFIG messages. NETWORK_CONFIG can also be sent by
  481. * network controllers or other nodes unsolicited.
  482. *
  483. * OK response payload:
  484. * (same as VERB_NETWORK_CONFIG payload)
  485. *
  486. * ERROR response payload:
  487. * <[8] 64-bit network ID>
  488. */
  489. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  490. /**
  491. * Network configuration data push:
  492. * <[8] 64-bit network ID>
  493. * <[2] 16-bit length of network configuration dictionary chunk>
  494. * <[...] network configuration dictionary (may be incomplete)>
  495. * <[1] 8-bit flags>
  496. * <[8] 64-bit config update ID (should never be 0)>
  497. * <[4] 32-bit total length of assembled dictionary>
  498. * <[4] 32-bit index of chunk>
  499. * [ ... end signed portion ... ]
  500. * <[1] 8-bit reserved field (legacy)>
  501. * <[2] 16-bit length of chunk signature>
  502. * <[...] chunk signature>
  503. *
  504. * Network configurations can come from network controllers or theoretically
  505. * any other node, but each chunk must be signed by the network controller
  506. * that generated it originally. The config update ID is arbitrary and is merely
  507. * used by the receiver to group chunks. Chunk indexes must be sequential and
  508. * the total delivered chunks must yield a total network config equal to the
  509. * specified total length.
  510. *
  511. * Flags:
  512. * 0x01 - Use fast propagation -- rumor mill flood this chunk to other members
  513. *
  514. * An OK should be sent if the config is successfully received and
  515. * accepted.
  516. *
  517. * OK payload:
  518. * <[8] 64-bit network ID>
  519. * <[8] 64-bit config update ID>
  520. */
  521. VERB_NETWORK_CONFIG = 0x0c,
  522. /**
  523. * Request endpoints for multicast distribution:
  524. * <[8] 64-bit network ID>
  525. * <[1] flags>
  526. * <[6] MAC address of multicast group being queried>
  527. * <[4] 32-bit ADI for multicast group being queried>
  528. * <[4] 32-bit requested max number of multicast peers>
  529. *
  530. * This message asks a peer for additional known endpoints that have
  531. * LIKEd a given multicast group. It's sent when the sender wishes
  532. * to send multicast but does not have the desired number of recipient
  533. * peers.
  534. *
  535. * OK response payload: (multiple OKs can be generated)
  536. * <[8] 64-bit network ID>
  537. * <[6] MAC address of multicast group being queried>
  538. * <[4] 32-bit ADI for multicast group being queried>
  539. * <[4] 32-bit total number of known members in this multicast group>
  540. * <[2] 16-bit number of members enumerated in this packet>
  541. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  542. *
  543. * ERROR is not generated; queries that return no response are dropped.
  544. */
  545. VERB_MULTICAST_GATHER = 0x0d,
  546. /** *** DEPRECATED ***
  547. * Multicast frame:
  548. * <[8] 64-bit network ID>
  549. * <[1] flags>
  550. * [<[4] 32-bit implicit gather limit>]
  551. * [<[6] source MAC>]
  552. * <[6] destination MAC (multicast address)>
  553. * <[4] 32-bit multicast ADI (multicast address extension)>
  554. * <[2] 16-bit ethertype>
  555. * <[...] ethernet payload>
  556. *
  557. * Flags:
  558. * 0x01 - Network certificate of membership attached (DEPRECATED)
  559. * 0x02 - Implicit gather limit field is present
  560. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  561. * 0x08 - Please replicate (sent to multicast replicators)
  562. *
  563. * OK and ERROR responses are optional. OK may be generated if there are
  564. * implicit gather results or if the recipient wants to send its own
  565. * updated certificate of network membership to the sender. ERROR may be
  566. * generated if a certificate is needed or if multicasts to this group
  567. * are no longer wanted (multicast unsubscribe).
  568. *
  569. * OK response payload:
  570. * <[8] 64-bit network ID>
  571. * <[6] MAC address of multicast group>
  572. * <[4] 32-bit ADI for multicast group>
  573. * <[1] flags>
  574. * [<[...] network certificate of membership (DEPRECATED)>]
  575. * [<[...] implicit gather results if flag 0x01 is set>]
  576. *
  577. * OK flags (same bits as request flags):
  578. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  579. * 0x02 - OK includes implicit gather results
  580. *
  581. * ERROR response payload:
  582. * <[8] 64-bit network ID>
  583. * <[6] multicast group MAC>
  584. * <[4] 32-bit multicast group ADI>
  585. */
  586. VERB_MULTICAST_FRAME_deprecated = 0x0e,
  587. /**
  588. * Push of potential endpoints for direct communication:
  589. * <[2] 16-bit number of paths>
  590. * <[...] paths>
  591. *
  592. * Path record format:
  593. * <[1] 8-bit path flags>
  594. * <[2] length of extended path characteristics or 0 for none>
  595. * <[...] extended path characteristics>
  596. * <[1] address type>
  597. * <[1] address record length in bytes>
  598. * <[...] address>
  599. *
  600. * Path flags:
  601. * 0x01 - Sender is likely behind a symmetric NAT
  602. * 0x02 - Use BFG1024 algorithm for symmetric NAT-t if conditions met
  603. *
  604. * The receiver may, upon receiving a push, attempt to establish a
  605. * direct link to one or more of the indicated addresses. It is the
  606. * responsibility of the sender to limit which peers it pushes direct
  607. * paths to to those with whom it has a trust relationship. The receiver
  608. * must obey any restrictions provided such as exclusivity or blacklists.
  609. * OK responses to this message are optional.
  610. *
  611. * Note that a direct path push does not imply that learned paths can't
  612. * be used unless they are blacklisted explicitly or unless flag 0x01
  613. * is set.
  614. *
  615. * OK and ERROR are not generated.
  616. */
  617. VERB_PUSH_DIRECT_PATHS = 0x10,
  618. /**
  619. * A message with arbitrary user-definable content:
  620. * <[8] 64-bit arbitrary message type ID>
  621. * [<[...] message payload>]
  622. *
  623. * This can be used to send arbitrary messages over VL1. It generates no
  624. * OK or ERROR and has no special semantics outside of whatever the user
  625. * (via the ZeroTier core API) chooses to give it.
  626. *
  627. * Message type IDs less than or equal to 65535 are reserved for use by
  628. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  629. * implementations.
  630. */
  631. VERB_USER_MESSAGE = 0x14,
  632. /**
  633. * Encapsulate a ZeroTier packet for multicast distribution:
  634. * [... begin signed portion ...]
  635. * <[1] 8-bit flags>
  636. * <[5] 40-bit ZeroTier address of sender>
  637. * <[2] 16-bit length of inner payload>
  638. * <[1] inner payload verb>
  639. * <[...] inner payload data>
  640. * [... end signed portion ...]
  641. * <[2] 16-bit length of signature or 0 if un-signed>
  642. * [<[...] optional signature of multicast>]
  643. * <[...] address (min prefix) list>
  644. */
  645. VERB_MULTICAST = 0x16,
  646. /**
  647. * Encapsulate a full ZeroTier packet in another:
  648. * <[...] raw encapsulated packet>
  649. *
  650. * Encapsulation exists to enable secure relaying as opposed to the usual
  651. * "dumb" relaying. The latter is faster but secure relaying has roles
  652. * where endpoint privacy is desired. Multiply nested ENCAP packets
  653. * could allow ZeroTier to act as an onion router.
  654. *
  655. * When encapsulated packets are forwarded they do have their hop count
  656. * field incremented.
  657. */
  658. VERB_ENCAP = 0x17
  659. // protocol max: 0x1f
  660. };
  661. /**
  662. * Error codes used in ERROR packets.
  663. */
  664. enum ErrorCode
  665. {
  666. /* Invalid request */
  667. ERROR_INVALID_REQUEST = 0x01,
  668. /* Bad/unsupported protocol version */
  669. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  670. /* Unknown object queried */
  671. ERROR_OBJ_NOT_FOUND = 0x03,
  672. /* Verb or use case not supported/enabled by this node */
  673. ERROR_UNSUPPORTED_OPERATION = 0x05,
  674. /* Network access denied; updated credentials needed */
  675. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  676. /* Tried to join network, but you're not a member */
  677. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  678. /* Cannot deliver a forwarded ZeroTier packet (for any reason) */
  679. ERROR_CANNOT_DELIVER = 0x09
  680. };
  681. /**
  682. * EXT_FRAME subtypes, which are packed into three bits in the flags field.
  683. *
  684. * This allows the node to know whether this is a normal frame or one generated
  685. * by a special tee or redirect type flow rule.
  686. */
  687. enum ExtFrameSubtype
  688. {
  689. EXT_FRAME_SUBTYPE_NORMAL = 0x0,
  690. EXT_FRAME_SUBTYPE_TEE_OUTBOUND = 0x1,
  691. EXT_FRAME_SUBTYPE_REDIRECT_OUTBOUND = 0x2,
  692. EXT_FRAME_SUBTYPE_WATCH_OUTBOUND = 0x3,
  693. EXT_FRAME_SUBTYPE_TEE_INBOUND = 0x4,
  694. EXT_FRAME_SUBTYPE_REDIRECT_INBOUND = 0x5,
  695. EXT_FRAME_SUBTYPE_WATCH_INBOUND = 0x6
  696. };
  697. /**
  698. * EXT_FRAME flags
  699. */
  700. enum ExtFrameFlag
  701. {
  702. /**
  703. * A certifiate of membership was included (no longer used but still accepted)
  704. */
  705. EXT_FRAME_FLAG_COM_ATTACHED_deprecated = 0x01,
  706. // bits 0x02, 0x04, and 0x08 are occupied by the 3-bit ExtFrameSubtype value.
  707. /**
  708. * An OK(EXT_FRAME) acknowledgement was requested by the sender.
  709. */
  710. EXT_FRAME_FLAG_ACK_REQUESTED = 0x10
  711. };
  712. /**
  713. * NETWORK_CONFIG (or OK(NETWORK_CONFIG_REQUEST)) flags
  714. */
  715. enum NetworkConfigFlag
  716. {
  717. /**
  718. * Indicates that this network config chunk should be fast propagated via rumor mill flooding.
  719. */
  720. NETWORK_CONFIG_FLAG_FAST_PROPAGATE = 0x01
  721. };
  722. /****************************************************************************/
  723. /*
  724. * These are bit-packed structures for rapid parsing of packets or at least
  725. * the fixed size headers thereof. Not all packet types have these as some
  726. * are full of variable length fields are are more easily parsed through
  727. * incremental decoding.
  728. *
  729. * All fields larger than one byte are in big-endian byte order on the wire.
  730. */
  731. /**
  732. * Normal packet header
  733. *
  734. * @tparam PT Packet payload type (default: uint8_t[])
  735. */
  736. ZT_PACKED_STRUCT(struct Header
  737. {
  738. uint64_t packetId;
  739. uint8_t destination[5];
  740. uint8_t source[5];
  741. uint8_t flags;
  742. uint64_t mac;
  743. // --- begin encrypted envelope ---
  744. uint8_t verb;
  745. });
  746. /**
  747. * Packet fragment header
  748. */
  749. ZT_PACKED_STRUCT(struct FragmentHeader
  750. {
  751. uint64_t packetId;
  752. uint8_t destination[5];
  753. uint8_t fragmentIndicator; // always 0xff for fragments
  754. uint8_t counts; // total: most significant four bits, number: least significant four bits
  755. uint8_t hops; // top 5 bits unused and must be zero
  756. });
  757. ZT_PACKED_STRUCT(struct HELLO
  758. {
  759. Header h;
  760. uint8_t versionProtocol;
  761. uint8_t versionMajor;
  762. uint8_t versionMinor;
  763. uint16_t versionRev;
  764. uint64_t timestamp;
  765. });
  766. ZT_PACKED_STRUCT(struct RENDEZVOUS
  767. {
  768. Header h;
  769. uint8_t flags;
  770. uint8_t peerAddress[5];
  771. uint16_t port;
  772. uint8_t addressLength;
  773. });
  774. ZT_PACKED_STRUCT(struct FRAME
  775. {
  776. Header h;
  777. uint64_t networkId;
  778. uint16_t etherType;
  779. });
  780. ZT_PACKED_STRUCT(struct EXT_FRAME
  781. {
  782. Header h;
  783. uint64_t networkId;
  784. uint8_t flags;
  785. });
  786. ZT_PACKED_STRUCT(struct PUSH_DIRECT_PATHS
  787. {
  788. Header h;
  789. uint16_t numPaths;
  790. });
  791. ZT_PACKED_STRUCT(struct MULTICAST_LIKE
  792. {
  793. ZT_PACKED_STRUCT(struct Entry
  794. {
  795. uint64_t networkId;
  796. uint8_t mac[6];
  797. uint32_t adi;
  798. });
  799. Header h;
  800. });
  801. namespace OK {
  802. /**
  803. * OK response header
  804. *
  805. * @tparam PT OK payload type (default: uint8_t[])
  806. */
  807. ZT_PACKED_STRUCT(struct Header
  808. {
  809. Protocol::Header h;
  810. uint8_t inReVerb;
  811. uint64_t inRePacketId;
  812. });
  813. ZT_PACKED_STRUCT(struct WHOIS
  814. {
  815. OK::Header h;
  816. });
  817. ZT_PACKED_STRUCT(struct ECHO
  818. {
  819. OK::Header h;
  820. });
  821. ZT_PACKED_STRUCT(struct HELLO
  822. {
  823. OK::Header h;
  824. uint64_t timestampEcho;
  825. uint8_t versionProtocol;
  826. uint8_t versionMajor;
  827. uint8_t versionMinor;
  828. uint16_t versionRev;
  829. });
  830. ZT_PACKED_STRUCT(struct EXT_FRAME
  831. {
  832. OK::Header h;
  833. uint64_t networkId;
  834. uint8_t flags;
  835. uint8_t destMac[6];
  836. uint8_t sourceMac[6];
  837. uint16_t etherType;
  838. });
  839. ZT_PACKED_STRUCT(struct NETWORK_CONFIG
  840. {
  841. OK::Header h;
  842. uint64_t networkId;
  843. uint64_t configUpdateId;
  844. });
  845. } // namespace OK
  846. namespace ERROR {
  847. /**
  848. * Error header
  849. *
  850. * The error header comes after the packet header but before type-specific payloads.
  851. *
  852. * @tparam PT Error payload type (default: uint8_t[])
  853. */
  854. ZT_PACKED_STRUCT(struct Header
  855. {
  856. Protocol::Header h;
  857. int8_t inReVerb;
  858. uint64_t inRePacketId;
  859. uint8_t error;
  860. });
  861. ZT_PACKED_STRUCT(struct NEED_MEMBERSHIP_CERTIFICATE
  862. {
  863. ERROR::Header h;
  864. uint64_t networkId;
  865. });
  866. ZT_PACKED_STRUCT(struct UNSUPPORTED_OPERATION__NETWORK_CONFIG_REQUEST
  867. {
  868. ERROR::Header h;
  869. uint64_t networkId;
  870. });
  871. } // namespace ERROR
  872. /****************************************************************************/
  873. /**
  874. * Convenience function to pull packet ID from a raw buffer
  875. *
  876. * @param pkt Packet to read first 8 bytes from
  877. * @param packetSize Packet's actual size in bytes
  878. * @return Packet ID or 0 if packet size is less than 8
  879. */
  880. static ZT_ALWAYS_INLINE uint64_t packetId(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= 8) ? Utils::loadBigEndian<uint64_t>(pkt.unsafeData) : 0ULL; }
  881. /**
  882. * @param Packet to extract hops from
  883. * @param packetSize Packet's actual size in bytes
  884. * @return 3-bit hops field embedded in packet flags field
  885. */
  886. static ZT_ALWAYS_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; }
  887. /**
  888. * @param Packet to extract cipher ID from
  889. * @param packetSize Packet's actual size in bytes
  890. * @return 3-bit cipher field embedded in packet flags field
  891. */
  892. static ZT_ALWAYS_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; }
  893. /**
  894. * @return 3-bit hops field embedded in packet flags field
  895. */
  896. static ZT_ALWAYS_INLINE uint8_t packetHops(const Header &ph) noexcept { return (ph.flags & 0x07U); }
  897. /**
  898. * @return 3-bit cipher field embedded in packet flags field
  899. */
  900. static ZT_ALWAYS_INLINE uint8_t packetCipher(const Header &ph) noexcept { return ((ph.flags >> 3U) & 0x07U); }
  901. /**
  902. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  903. *
  904. * This uses extra data from the packet to mangle the secret, yielding when
  905. * combined with Salsa20's conventional 64-bit nonce an effective nonce that's
  906. * more like 68 bits.
  907. *
  908. * @param in Input key (32 bytes)
  909. * @param out Output buffer (32 bytes)
  910. */
  911. static ZT_ALWAYS_INLINE void salsa2012DeriveKey(const uint8_t *const in,uint8_t *const out,const Buf &packet,const unsigned int packetSize) noexcept
  912. {
  913. // IV and source/destination addresses. Using the addresses divides the
  914. // key space into two halves-- A->B and B->A (since order will change).
  915. #ifdef ZT_NO_UNALIGNED_ACCESS
  916. for(int i=0;i<18;++i)
  917. out[i] = in[i] ^ packet.b[i];
  918. #else
  919. *reinterpret_cast<uint64_t *>(out) = *reinterpret_cast<const uint64_t *>(in) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData);
  920. *reinterpret_cast<uint64_t *>(out + 8) = *reinterpret_cast<const uint64_t *>(in + 8) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData + 8);
  921. *reinterpret_cast<uint16_t *>(out + 16) = *reinterpret_cast<const uint16_t *>(in + 16) ^ *reinterpret_cast<const uint16_t *>(packet.unsafeData + 16);
  922. #endif
  923. // Flags, but with hop count masked off. Hop count is altered by forwarding
  924. // nodes and is the only field that is mutable by unauthenticated third parties.
  925. out[18] = in[18] ^ (packet.unsafeData[18] & 0xf8U);
  926. // Raw packet size in bytes -- thus each packet size defines a new key space.
  927. out[19] = in[19] ^ (uint8_t)packetSize;
  928. out[20] = in[20] ^ (uint8_t)(packetSize >> 8U); // little endian
  929. // Rest of raw key is used unchanged
  930. #ifdef ZT_NO_UNALIGNED_ACCESS
  931. for(int i=21;i<32;++i)
  932. out[i] = in[i];
  933. #else
  934. out[21] = in[21];
  935. out[22] = in[22];
  936. out[23] = in[23];
  937. *reinterpret_cast<uint64_t *>(out + 24) = *reinterpret_cast<const uint64_t *>(in + 24);
  938. #endif
  939. }
  940. /**
  941. * Create a short probe packet for probing a recipient for e.g. NAT traversal and path setup
  942. *
  943. * @param sender Sender identity
  944. * @param recipient Recipient identity
  945. * @param key Long-term shared secret key resulting from sender and recipient agreement
  946. * @return Probe packed into 64-bit integer (in big-endian byte order)
  947. */
  948. uint64_t createProbe(const Identity &sender,const Identity &recipient,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) noexcept;
  949. /**
  950. * Get a sequential non-repeating packet ID for the next packet (thread-safe)
  951. *
  952. * @return Next packet ID / cryptographic nonce
  953. */
  954. uint64_t getPacketId() noexcept;
  955. /**
  956. * Encrypt and compute packet MAC
  957. *
  958. * @param pkt Packet data to encrypt (in place)
  959. * @param packetSize Packet size, must be at least ZT_PROTO_MIN_PACKET_LENGTH or crash will occur
  960. * @param key Key to use for encryption (not per-packet key)
  961. * @param cipherSuite Cipher suite to use for AEAD encryption or just MAC
  962. */
  963. void armor(Buf &pkt,int packetSize,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH],uint8_t cipherSuite) noexcept;
  964. /**
  965. * Attempt to compress packet payload
  966. *
  967. * This attempts compression and swaps the pointer in 'pkt' for a buffer holding
  968. * compressed data on success. If compression did not shrink the packet, the original
  969. * packet size is returned and 'pkt' remains unchanged. If compression is successful
  970. * the compressed verb flag is also set.
  971. *
  972. * @param pkt Packet buffer value/result parameter: pointer may be swapped if compression is successful
  973. * @param packetSize Total size of packet in bytes (including headers)
  974. * @return New size of packet after compression or original size of compression wasn't helpful
  975. */
  976. int compress(SharedPtr<Buf> &pkt,int packetSize) noexcept;
  977. } // namespace Protocol
  978. } // namespace ZeroTier
  979. #endif