Protocol.hpp 32 KB

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