Protocol.hpp 37 KB

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