Packet.hpp 50 KB

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