Protocol.hpp 35 KB

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