Packet.hpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_N_PACKET_HPP
  19. #define ZT_N_PACKET_HPP
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <string>
  24. #include <iostream>
  25. #include "Constants.hpp"
  26. #include "Address.hpp"
  27. #include "Poly1305.hpp"
  28. #include "Salsa20.hpp"
  29. #include "Utils.hpp"
  30. #include "Buffer.hpp"
  31. #include "../ext/lz4/lz4.h"
  32. /**
  33. * Protocol version -- incremented only for major changes
  34. *
  35. * 1 - 0.2.0 ... 0.2.5
  36. * 2 - 0.3.0 ... 0.4.5
  37. * + Added signature and originating peer to multicast frame
  38. * + Double size of multicast frame bloom filter
  39. * 3 - 0.5.0 ... 0.6.0
  40. * + Yet another multicast redesign
  41. * + New crypto completely changes key agreement cipher
  42. * 4 - 0.6.0 ... 1.0.6
  43. * + New identity format based on hashcash design
  44. * 5 - 1.1.0 ... CURRENT
  45. * + Supports circuit test, proof of work, and echo
  46. * + Supports in-band world (root server definition) updates
  47. * + Clustering! (Though this will work with protocol v4 clients.)
  48. * + Otherwise backward compatible with protocol v4
  49. */
  50. #define ZT_PROTO_VERSION 5
  51. /**
  52. * Minimum supported protocol version
  53. */
  54. #define ZT_PROTO_VERSION_MIN 4
  55. /**
  56. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  57. *
  58. * This is a protocol constant. It's the maximum allowed by the length
  59. * of the hop counter -- three bits. See node/Constants.hpp for the
  60. * pragmatic forwarding limit, which is typically lower.
  61. */
  62. #define ZT_PROTO_MAX_HOPS 7
  63. /**
  64. * Cipher suite: Curve25519/Poly1305/Salsa20/12/NOCRYPT
  65. *
  66. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  67. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  68. * but the payload is not encrypted. This is currently only used to send
  69. * HELLO since that's the public key specification packet and must be
  70. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  71. * curve Diffie-Hellman.
  72. */
  73. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  74. /**
  75. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  76. *
  77. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  78. * stream as its one-time-use key followed by payload encryption with
  79. * the remaining Salsa20/12 key stream. Key agreement is performed using
  80. * Curve25519 elliptic curve Diffie-Hellman.
  81. */
  82. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  83. /**
  84. * DEPRECATED payload encrypted flag, will be removed for re-use soon.
  85. *
  86. * This has been replaced by the two-bit cipher suite selection field where
  87. * a value of 0 indicates unencrypted (but authenticated) messages.
  88. */
  89. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  90. /**
  91. * Header flag indicating that a packet is fragmented
  92. *
  93. * If this flag is set, the receiver knows to expect more than one fragment.
  94. * See Packet::Fragment for details.
  95. */
  96. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  97. /**
  98. * Verb flag indicating payload is compressed with LZ4
  99. */
  100. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  101. /**
  102. * Rounds used for Salsa20 encryption in ZT
  103. *
  104. * Discussion:
  105. *
  106. * DJB (Salsa20's designer) designed Salsa20 with a significant margin of 20
  107. * rounds, but has said repeatedly that 12 is likely sufficient. So far (as of
  108. * July 2015) there are no published attacks against 12 rounds, let alone 20.
  109. *
  110. * In cryptography, a "break" means something different from what it means in
  111. * common discussion. If a cipher is 256 bits strong and someone finds a way
  112. * to reduce key search to 254 bits, this constitues a "break" in the academic
  113. * literature. 254 bits is still far beyond what can be leveraged to accomplish
  114. * a "break" as most people would understand it -- the actual decryption and
  115. * reading of traffic.
  116. *
  117. * Nevertheless, "attacks only get better" as cryptographers like to say. As
  118. * a result, they recommend not using anything that's shown any weakness even
  119. * if that weakness is so far only meaningful to academics. It may be a sign
  120. * of a deeper problem.
  121. *
  122. * So why choose a lower round count?
  123. *
  124. * Turns out the speed difference is nontrivial. On a Macbook Pro (Core i3) 20
  125. * rounds of SSE-optimized Salsa20 achieves ~508mb/sec/core, while 12 rounds
  126. * hits ~832mb/sec/core. ZeroTier is designed for multiple objectives:
  127. * security, simplicity, and performance. In this case a deference was made
  128. * for performance.
  129. *
  130. * Meta discussion:
  131. *
  132. * The cipher is not the thing you should be paranoid about.
  133. *
  134. * I'll qualify that. If the cipher is known to be weak, like RC4, or has a
  135. * key size that is too small, like DES, then yes you should worry about
  136. * the cipher.
  137. *
  138. * But if the cipher is strong and your adversary is anyone other than the
  139. * intelligence apparatus of a major superpower, you are fine in that
  140. * department.
  141. *
  142. * Go ahead. Search for the last ten vulnerabilities discovered in SSL. Not
  143. * a single one involved the breaking of a cipher. Now broaden your search.
  144. * Look for issues with SSH, IPSec, etc. The only cipher-related issues you
  145. * will find might involve the use of RC4 or MD5, algorithms with known
  146. * issues or small key/digest sizes. But even weak ciphers are difficult to
  147. * exploit in the real world -- you usually need a lot of data and a lot of
  148. * compute time. No, virtually EVERY security vulnerability you will find
  149. * involves a problem with the IMPLEMENTATION not with the cipher.
  150. *
  151. * A flaw in ZeroTier's protocol or code is incredibly, unbelievably
  152. * more likely than a flaw in Salsa20 or any other cipher or cryptographic
  153. * primitive it uses. We're talking odds of dying in a car wreck vs. odds of
  154. * being personally impacted on the head by a meteorite. Nobody without a
  155. * billion dollar budget is going to break into your network by actually
  156. * cracking Salsa20/12 (or even /8) in the field.
  157. *
  158. * So stop worrying about the cipher unless you are, say, the Kremlin and your
  159. * adversary is the NSA and the GCHQ. In that case... well that's above my
  160. * pay grade. I'll just say defense in depth.
  161. */
  162. #define ZT_PROTO_SALSA20_ROUNDS 12
  163. /**
  164. * PUSH_DIRECT_PATHS flag: forget path
  165. */
  166. #define ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH 0x01
  167. /**
  168. * PUSH_DIRECT_PATHS flag: cluster redirect
  169. */
  170. #define ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT 0x02
  171. // Field indexes in packet header
  172. #define ZT_PACKET_IDX_IV 0
  173. #define ZT_PACKET_IDX_DEST 8
  174. #define ZT_PACKET_IDX_SOURCE 13
  175. #define ZT_PACKET_IDX_FLAGS 18
  176. #define ZT_PACKET_IDX_MAC 19
  177. #define ZT_PACKET_IDX_VERB 27
  178. #define ZT_PACKET_IDX_PAYLOAD 28
  179. /**
  180. * Packet buffer size (can be changed)
  181. *
  182. * The current value is big enough for ZT_MAX_PACKET_FRAGMENTS, the pragmatic
  183. * packet fragment limit, times the default UDP MTU. Most packets won't be
  184. * this big.
  185. */
  186. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  187. /**
  188. * Minimum viable packet length (a.k.a. header length)
  189. */
  190. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  191. // Indexes of fields in fragment header
  192. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  193. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  194. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  195. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  196. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  197. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  198. /**
  199. * Magic number found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR
  200. */
  201. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  202. /**
  203. * Minimum viable fragment length
  204. */
  205. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  206. // Field incides for parsing verbs -------------------------------------------
  207. // Some verbs have variable-length fields. Those aren't fully defined here
  208. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  209. // See their respective handler functions.
  210. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  211. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  212. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  213. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  214. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  215. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  216. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  217. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  218. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  219. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  220. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  221. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  222. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  223. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  224. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  225. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  226. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  227. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  228. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  229. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  230. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  231. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  232. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  233. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  234. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  235. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  236. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  237. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  238. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  239. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  240. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  241. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  242. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  243. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  244. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  245. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  246. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  247. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  248. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  249. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  250. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  251. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  252. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  253. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  254. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  255. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  256. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  257. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  258. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  259. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  260. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  261. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  262. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  263. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  264. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  265. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  266. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  267. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  268. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  269. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  270. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  271. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  272. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  273. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  274. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  275. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  276. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  277. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  278. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  279. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  280. // ---------------------------------------------------------------------------
  281. namespace ZeroTier {
  282. /**
  283. * ZeroTier packet
  284. *
  285. * Packet format:
  286. * <[8] 64-bit random packet ID and crypto initialization vector>
  287. * <[5] destination ZT address>
  288. * <[5] source ZT address>
  289. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  290. * <[8] 64-bit MAC>
  291. * [... -- begin encryption envelope -- ...]
  292. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  293. * [... verb-specific payload ...]
  294. *
  295. * Packets smaller than 28 bytes are invalid and silently discarded.
  296. *
  297. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  298. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  299. * and H is hop count.
  300. *
  301. * The three-bit hop count is the only part of a packet that is mutable in
  302. * transit without invalidating the MAC. All other bits in the packet are
  303. * immutable. This is because intermediate nodes can increment the hop
  304. * count up to 7 (protocol max).
  305. *
  306. * A hop count of 7 also indicates that receiving peers should not attempt
  307. * to learn direct paths from this packet. (Right now direct paths are only
  308. * learned from direct packets anyway.)
  309. *
  310. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  311. *
  312. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  313. * sent in the clear, as it's the "here is my public key" message.
  314. */
  315. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  316. {
  317. public:
  318. /**
  319. * A packet fragment
  320. *
  321. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  322. * is sent with its normal header with the fragmented flag set. Remaining
  323. * fragments are sent this way.
  324. *
  325. * The fragmented bit indicates that there is at least one fragment. Fragments
  326. * themselves contain the total, so the receiver must "learn" this from the
  327. * first fragment it receives.
  328. *
  329. * Fragments are sent with the following format:
  330. * <[8] packet ID of packet whose fragment this belongs to>
  331. * <[5] destination ZT address>
  332. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  333. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  334. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  335. * <[...] fragment data>
  336. *
  337. * The protocol supports a maximum of 16 fragments. If a fragment is received
  338. * before its main packet header, it should be cached for a brief period of
  339. * time to see if its parent arrives. Loss of any fragment constitutes packet
  340. * loss; there is no retransmission mechanism. The receiver must wait for full
  341. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  342. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  343. */
  344. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  345. {
  346. public:
  347. Fragment() :
  348. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  349. {
  350. }
  351. template<unsigned int C2>
  352. Fragment(const Buffer<C2> &b)
  353. throw(std::out_of_range) :
  354. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  355. {
  356. }
  357. Fragment(const void *data,unsigned int len) :
  358. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  359. {
  360. }
  361. /**
  362. * Initialize from a packet
  363. *
  364. * @param p Original assembled packet
  365. * @param fragStart Start of fragment (raw index in packet data)
  366. * @param fragLen Length of fragment in bytes
  367. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  368. * @param fragTotal Total number of fragments (including 0)
  369. * @throws std::out_of_range Packet size would exceed buffer
  370. */
  371. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  372. throw(std::out_of_range)
  373. {
  374. init(p,fragStart,fragLen,fragNo,fragTotal);
  375. }
  376. /**
  377. * Initialize from a packet
  378. *
  379. * @param p Original assembled packet
  380. * @param fragStart Start of fragment (raw index in packet data)
  381. * @param fragLen Length of fragment in bytes
  382. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  383. * @param fragTotal Total number of fragments (including 0)
  384. * @throws std::out_of_range Packet size would exceed buffer
  385. */
  386. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  387. throw(std::out_of_range)
  388. {
  389. if ((fragStart + fragLen) > p.size())
  390. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  391. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  392. // NOTE: this copies both the IV/packet ID and the destination address.
  393. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  394. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  395. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  396. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  397. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  398. }
  399. /**
  400. * Get this fragment's destination
  401. *
  402. * @return Destination ZT address
  403. */
  404. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  405. /**
  406. * @return True if fragment is of a valid length
  407. */
  408. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  409. /**
  410. * @return ID of packet this is a fragment of
  411. */
  412. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  413. /**
  414. * @return Total number of fragments in packet
  415. */
  416. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  417. /**
  418. * @return Fragment number of this fragment
  419. */
  420. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  421. /**
  422. * @return Fragment ZT hop count
  423. */
  424. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  425. /**
  426. * Increment this packet's hop count
  427. */
  428. inline void incrementHops()
  429. {
  430. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  431. }
  432. /**
  433. * @return Length of payload in bytes
  434. */
  435. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  436. /**
  437. * @return Raw packet payload
  438. */
  439. inline const unsigned char *payload() const
  440. {
  441. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  442. }
  443. };
  444. /**
  445. * ZeroTier protocol verbs
  446. */
  447. enum Verb /* Max value: 32 (5 bits) */
  448. {
  449. /**
  450. * No operation (ignored, no reply)
  451. */
  452. VERB_NOP = 0,
  453. /**
  454. * Announcement of a node's existence:
  455. * <[1] protocol version>
  456. * <[1] software major version>
  457. * <[1] software minor version>
  458. * <[2] software revision>
  459. * <[8] timestamp (ms since epoch)>
  460. * <[...] binary serialized identity (see Identity)>
  461. * <[1] destination address type>
  462. * [<[...] destination address>]
  463. * <[8] 64-bit world ID of current world>
  464. * <[8] 64-bit timestamp of current world>
  465. *
  466. * This is the only message that ever must be sent in the clear, since it
  467. * is used to push an identity to a new peer.
  468. *
  469. * The destination address is the wire address to which this packet is
  470. * being sent, and in OK is *also* the destination address of the OK
  471. * packet. This can be used by the receiver to detect NAT, learn its real
  472. * external address if behind NAT, and detect changes to its external
  473. * address that require re-establishing connectivity.
  474. *
  475. * Destination address types and formats (not all of these are used now):
  476. * 0x00 - None -- no destination address data present
  477. * 0x01 - Ethernet address -- format: <[6] Ethernet MAC>
  478. * 0x04 - 6-byte IPv4 UDP address/port -- format: <[4] IP>, <[2] port>
  479. * 0x06 - 18-byte IPv6 UDP address/port -- format: <[16] IP>, <[2] port>
  480. *
  481. * OK payload:
  482. * <[8] timestamp (echoed from original HELLO)>
  483. * <[1] protocol version (of responder)>
  484. * <[1] software major version (of responder)>
  485. * <[1] software minor version (of responder)>
  486. * <[2] software revision (of responder)>
  487. * <[1] destination address type (for this OK, not copied from HELLO)>
  488. * [<[...] destination address>]
  489. * <[2] 16-bit length of world update or 0 if none>
  490. * [[...] world update]
  491. *
  492. * ERROR has no payload.
  493. */
  494. VERB_HELLO = 1,
  495. /**
  496. * Error response:
  497. * <[1] in-re verb>
  498. * <[8] in-re packet ID>
  499. * <[1] error code>
  500. * <[...] error-dependent payload>
  501. */
  502. VERB_ERROR = 2,
  503. /**
  504. * Success response:
  505. * <[1] in-re verb>
  506. * <[8] in-re packet ID>
  507. * <[...] request-specific payload>
  508. */
  509. VERB_OK = 3,
  510. /**
  511. * Query an identity by address:
  512. * <[5] address to look up>
  513. *
  514. * OK response payload:
  515. * <[...] binary serialized identity>
  516. *
  517. * If querying a cluster, duplicate OK responses may occasionally occur.
  518. * These should be discarded.
  519. *
  520. * If the address is not found, no response is generated. WHOIS requests
  521. * will time out much like ARP requests and similar do in L2.
  522. */
  523. VERB_WHOIS = 4,
  524. /**
  525. * Meet another node at a given protocol address:
  526. * <[1] flags (unused, currently 0)>
  527. * <[5] ZeroTier address of peer that might be found at this address>
  528. * <[2] 16-bit protocol address port>
  529. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  530. * <[...] protocol address (network byte order)>
  531. *
  532. * This is sent by a relaying node to initiate NAT traversal between two
  533. * peers that are communicating by way of indirect relay. The relay will
  534. * send this to both peers at the same time on a periodic basis, telling
  535. * each where it might find the other on the network.
  536. *
  537. * Upon receipt a peer sends HELLO to establish a direct link.
  538. *
  539. * Nodes should implement rate control, limiting the rate at which they
  540. * respond to these packets to prevent their use in DDOS attacks. Nodes
  541. * may also ignore these messages if a peer is not known or is not being
  542. * actively communicated with.
  543. *
  544. * Unfortunately the physical address format in this message pre-dates
  545. * InetAddress's serialization format. :( ZeroTier is four years old and
  546. * yes we've accumulated a tiny bit of cruft here and there.
  547. *
  548. * No OK or ERROR is generated.
  549. */
  550. VERB_RENDEZVOUS = 5,
  551. /**
  552. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  553. * <[8] 64-bit network ID>
  554. * <[2] 16-bit ethertype>
  555. * <[...] ethernet payload>
  556. *
  557. * MAC addresses are derived from the packet's source and destination
  558. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  559. * Ethernet framing and other optional flags and features when they
  560. * are not necessary.
  561. *
  562. * ERROR may be generated if a membership certificate is needed for a
  563. * closed network. Payload will be network ID.
  564. */
  565. VERB_FRAME = 6,
  566. /**
  567. * Full Ethernet frame with MAC addressing and optional fields:
  568. * <[8] 64-bit network ID>
  569. * <[1] flags>
  570. * [<[...] certificate of network membership>]
  571. * <[6] destination MAC or all zero for destination node>
  572. * <[6] source MAC or all zero for node of origin>
  573. * <[2] 16-bit ethertype>
  574. * <[...] ethernet payload>
  575. *
  576. * Flags:
  577. * 0x01 - Certificate of network membership is attached
  578. *
  579. * An extended frame carries full MAC addressing, making them a
  580. * superset of VERB_FRAME. They're used for bridging or when we
  581. * want to attach a certificate since FRAME does not support that.
  582. *
  583. * Multicast frames may not be sent as EXT_FRAME.
  584. *
  585. * ERROR may be generated if a membership certificate is needed for a
  586. * closed network. Payload will be network ID.
  587. */
  588. VERB_EXT_FRAME = 7,
  589. /**
  590. * ECHO request (a.k.a. ping):
  591. * <[...] arbitrary payload>
  592. *
  593. * This generates OK with a copy of the transmitted payload. No ERROR
  594. * is generated. Response to ECHO requests is optional and ECHO may be
  595. * ignored if a node detects a possible flood.
  596. */
  597. VERB_ECHO = 8,
  598. /**
  599. * Announce interest in multicast group(s):
  600. * <[8] 64-bit network ID>
  601. * <[6] multicast Ethernet address>
  602. * <[4] multicast additional distinguishing information (ADI)>
  603. * [... additional tuples of network/address/adi ...]
  604. *
  605. * LIKEs may be sent to any peer, though a good implementation should
  606. * restrict them to peers on the same network they're for and to network
  607. * controllers and root servers. In the current network, root servers
  608. * will provide the service of final multicast cache.
  609. *
  610. * It is recommended that NETWORK_MEMBERSHIP_CERTIFICATE pushes be sent
  611. * along with MULTICAST_LIKE when pushing LIKEs to peers that do not
  612. * share a network membership (such as root servers), since this can be
  613. * used to authenticate GATHER requests and limit responses to peers
  614. * authorized to talk on a network. (Should be an optional field here,
  615. * but saving one or two packets every five minutes is not worth an
  616. * ugly hack or protocol rev.)
  617. *
  618. * OK/ERROR are not generated.
  619. */
  620. VERB_MULTICAST_LIKE = 9,
  621. /**
  622. * Network member certificate replication/push:
  623. * <[...] serialized certificate of membership>
  624. * [ ... additional certificates may follow ...]
  625. *
  626. * This is sent in response to ERROR_NEED_MEMBERSHIP_CERTIFICATE and may
  627. * be pushed at any other time to keep exchanged certificates up to date.
  628. *
  629. * OK/ERROR are not generated.
  630. */
  631. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  632. /**
  633. * Network configuration request:
  634. * <[8] 64-bit network ID>
  635. * <[2] 16-bit length of request meta-data dictionary>
  636. * <[...] string-serialized request meta-data>
  637. * [<[8] 64-bit revision of netconf we currently have>]
  638. *
  639. * This message requests network configuration from a node capable of
  640. * providing it. If the optional revision is included, a response is
  641. * only generated if there is a newer network configuration available.
  642. *
  643. * OK response payload:
  644. * <[8] 64-bit network ID>
  645. * <[2] 16-bit length of network configuration dictionary>
  646. * <[...] network configuration dictionary>
  647. *
  648. * OK returns a Dictionary (string serialized) containing the network's
  649. * configuration and IP address assignment information for the querying
  650. * node. It also contains a membership certificate that the querying
  651. * node can push to other peers to demonstrate its right to speak on
  652. * a given network.
  653. *
  654. * When a new network configuration is received, another config request
  655. * should be sent with the new netconf's revision. This confirms receipt
  656. * and also causes any subsequent changes to rapidly propagate as this
  657. * cycle will repeat until there are no changes. This is optional but
  658. * recommended behavior.
  659. *
  660. * ERROR response payload:
  661. * <[8] 64-bit network ID>
  662. *
  663. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  664. * and OBJ_NOT_FOUND if the queried network ID was not found.
  665. */
  666. VERB_NETWORK_CONFIG_REQUEST = 11,
  667. /**
  668. * Network configuration refresh request:
  669. * <[...] array of 64-bit network IDs>
  670. *
  671. * This can be sent by the network controller to inform a node that it
  672. * should now make a NETWORK_CONFIG_REQUEST.
  673. *
  674. * It does not generate an OK or ERROR message, and is treated only as
  675. * a hint to refresh now.
  676. */
  677. VERB_NETWORK_CONFIG_REFRESH = 12,
  678. /**
  679. * Request endpoints for multicast distribution:
  680. * <[8] 64-bit network ID>
  681. * <[1] flags>
  682. * <[6] MAC address of multicast group being queried>
  683. * <[4] 32-bit ADI for multicast group being queried>
  684. * <[4] 32-bit requested max number of multicast peers>
  685. * [<[...] network certificate of membership>]
  686. *
  687. * Flags:
  688. * 0x01 - Network certificate of membership is attached
  689. *
  690. * This message asks a peer for additional known endpoints that have
  691. * LIKEd a given multicast group. It's sent when the sender wishes
  692. * to send multicast but does not have the desired number of recipient
  693. * peers.
  694. *
  695. * More than one OK response can occur if the response is broken up across
  696. * multiple packets or if querying a clustered node.
  697. *
  698. * OK response payload:
  699. * <[8] 64-bit network ID>
  700. * <[6] MAC address of multicast group being queried>
  701. * <[4] 32-bit ADI for multicast group being queried>
  702. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  703. * <[4] 32-bit total number of known members in this multicast group>
  704. * <[2] 16-bit number of members enumerated in this packet>
  705. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  706. *
  707. * ERROR is not generated; queries that return no response are dropped.
  708. */
  709. VERB_MULTICAST_GATHER = 13,
  710. /**
  711. * Multicast frame:
  712. * <[8] 64-bit network ID>
  713. * <[1] flags>
  714. * [<[...] network certificate of membership>]
  715. * [<[4] 32-bit implicit gather limit>]
  716. * [<[6] source MAC>]
  717. * <[6] destination MAC (multicast address)>
  718. * <[4] 32-bit multicast ADI (multicast address extension)>
  719. * <[2] 16-bit ethertype>
  720. * <[...] ethernet payload>
  721. *
  722. * Flags:
  723. * 0x01 - Network certificate of membership is attached
  724. * 0x02 - Implicit gather limit field is present
  725. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  726. *
  727. * OK and ERROR responses are optional. OK may be generated if there are
  728. * implicit gather results or if the recipient wants to send its own
  729. * updated certificate of network membership to the sender. ERROR may be
  730. * generated if a certificate is needed or if multicasts to this group
  731. * are no longer wanted (multicast unsubscribe).
  732. *
  733. * OK response payload:
  734. * <[8] 64-bit network ID>
  735. * <[6] MAC address of multicast group>
  736. * <[4] 32-bit ADI for multicast group>
  737. * <[1] flags>
  738. * [<[...] network certficate of membership>]
  739. * [<[...] implicit gather results if flag 0x01 is set>]
  740. *
  741. * OK flags (same bits as request flags):
  742. * 0x01 - OK includes certificate of network membership
  743. * 0x02 - OK includes implicit gather results
  744. *
  745. * ERROR response payload:
  746. * <[8] 64-bit network ID>
  747. * <[6] multicast group MAC>
  748. * <[4] 32-bit multicast group ADI>
  749. */
  750. VERB_MULTICAST_FRAME = 14,
  751. /**
  752. * Push of potential endpoints for direct communication:
  753. * <[2] 16-bit number of paths>
  754. * <[...] paths>
  755. *
  756. * Path record format:
  757. * <[1] 8-bit path flags>
  758. * <[2] length of extended path characteristics or 0 for none>
  759. * <[...] extended path characteristics>
  760. * <[1] address type>
  761. * <[1] address length in bytes>
  762. * <[...] address>
  763. *
  764. * Path record flags:
  765. * 0x01 - Forget this path if currently known (not implemented yet)
  766. * 0x02 - Cluster redirect -- use this in preference to others
  767. *
  768. * The receiver may, upon receiving a push, attempt to establish a
  769. * direct link to one or more of the indicated addresses. It is the
  770. * responsibility of the sender to limit which peers it pushes direct
  771. * paths to to those with whom it has a trust relationship. The receiver
  772. * must obey any restrictions provided such as exclusivity or blacklists.
  773. * OK responses to this message are optional.
  774. *
  775. * Note that a direct path push does not imply that learned paths can't
  776. * be used unless they are blacklisted explicitly or unless flag 0x01
  777. * is set.
  778. *
  779. * Only a subset of this functionality is currently implemented: basic
  780. * path pushing and learning. Blacklisting and trust are not fully
  781. * implemented yet (encryption is still always used).
  782. *
  783. * OK and ERROR are not generated.
  784. */
  785. VERB_PUSH_DIRECT_PATHS = 16,
  786. /**
  787. * Source-routed circuit test message:
  788. * <[5] address of originator of circuit test>
  789. * <[2] 16-bit flags>
  790. * <[8] 64-bit timestamp>
  791. * <[8] 64-bit test ID (arbitrary, set by tester)>
  792. * <[2] 16-bit originator credential length (includes type)>
  793. * [[1] originator credential type (for authorizing test)]
  794. * [[...] originator credential]
  795. * <[2] 16-bit length of additional fields>
  796. * [[...] additional fields]
  797. * [ ... end of signed portion of request ... ]
  798. * <[2] 16-bit length of signature of request>
  799. * <[...] signature of request by originator>
  800. * <[2] 16-bit previous hop credential length (including type)>
  801. * [[1] previous hop credential type]
  802. * [[...] previous hop credential]
  803. * <[...] next hop(s) in path>
  804. *
  805. * Flags:
  806. * 0x01 - Report back to originator at middle hops
  807. * 0x02 - Report back to originator at last hop
  808. *
  809. * Originator credential types:
  810. * 0x01 - 64-bit network ID for which originator is controller
  811. *
  812. * Previous hop credential types:
  813. * 0x01 - Certificate of network membership
  814. *
  815. * Path record format:
  816. * <[1] 8-bit flags (unused, must be zero)>
  817. * <[1] 8-bit breadth (number of next hops)>
  818. * <[...] one or more ZeroTier addresses of next hops>
  819. *
  820. * The circuit test allows a device to send a message that will traverse
  821. * the network along a specified path, with each hop optionally reporting
  822. * back to the tester via VERB_CIRCUIT_TEST_REPORT.
  823. *
  824. * Each circuit test packet includes a digital signature by the originator
  825. * of the request, as well as a credential by which that originator claims
  826. * authorization to perform the test. Currently this signature is ed25519,
  827. * but in the future flags might be used to indicate an alternative
  828. * algorithm. For example, the originator might be a network controller.
  829. * In this case the test might be authorized if the recipient is a member
  830. * of a network controlled by it, and if the previous hop(s) are also
  831. * members. Each hop may include its certificate of network membership.
  832. *
  833. * Circuit test paths consist of a series of records. When a node receives
  834. * an authorized circuit test, it:
  835. *
  836. * (1) Reports back to circuit tester as flags indicate
  837. * (2) Reads and removes the next hop from the packet's path
  838. * (3) Sends the packet along to next hop(s), if any.
  839. *
  840. * It is perfectly legal for a path to contain the same hop more than
  841. * once. In fact, this can be a very useful test to determine if a hop
  842. * can be reached bidirectionally and if so what that connectivity looks
  843. * like.
  844. *
  845. * The breadth field in source-routed path records allows a hop to forward
  846. * to more than one recipient, allowing the tester to specify different
  847. * forms of graph traversal in a test.
  848. *
  849. * There is no hard limit to the number of hops in a test, but it is
  850. * practically limited by the maximum size of a (possibly fragmented)
  851. * ZeroTier packet.
  852. *
  853. * Support for circuit tests is optional. If they are not supported, the
  854. * node should respond with an UNSUPPORTED_OPERATION error. If a circuit
  855. * test request is not authorized, it may be ignored or reported as
  856. * an INVALID_REQUEST. No OK messages are generated, but TEST_REPORT
  857. * messages may be sent (see below).
  858. *
  859. * ERROR packet format:
  860. * <[8] 64-bit timestamp (echoed from original>
  861. * <[8] 64-bit test ID (echoed from original)>
  862. */
  863. VERB_CIRCUIT_TEST = 17,
  864. /**
  865. * Circuit test hop report:
  866. * <[8] 64-bit timestamp (from original test)>
  867. * <[8] 64-bit test ID (from original test)>
  868. * <[8] 64-bit reserved field (set to 0, currently unused)>
  869. * <[1] 8-bit vendor ID (set to 0, currently unused)>
  870. * <[1] 8-bit reporter protocol version>
  871. * <[1] 8-bit reporter major version>
  872. * <[1] 8-bit reporter minor version>
  873. * <[2] 16-bit reporter revision>
  874. * <[2] 16-bit reporter OS/platform>
  875. * <[2] 16-bit reporter architecture>
  876. * <[2] 16-bit error code (set to 0, currently unused)>
  877. * <[8] 64-bit report flags (set to 0, currently unused)>
  878. * <[8] 64-bit source packet ID>
  879. * <[5] upstream ZeroTier address from which test was received>
  880. * <[1] 8-bit source packet hop count (ZeroTier hop count)>
  881. * <[...] local wire address on which packet was received>
  882. * <[...] remote wire address from which packet was received>
  883. * <[2] 16-bit length of additional fields>
  884. * <[...] additional fields>
  885. * <[1] 8-bit number of next hops (breadth)>
  886. * <[...] next hop information>
  887. *
  888. * Next hop information record format:
  889. * <[5] ZeroTier address of next hop>
  890. * <[...] current best direct path address, if any, 0 if none>
  891. *
  892. * Circuit test reports can be sent by hops in a circuit test to report
  893. * back results. They should include information about the sender as well
  894. * as about the paths to which next hops are being sent.
  895. *
  896. * If a test report is received and no circuit test was sent, it should be
  897. * ignored. This message generates no OK or ERROR response.
  898. */
  899. VERB_CIRCUIT_TEST_REPORT = 18,
  900. /**
  901. * Request proof of work:
  902. * <[1] 8-bit proof of work type>
  903. * <[1] 8-bit proof of work difficulty>
  904. * <[2] 16-bit length of proof of work challenge>
  905. * <[...] proof of work challenge>
  906. *
  907. * This requests that a peer perform a proof of work calucation. It can be
  908. * sent by highly trusted peers (e.g. root servers, network controllers)
  909. * under suspected denial of service conditions in an attempt to filter
  910. * out "non-serious" peers and remain responsive to those proving their
  911. * intent to actually communicate.
  912. *
  913. * If the peer obliges to perform the work, it does so and responds with
  914. * an OK containing the result. Otherwise it may ignore the message or
  915. * response with an ERROR_INVALID_REQUEST or ERROR_UNSUPPORTED_OPERATION.
  916. *
  917. * Proof of work type IDs:
  918. * 0x01 - Salsa20/12+SHA512 hashcash function
  919. *
  920. * Salsa20/12+SHA512 is based on the following composite hash function:
  921. *
  922. * (1) Compute SHA512(candidate)
  923. * (2) Use the first 256 bits of the result of #1 as a key to encrypt
  924. * 131072 zero bytes with Salsa20/12 (with a zero IV).
  925. * (3) Compute SHA512(the result of step #2)
  926. * (4) Accept this candiate if the first [difficulty] bits of the result
  927. * from step #3 are zero. Otherwise generate a new candidate and try
  928. * again.
  929. *
  930. * This is performed repeatedly on candidates generated by appending the
  931. * supplied challenge to an arbitrary nonce until a valid candidate
  932. * is found. This chosen prepended nonce is then returned as the result
  933. * in OK.
  934. *
  935. * OK payload:
  936. * <[2] 16-bit length of result>
  937. * <[...] computed proof of work>
  938. *
  939. * ERROR has no payload.
  940. */
  941. VERB_REQUEST_PROOF_OF_WORK = 19
  942. };
  943. /**
  944. * Error codes for VERB_ERROR
  945. */
  946. enum ErrorCode
  947. {
  948. /* No error, not actually used in transit */
  949. ERROR_NONE = 0,
  950. /* Invalid request */
  951. ERROR_INVALID_REQUEST = 1,
  952. /* Bad/unsupported protocol version */
  953. ERROR_BAD_PROTOCOL_VERSION = 2,
  954. /* Unknown object queried */
  955. ERROR_OBJ_NOT_FOUND = 3,
  956. /* HELLO pushed an identity whose address is already claimed */
  957. ERROR_IDENTITY_COLLISION = 4,
  958. /* Verb or use case not supported/enabled by this node */
  959. ERROR_UNSUPPORTED_OPERATION = 5,
  960. /* Message to private network rejected -- no unexpired certificate on file */
  961. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  962. /* Tried to join network, but you're not a member */
  963. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  964. /* Multicasts to this group are not wanted */
  965. ERROR_UNWANTED_MULTICAST = 8
  966. };
  967. //#ifdef ZT_TRACE
  968. static const char *verbString(Verb v)
  969. throw();
  970. static const char *errorString(ErrorCode e)
  971. throw();
  972. //#endif
  973. template<unsigned int C2>
  974. Packet(const Buffer<C2> &b) :
  975. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  976. {
  977. }
  978. Packet(const void *data,unsigned int len) :
  979. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  980. {
  981. }
  982. /**
  983. * Construct a new empty packet with a unique random packet ID
  984. *
  985. * Flags and hops will be zero. Other fields and data region are undefined.
  986. * Use the header access methods (setDestination() and friends) to fill out
  987. * the header. Payload should be appended; initial size is header size.
  988. */
  989. Packet() :
  990. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  991. {
  992. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  993. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  994. }
  995. /**
  996. * Make a copy of a packet with a new initialization vector and destination address
  997. *
  998. * This can be used to take one draft prototype packet and quickly make copies to
  999. * encrypt for different destinations.
  1000. *
  1001. * @param prototype Prototype packet
  1002. * @param dest Destination ZeroTier address for new packet
  1003. */
  1004. Packet(const Packet &prototype,const Address &dest) :
  1005. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  1006. {
  1007. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1008. setDestination(dest);
  1009. }
  1010. /**
  1011. * Construct a new empty packet with a unique random packet ID
  1012. *
  1013. * @param dest Destination ZT address
  1014. * @param source Source ZT address
  1015. * @param v Verb
  1016. */
  1017. Packet(const Address &dest,const Address &source,const Verb v) :
  1018. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  1019. {
  1020. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1021. setDestination(dest);
  1022. setSource(source);
  1023. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  1024. setVerb(v);
  1025. }
  1026. /**
  1027. * Reset this packet structure for reuse in place
  1028. *
  1029. * @param dest Destination ZT address
  1030. * @param source Source ZT address
  1031. * @param v Verb
  1032. */
  1033. inline void reset(const Address &dest,const Address &source,const Verb v)
  1034. {
  1035. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  1036. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1037. setDestination(dest);
  1038. setSource(source);
  1039. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  1040. setVerb(v);
  1041. }
  1042. /**
  1043. * Generate a new IV / packet ID in place
  1044. *
  1045. * This can be used to re-use a packet buffer multiple times to send
  1046. * technically different but otherwise identical copies of the same
  1047. * packet.
  1048. */
  1049. inline void newInitializationVector() { Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8); }
  1050. /**
  1051. * Set this packet's destination
  1052. *
  1053. * @param dest ZeroTier address of destination
  1054. */
  1055. inline void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1056. /**
  1057. * Set this packet's source
  1058. *
  1059. * @param source ZeroTier address of source
  1060. */
  1061. inline void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1062. /**
  1063. * Get this packet's destination
  1064. *
  1065. * @return Destination ZT address
  1066. */
  1067. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1068. /**
  1069. * Get this packet's source
  1070. *
  1071. * @return Source ZT address
  1072. */
  1073. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1074. /**
  1075. * @return True if packet is of valid length
  1076. */
  1077. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  1078. /**
  1079. * @return True if packet is fragmented (expect fragments)
  1080. */
  1081. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  1082. /**
  1083. * Set this packet's fragmented flag
  1084. *
  1085. * @param f Fragmented flag value
  1086. */
  1087. inline void setFragmented(bool f)
  1088. {
  1089. if (f)
  1090. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  1091. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  1092. }
  1093. /**
  1094. * @return True if compressed (result only valid if unencrypted)
  1095. */
  1096. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  1097. /**
  1098. * @return ZeroTier forwarding hops (0 to 7)
  1099. */
  1100. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  1101. /**
  1102. * Increment this packet's hop count
  1103. */
  1104. inline void incrementHops()
  1105. {
  1106. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1107. b = (b & 0xf8) | ((b + 1) & 0x07);
  1108. }
  1109. /**
  1110. * @return Cipher suite selector: 0 - 7 (see #defines)
  1111. */
  1112. inline unsigned int cipher() const
  1113. {
  1114. // Note: this uses the new cipher spec field, which is incompatible with <1.0.0 peers
  1115. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  1116. }
  1117. /**
  1118. * Set this packet's cipher suite
  1119. */
  1120. inline void setCipher(unsigned int c)
  1121. {
  1122. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1123. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  1124. // DEPRECATED "encrypted" flag -- used by pre-1.0.3 peers
  1125. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1126. b |= ZT_PROTO_FLAG_ENCRYPTED;
  1127. else b &= (~ZT_PROTO_FLAG_ENCRYPTED);
  1128. }
  1129. /**
  1130. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  1131. *
  1132. * @return Packet ID
  1133. */
  1134. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  1135. /**
  1136. * Set packet verb
  1137. *
  1138. * This also has the side-effect of clearing any verb flags, such as
  1139. * compressed, and so must only be done during packet composition.
  1140. *
  1141. * @param v New packet verb
  1142. */
  1143. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  1144. /**
  1145. * @return Packet verb (not including flag bits)
  1146. */
  1147. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  1148. /**
  1149. * @return Length of packet payload
  1150. */
  1151. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1152. /**
  1153. * @return Raw packet payload
  1154. */
  1155. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1156. /**
  1157. * Armor packet for transport
  1158. *
  1159. * @param key 32-byte key
  1160. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1161. */
  1162. void armor(const void *key,bool encryptPayload);
  1163. /**
  1164. * Verify and (if encrypted) decrypt packet
  1165. *
  1166. * @param key 32-byte key
  1167. * @return False if packet is invalid or failed MAC authenticity check
  1168. */
  1169. bool dearmor(const void *key);
  1170. /**
  1171. * Attempt to compress payload if not already (must be unencrypted)
  1172. *
  1173. * This requires that the payload at least contain the verb byte already
  1174. * set. The compressed flag in the verb is set if compression successfully
  1175. * results in a size reduction. If no size reduction occurs, compression
  1176. * is not done and the flag is left cleared.
  1177. *
  1178. * @return True if compression occurred
  1179. */
  1180. bool compress();
  1181. /**
  1182. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1183. *
  1184. * If payload is compressed, it is decompressed and the compressed verb
  1185. * flag is cleared. Otherwise nothing is done and true is returned.
  1186. *
  1187. * @return True if data is now decompressed and valid, false on error
  1188. */
  1189. bool uncompress();
  1190. private:
  1191. static const unsigned char ZERO_KEY[32];
  1192. /**
  1193. * Deterministically mangle a 256-bit crypto key based on packet
  1194. *
  1195. * This uses extra data from the packet to mangle the secret, giving us an
  1196. * effective IV that is somewhat more than 64 bits. This is "free" for
  1197. * Salsa20 since it has negligible key setup time so using a different
  1198. * key each time is fine.
  1199. *
  1200. * @param in Input key (32 bytes)
  1201. * @param out Output buffer (32 bytes)
  1202. */
  1203. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1204. {
  1205. const unsigned char *d = (const unsigned char *)data();
  1206. // IV and source/destination addresses. Using the addresses divides the
  1207. // key space into two halves-- A->B and B->A (since order will change).
  1208. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1209. out[i] = in[i] ^ d[i];
  1210. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1211. // nodes. It's one of the only parts of a packet modifiable by people
  1212. // without the key.
  1213. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1214. // Raw packet size in bytes -- thus each packet size defines a new
  1215. // key space.
  1216. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1217. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1218. // Rest of raw key is used unchanged
  1219. for(unsigned int i=21;i<32;++i)
  1220. out[i] = in[i];
  1221. }
  1222. };
  1223. } // namespace ZeroTier
  1224. #endif