Packet.hpp 51 KB

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