Packet.hpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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 "Address.hpp"
  35. #include "Poly1305.hpp"
  36. #include "Salsa20.hpp"
  37. #include "Utils.hpp"
  38. #include "Constants.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 ... 0.9.2
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  58. /**
  59. * Minimum supported protocol version
  60. */
  61. #define ZT_PROTO_VERSION_MIN 4
  62. /**
  63. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  64. *
  65. * This is not necessarily the maximum hop counter after which
  66. * relaying is no longer performed.
  67. */
  68. #define ZT_PROTO_MAX_HOPS 7
  69. /**
  70. * Cipher suite: Curve25519/Poly1305/Salsa20/12 without payload encryption
  71. *
  72. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  73. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  74. * but the payload is not encrypted. This is currently only used to send
  75. * HELLO since that's the public key specification packet and must be
  76. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  77. * curve Diffie-Hellman.
  78. */
  79. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  80. /**
  81. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  82. *
  83. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  84. * stream as its one-time-use key followed by payload encryption with
  85. * the remaining Salsa20/12 key stream. Key agreement is performed using
  86. * Curve25519 elliptic curve Diffie-Hellman.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  89. /**
  90. * Cipher suite: Curve25519/AES256-GCM
  91. *
  92. * This specifies AES256 in GCM mode using GCM's built-in authentication
  93. * with Curve25519 elliptic curve Diffie-Hellman.
  94. *
  95. * (Not implemented yet in client but reserved for future use.)
  96. */
  97. #define ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM 2
  98. /**
  99. * Header flag indicating that a packet is fragmented
  100. *
  101. * If this flag is set, the receiver knows to expect more than one fragment.
  102. * See Packet::Fragment for details.
  103. */
  104. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  105. /**
  106. * Verb flag indicating payload is compressed with LZ4
  107. */
  108. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  109. /**
  110. * Rounds used for Salsa20 encryption in ZT
  111. */
  112. #define ZT_PROTO_SALSA20_ROUNDS 12
  113. // Indices of fields in normal packet header -- do not change as this
  114. // might require both code rework and will break compatibility.
  115. #define ZT_PACKET_IDX_IV 0
  116. #define ZT_PACKET_IDX_DEST 8
  117. #define ZT_PACKET_IDX_SOURCE 13
  118. #define ZT_PACKET_IDX_FLAGS 18
  119. #define ZT_PACKET_IDX_MAC 19
  120. #define ZT_PACKET_IDX_VERB 27
  121. #define ZT_PACKET_IDX_PAYLOAD 28
  122. /**
  123. * Packet buffer size (can be changed)
  124. */
  125. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  126. /**
  127. * Minimum viable packet length (also length of header)
  128. */
  129. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  130. // Indexes of fields in fragment header -- also can't be changed without
  131. // breaking compatibility.
  132. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  133. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  134. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  135. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  136. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  137. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  138. /**
  139. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  140. */
  141. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  142. /**
  143. * Minimum viable fragment length
  144. */
  145. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  146. /**
  147. * Length of LAN beacon packets
  148. */
  149. #define ZT_PROTO_BEACON_LENGTH 13
  150. /**
  151. * Index of address in a LAN beacon
  152. */
  153. #define ZT_PROTO_BEACON_IDX_ADDRESS 8
  154. // Field incides for parsing verbs -------------------------------------------
  155. // Some verbs have variable-length fields. Those aren't fully defined here
  156. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  157. // See their respective handler functions.
  158. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  159. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  160. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  161. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  162. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  163. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  164. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  165. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  166. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  167. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  168. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  169. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  170. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  171. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  172. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  173. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  174. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  175. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  176. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  177. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  178. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  179. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  180. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  181. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  182. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  183. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  184. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  185. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  186. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  187. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  188. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  189. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  190. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  191. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  192. // P5_MULTICAST_FRAME is deprecated
  193. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH (ZT_PACKET_IDX_PAYLOAD)
  194. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH 2
  195. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_FIFO (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH)
  196. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_FIFO 320
  197. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO)
  198. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM 1024
  199. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM)
  200. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_FLAGS 1
  201. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS)
  202. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FLAGS)
  203. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_NETWORK_ID 8
  204. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_NETWORK_ID)
  205. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE 2
  206. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE)
  207. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS 1
  208. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS)
  209. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX 1
  210. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_ORIGIN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX)
  211. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_ORIGIN 5
  212. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_ORIGIN_MCID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN)
  213. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_ORIGIN_MCID 3
  214. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_GUID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN)
  215. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_GUID 8
  216. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN_MCID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN_MCID)
  217. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_SOURCE_MAC 6
  218. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC)
  219. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_DEST_MAC 6
  220. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC)
  221. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_DEST_ADI 4
  222. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_ADI)
  223. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_ETHERTYPE 2
  224. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_FRAME_LEN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ETHERTYPE)
  225. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_LEN_FRAME_LEN 2
  226. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FRAME_LEN)
  227. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE 0x01
  228. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  229. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  230. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  231. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  232. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  233. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  234. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  235. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  236. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN (ZT_PACKET_IDX_PAYLOAD)
  237. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN + 5)
  238. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  239. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  240. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT + 4)
  241. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  242. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  243. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC + 6)
  244. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  245. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  246. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  247. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  248. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  249. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  250. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  251. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  252. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  253. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  254. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  255. // ---------------------------------------------------------------------------
  256. namespace ZeroTier {
  257. /**
  258. * ZeroTier packet
  259. *
  260. * Packet format:
  261. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  262. * <[5] destination ZT address>
  263. * <[5] source ZT address>
  264. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  265. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  266. * [... -- begin encryption envelope -- ...]
  267. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  268. * [... verb-specific payload ...]
  269. *
  270. * Packets smaller than 28 bytes are invalid and silently discarded.
  271. *
  272. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  273. * selection allowing up to 8 cipher suites, F is flags (reserved, currently
  274. * all zero), and H is hop count.
  275. *
  276. * The three-bit hop count is the only part of a packet that is mutable in
  277. * transit without invalidating the MAC. All other bits in the packet are
  278. * immutable. This is because intermediate nodes can increment the hop
  279. * count up to 7 (protocol max).
  280. *
  281. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  282. *
  283. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  284. * sent in the clear, as it's the "here is my public key" message.
  285. *
  286. * Beacon format and beacon packets:
  287. * <[8] 8 random bytes>
  288. * <[5] sender ZT address>
  289. *
  290. * A beacon is a 13-byte packet containing only the address of the sender.
  291. * Receiving peers may or may not respond to beacons with a HELLO or other
  292. * message to initiate direct communication.
  293. *
  294. * Beacons may be used for direct LAN announcement or NAT traversal.
  295. */
  296. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  297. {
  298. public:
  299. /**
  300. * A packet fragment
  301. *
  302. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  303. * is sent with its normal header with the fragmented flag set. Remaining
  304. * fragments are sent this way.
  305. *
  306. * The fragmented bit indicates that there is at least one fragment. Fragments
  307. * themselves contain the total, so the receiver must "learn" this from the
  308. * first fragment it receives.
  309. *
  310. * Fragments are sent with the following format:
  311. * <[8] packet ID of packet whose fragment this belongs to>
  312. * <[5] destination ZT address>
  313. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  314. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  315. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  316. * <[...] fragment data>
  317. *
  318. * The protocol supports a maximum of 16 fragments. If a fragment is received
  319. * before its main packet header, it should be cached for a brief period of
  320. * time to see if its parent arrives. Loss of any fragment constitutes packet
  321. * loss; there is no retransmission mechanism. The receiver must wait for full
  322. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  323. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  324. */
  325. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  326. {
  327. public:
  328. Fragment() :
  329. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  330. {
  331. }
  332. template<unsigned int C2>
  333. Fragment(const Buffer<C2> &b)
  334. throw(std::out_of_range) :
  335. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  336. {
  337. }
  338. /**
  339. * Initialize from a packet
  340. *
  341. * @param p Original assembled packet
  342. * @param fragStart Start of fragment (raw index in packet data)
  343. * @param fragLen Length of fragment in bytes
  344. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  345. * @param fragTotal Total number of fragments (including 0)
  346. * @throws std::out_of_range Packet size would exceed buffer
  347. */
  348. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  349. throw(std::out_of_range)
  350. {
  351. init(p,fragStart,fragLen,fragNo,fragTotal);
  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. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  364. throw(std::out_of_range)
  365. {
  366. if ((fragStart + fragLen) > p.size())
  367. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  368. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  369. // NOTE: this copies both the IV/packet ID and the destination address.
  370. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),field(ZT_PACKET_IDX_IV,13),13);
  371. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  372. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  373. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  374. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),field(fragStart,fragLen),fragLen);
  375. }
  376. /**
  377. * Get this fragment's destination
  378. *
  379. * @return Destination ZT address
  380. */
  381. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  382. /**
  383. * @return True if fragment is of a valid length
  384. */
  385. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  386. /**
  387. * @return ID of packet this is a fragment of
  388. */
  389. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  390. /**
  391. * @return Total number of fragments in packet
  392. */
  393. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  394. /**
  395. * @return Fragment number of this fragment
  396. */
  397. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  398. /**
  399. * @return Fragment ZT hop count
  400. */
  401. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  402. /**
  403. * Increment this packet's hop count
  404. */
  405. inline void incrementHops()
  406. {
  407. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  408. }
  409. /**
  410. * @return Length of payload in bytes
  411. */
  412. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  413. /**
  414. * @return Raw packet payload
  415. */
  416. inline const unsigned char *payload() const
  417. {
  418. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  419. }
  420. };
  421. /**
  422. * ZeroTier protocol verbs
  423. */
  424. enum Verb /* Max value: 32 (5 bits) */
  425. {
  426. /* No operation, payload ignored, no reply */
  427. VERB_NOP = 0,
  428. /* Announcement of a node's existence:
  429. * <[1] protocol version>
  430. * <[1] software major version>
  431. * <[1] software minor version>
  432. * <[2] software revision>
  433. * <[8] timestamp (ms since epoch)>
  434. * <[...] binary serialized identity (see Identity)>
  435. *
  436. * OK payload:
  437. * <[8] timestamp (echoed from original HELLO)>
  438. * <[1] protocol version (of responder)>
  439. * <[1] software major version (of responder)>
  440. * <[1] software minor version (of responder)>
  441. * <[2] software revision (of responder)>
  442. *
  443. * ERROR has no payload.
  444. */
  445. VERB_HELLO = 1,
  446. /* Error response:
  447. * <[1] in-re verb>
  448. * <[8] in-re packet ID>
  449. * <[1] error code>
  450. * <[...] error-dependent payload>
  451. */
  452. VERB_ERROR = 2,
  453. /* Success response:
  454. * <[1] in-re verb>
  455. * <[8] in-re packet ID>
  456. * <[...] request-specific payload>
  457. */
  458. VERB_OK = 3,
  459. /* Query an identity by address:
  460. * <[5] address to look up>
  461. *
  462. * OK response payload:
  463. * <[...] binary serialized identity>
  464. *
  465. * ERROR response payload:
  466. * <[5] address>
  467. */
  468. VERB_WHOIS = 4,
  469. /* Meet another node at a given protocol address:
  470. * <[1] flags (unused, currently 0)>
  471. * <[5] ZeroTier address of peer that might be found at this address>
  472. * <[2] 16-bit protocol address port>
  473. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  474. * <[...] protocol address (network byte order)>
  475. *
  476. * This is sent by a relaying node to initiate NAT traversal between two
  477. * peers that are communicating by way of indirect relay. The relay will
  478. * send this to both peers at the same time on a periodic basis, telling
  479. * each where it might find the other on the network.
  480. *
  481. * Upon receipt a peer sends HELLO to establish a direct link.
  482. *
  483. * Nodes should implement rate control, limiting the rate at which they
  484. * respond to these packets to prevent their use in DDOS attacks. Nodes
  485. * may also ignore these messages if a peer is not known or is not being
  486. * actively communicated with.
  487. *
  488. * No OK or ERROR is generated.
  489. */
  490. VERB_RENDEZVOUS = 5,
  491. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  492. * <[8] 64-bit network ID>
  493. * <[2] 16-bit ethertype>
  494. * <[...] ethernet payload>
  495. *
  496. * MAC addresses are derived from the packet's source and destination
  497. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  498. * Ethernet framing and other optional flags and features when they
  499. * are not necessary.
  500. *
  501. * ERROR may be generated if a membership certificate is needed for a
  502. * closed network. Payload will be network ID.
  503. */
  504. VERB_FRAME = 6,
  505. /* Full Ethernet frame with MAC addressing and optional fields:
  506. * <[8] 64-bit network ID>
  507. * <[1] flags>
  508. * [<[...] certificate of network membership>]
  509. * <[6] destination MAC or all zero for destination node>
  510. * <[6] source MAC or all zero for node of origin>
  511. * <[2] 16-bit ethertype>
  512. * <[...] ethernet payload>
  513. *
  514. * Flags:
  515. * 0x01 - Certificate of network membership is attached
  516. *
  517. * An extended frame carries full MAC addressing, making them a
  518. * superset of VERB_FRAME. They're used for bridging or when we
  519. * want to attach a certificate since FRAME does not support that.
  520. *
  521. * Multicast frames may not be sent as EXT_FRAME.
  522. *
  523. * ERROR may be generated if a membership certificate is needed for a
  524. * closed network. Payload will be network ID.
  525. */
  526. VERB_EXT_FRAME = 7,
  527. /* A multicast frame [old multicast protocol, deprecated]:
  528. * <[2] 16-bit propagation depth or 0xffff for "do not forward">
  529. * <[320] propagation FIFO>
  530. * <[1024] propagation bloom filter>
  531. * [... begin signed portion ...]
  532. * <[1] 8-bit flags, currently unused and must be 0>
  533. * <[8] 64-bit network ID>
  534. * <[2] 16-bit random propagation bloom filter nonce>
  535. * <[1] number of significant bits in propagation restrict prefix>
  536. * <[1] propagation restriction prefix (sig bits right to left)>
  537. * <[5] ZeroTier address of node of origin>
  538. * <[3] 24-bit multicast ID, together with origin forms GUID>
  539. * <[6] source MAC address>
  540. * <[6] destination multicast group MAC address>
  541. * <[4] destination multicast group ADI field>
  542. * <[2] 16-bit frame ethertype>
  543. * <[2] 16-bit length of payload>
  544. * <[...] ethernet frame payload>
  545. * [... end of signed portion ...]
  546. * <[2] 16-bit length of signature>
  547. * <[...] signature (currently Ed25519/SHA-512, 96 bytes in length)>
  548. * [<[...] network membership certificate (optional)>]
  549. *
  550. * Flags:
  551. * 0x01 - Multicast frame includes network membership certificate
  552. * for original sender for this network.
  553. *
  554. * When a multicast frame is received:
  555. *
  556. * (1) Check the signature of the signed portion of packet, discard on fail
  557. * (2) Check for duplicate multicast, STOP if duplicate
  558. * (3) Check rate limits, STOP if over limit
  559. * (4) Inject into tap if member of network and packet passes other checks
  560. * (5) Increment propagation depth, STOP if over limit
  561. * (6) Pop topmost element off FIFO -- this is next hop
  562. * (7) Push suggested next hops onto FIFO until full -- set corresponding
  563. * bits in bloom filter
  564. * (8) Send to next hop, or to a supernode if none
  565. *
  566. * When choosing next hops, exclude addresses corresponding to bits already
  567. * set in the bloom filter and addresses outside the propagation restrict
  568. * prefix.
  569. *
  570. * Active bridges on a network are always added as next hops for all
  571. * multicast and broadcast traffic, as if they "like" all groups.
  572. *
  573. * Algorithm for setting bits in bloom filter:
  574. *
  575. * (1) Place the address in the least significant 40 bits of a 64-bit int.
  576. * (2) Add the bloom filter nonce to this value.
  577. * (3) XOR the least significant 13 bits of this value with the next most
  578. * significant 13 bits and so on, 4 times.
  579. * (4) This value ANDed with 0x1fff is the bit to set in the bloom filter.
  580. * (5) Set this bit via: byte[bit >> 3] |= (0x80 >> (bit & 7))
  581. *
  582. * To check bits in bloom filter perform the same computation but mask the
  583. * bit instead of ORing it.
  584. *
  585. * Propagation occurs within a restrict prefix. The restrict prefix is
  586. * applied to the least significant 16 bits of an address. The original
  587. * sender of the multicast sets the restrict prefix and sends 2^N copies
  588. * of the multicast frame, one for each address prefix.
  589. *
  590. * ERROR may be generated if a membership certificate is needed for a
  591. * closed network. Payload will be network ID.
  592. */
  593. VERB_P5_MULTICAST_FRAME = 8,
  594. /* Announce interest in multicast group(s):
  595. * <[8] 64-bit network ID>
  596. * <[6] multicast Ethernet address>
  597. * <[4] multicast additional distinguishing information (ADI)>
  598. * [... additional tuples of network/address/adi ...]
  599. *
  600. * LIKEs are sent to peers with whom you have a direct peer to peer
  601. * connection, and always including supernodes.
  602. *
  603. * OK/ERROR are not generated.
  604. */
  605. VERB_MULTICAST_LIKE = 9,
  606. /* Network member certificate replication/push:
  607. * <[...] serialized certificate of membership>
  608. * [ ... additional certificates may follow ...]
  609. *
  610. * Certificate contains network ID, peer it was issued for, etc.
  611. *
  612. * OK/ERROR are not generated.
  613. */
  614. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  615. /* Network configuration request:
  616. * <[8] 64-bit network ID>
  617. * <[2] 16-bit length of request meta-data dictionary>
  618. * <[...] string-serialized request meta-data>
  619. *
  620. * This message requests network configuration from a node capable of
  621. * providing it. Such nodes run the netconf service, which must be
  622. * installed into the ZeroTier home directory.
  623. *
  624. * OK response payload:
  625. * <[8] 64-bit network ID>
  626. * <[2] 16-bit length of network configuration dictionary>
  627. * <[...] network configuration dictionary>
  628. *
  629. * OK returns a Dictionary (string serialized) containing the network's
  630. * configuration and IP address assignment information for the querying
  631. * node. It also contains a membership certificate that the querying
  632. * node can push to other peers to demonstrate its right to speak on
  633. * a given network.
  634. *
  635. * ERROR response payload:
  636. * <[8] 64-bit network ID>
  637. *
  638. * Support is optional. Nodes should return UNSUPPORTED_OPERATION if
  639. * not supported or enabled.
  640. */
  641. VERB_NETWORK_CONFIG_REQUEST = 11,
  642. /* Network configuration refresh request:
  643. * <[...] array of 64-bit network IDs>
  644. *
  645. * This message can be sent by the network configuration master node
  646. * to request that nodes refresh their network configuration. It can
  647. * thus be used to "push" updates so that network config changes will
  648. * take effect quickly.
  649. *
  650. * It does not generate an OK or ERROR message, and is treated only as
  651. * a hint to refresh now.
  652. */
  653. VERB_NETWORK_CONFIG_REFRESH = 12,
  654. /* Request endpoints for multicast distribution:
  655. * <[8] 64-bit network ID>
  656. * <[1] flags (unused, must be 0)>
  657. * <[6] MAC address of multicast group being queried>
  658. * <[4] 32-bit ADI for multicast group being queried>
  659. * <[4] 32-bit (suggested) max number of multicast peers desired or 0 for no limit>
  660. *
  661. * This message asks a peer for additional known endpoints that have
  662. * LIKEd a given multicast group. It's sent when the sender wishes
  663. * to send multicast but does not have the desired number of recipient
  664. * peers.
  665. *
  666. * OK response payload:
  667. * <[8] 64-bit network ID>
  668. * <[6] MAC address of multicast group being queried>
  669. * <[4] 32-bit ADI for multicast group being queried>
  670. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  671. * <[4] 32-bit total number of known members in this multicast group>
  672. * <[2] 16-bit number of members enumerated in this packet>
  673. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  674. *
  675. * If no endpoints are known, OK and ERROR are both optional. It's okay
  676. * to return nothing in that case since gathering is "lazy."
  677. *
  678. * ERROR response payload:
  679. * <[8] 64-bit network ID>
  680. * <[6] MAC address of multicast group being queried>
  681. * <[4] 32-bit ADI for multicast group being queried>
  682. *
  683. * ERRORs are optional and are only generated if permission is denied,
  684. * certificate of membership is out of date, etc.
  685. */
  686. VERB_MULTICAST_GATHER = 13,
  687. /* Multicast frame:
  688. * <[5] ZT address of original source of multicast frame>
  689. * <[8] 64-bit network ID>
  690. * <[1] flags>
  691. * <[4] 32-bit (suggested) gather limit or 0 for no implicit gathering>
  692. * [<[...] network certificate of membership if included>]
  693. * <[4] 32-bit multicast ADI (note that this is out of order here -- it precedes MAC)>
  694. * <[6] destination MAC or all zero for destination node>
  695. * <[6] source MAC or all zero for node of origin>
  696. * <[2] 16-bit ethertype>
  697. * <[...] ethernet payload>
  698. *
  699. * Flags:
  700. * 0x01 - Network certificate of membership is attached
  701. *
  702. * This is similar to EXT_FRAME but carries a multicast, and is sent
  703. * out to recipients on a multicast list. It may also specify a desired
  704. * number of multicast peers to gather if additional multicast peers
  705. * for this group are desired.
  706. *
  707. * (ADI precedes MAC here so that everything from destination MAC forward
  708. * could be treated as a raw Ethernet frame.)
  709. *
  710. * OK responses are optional and are currently only returned if gathering
  711. * of additional multicast peers is requested.
  712. *
  713. * OK response payload:
  714. * <[8] 64-bit network ID>
  715. * <[6] MAC address of multicast group>
  716. * <[4] 32-bit ADI for multicast group>
  717. * <[1] flags>
  718. * [<[...] implicit gather results if flag 0x01 is set>]
  719. *
  720. * Flags:
  721. * 0x01 - OK include implicit gather results
  722. *
  723. * ERROR response payload:
  724. * <[8] 64-bit network ID>
  725. * <[6] multicast group MAC>
  726. * <[4] 32-bit multicast group ADI>
  727. *
  728. * ERRORs are optional and can be generated if a certificate is needed or if
  729. * multicasts for this multicast group are no longer wanted.
  730. */
  731. VERB_MULTICAST_FRAME = 14
  732. };
  733. /**
  734. * Error codes for VERB_ERROR
  735. */
  736. enum ErrorCode
  737. {
  738. /* No error, not actually used in transit */
  739. ERROR_NONE = 0,
  740. /* Invalid request */
  741. ERROR_INVALID_REQUEST = 1,
  742. /* Bad/unsupported protocol version */
  743. ERROR_BAD_PROTOCOL_VERSION = 2,
  744. /* Unknown object queried (e.g. with WHOIS) */
  745. ERROR_OBJ_NOT_FOUND = 3,
  746. /* HELLO pushed an identity whose address is already claimed */
  747. ERROR_IDENTITY_COLLISION = 4,
  748. /* Verb or use case not supported/enabled by this node */
  749. ERROR_UNSUPPORTED_OPERATION = 5,
  750. /* Message to private network rejected -- no unexpired certificate on file */
  751. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  752. /* Tried to join network, but you're not a member */
  753. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  754. /* Multicasts to this group are not wanted */
  755. ERROR_UNWANTED_MULTICAST = 8
  756. };
  757. /**
  758. * @param v Verb
  759. * @return String representation (e.g. HELLO, OK)
  760. */
  761. static const char *verbString(Verb v)
  762. throw();
  763. /**
  764. * @param e Error code
  765. * @return String error name
  766. */
  767. static const char *errorString(ErrorCode e)
  768. throw();
  769. template<unsigned int C2>
  770. Packet(const Buffer<C2> &b)
  771. throw(std::out_of_range) :
  772. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  773. {
  774. }
  775. /**
  776. * Construct a new empty packet with a unique random packet ID
  777. *
  778. * Flags and hops will be zero. Other fields and data region are undefined.
  779. * Use the header access methods (setDestination() and friends) to fill out
  780. * the header. Payload should be appended; initial size is header size.
  781. */
  782. Packet() :
  783. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  784. {
  785. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  786. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  787. }
  788. /**
  789. * Make a copy of a packet with a new initialization vector and destination address
  790. *
  791. * This can be used to take one draft prototype packet and quickly make copies to
  792. * encrypt for different destinations.
  793. *
  794. * @param prototype Prototype packet
  795. * @param dest Destination ZeroTier address for new packet
  796. */
  797. Packet(const Packet &prototype,const Address &dest) :
  798. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  799. {
  800. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  801. setDestination(dest);
  802. }
  803. /**
  804. * Construct a new empty packet with a unique random packet ID
  805. *
  806. * @param dest Destination ZT address
  807. * @param source Source ZT address
  808. * @param v Verb
  809. */
  810. Packet(const Address &dest,const Address &source,const Verb v) :
  811. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  812. {
  813. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  814. setDestination(dest);
  815. setSource(source);
  816. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  817. setVerb(v);
  818. }
  819. /**
  820. * Reset this packet structure for reuse in place
  821. *
  822. * @param dest Destination ZT address
  823. * @param source Source ZT address
  824. * @param v Verb
  825. */
  826. inline void reset(const Address &dest,const Address &source,const Verb v)
  827. {
  828. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  829. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  830. setDestination(dest);
  831. setSource(source);
  832. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  833. setVerb(v);
  834. }
  835. /**
  836. * Generate a new IV / packet ID in place
  837. *
  838. * This can be used to re-use a packet buffer multiple times to send
  839. * technically different but otherwise identical copies of the same
  840. * packet.
  841. */
  842. inline void newInitializationVector()
  843. {
  844. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  845. }
  846. /**
  847. * Set this packet's destination
  848. *
  849. * @param dest ZeroTier address of destination
  850. */
  851. inline void setDestination(const Address &dest)
  852. {
  853. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  854. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  855. d[i] = dest[i];
  856. }
  857. /**
  858. * Set this packet's source
  859. *
  860. * @param source ZeroTier address of source
  861. */
  862. inline void setSource(const Address &source)
  863. {
  864. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  865. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  866. s[i] = source[i];
  867. }
  868. /**
  869. * Get this packet's destination
  870. *
  871. * @return Destination ZT address
  872. */
  873. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  874. /**
  875. * Get this packet's source
  876. *
  877. * @return Source ZT address
  878. */
  879. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  880. /**
  881. * @return True if packet is of valid length
  882. */
  883. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  884. /**
  885. * @return True if packet is fragmented (expect fragments)
  886. */
  887. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  888. /**
  889. * Set this packet's fragmented flag
  890. *
  891. * @param f Fragmented flag value
  892. */
  893. inline void setFragmented(bool f)
  894. {
  895. if (f)
  896. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  897. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  898. }
  899. /**
  900. * @return True if compressed (result only valid if unencrypted)
  901. */
  902. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  903. /**
  904. * @return ZeroTier forwarding hops (0 to 7)
  905. */
  906. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  907. /**
  908. * Increment this packet's hop count
  909. */
  910. inline void incrementHops()
  911. {
  912. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  913. b = (b & 0xf8) | ((b + 1) & 0x07);
  914. }
  915. /**
  916. * @return Cipher suite selector: 0 - 7 (see #defines)
  917. */
  918. inline unsigned int cipher() const
  919. {
  920. //return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  921. // Use DEPRECATED 0x80 "encrypted" flag -- this will go away once there are no more <1.0.0 peers on the net
  922. return (((*this)[ZT_PACKET_IDX_FLAGS] & 0x80) == 0) ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012;
  923. }
  924. /**
  925. * Set this packet's cipher suite
  926. *
  927. * This normally shouldn't be called directly as armor() will set it after
  928. * encrypting and MACing the packet.
  929. */
  930. inline void setCipher(unsigned int c)
  931. {
  932. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  933. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38);
  934. // Set both the new cipher suite spec field and the old DEPRECATED "encrypted" flag as long as there's <1.0.0 peers online
  935. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  936. b |= 0x80;
  937. else b &= 0x7f;
  938. }
  939. /**
  940. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  941. *
  942. * @return Packet ID
  943. */
  944. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  945. /**
  946. * Set packet verb
  947. *
  948. * This also has the side-effect of clearing any verb flags, such as
  949. * compressed, and so must only be done during packet composition.
  950. *
  951. * @param v New packet verb
  952. */
  953. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  954. /**
  955. * @return Packet verb (not including flag bits)
  956. */
  957. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  958. /**
  959. * @return Length of packet payload
  960. */
  961. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  962. /**
  963. * @return Raw packet payload
  964. */
  965. inline const unsigned char *payload() const
  966. {
  967. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  968. }
  969. /**
  970. * Armor packet for transport
  971. *
  972. * @param key 32-byte key
  973. * @param encryptPayload If true, encrypt packet payload, else just MAC
  974. */
  975. inline void armor(const void *key,bool encryptPayload)
  976. {
  977. unsigned char mangledKey[32];
  978. unsigned char macKey[32];
  979. unsigned char mac[16];
  980. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  981. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  982. // Set flag now, since it affects key mangle function
  983. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  984. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  985. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  986. // MAC key is always the first 32 bytes of the Salsa20 key stream
  987. // This is the same construction DJB's NaCl library uses
  988. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  989. if (encryptPayload)
  990. s20.encrypt(payload,payload,payloadLen);
  991. Poly1305::compute(mac,payload,payloadLen,macKey);
  992. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  993. }
  994. /**
  995. * Verify and (if encrypted) decrypt packet
  996. *
  997. * @param key 32-byte key
  998. * @return False if packet is invalid or failed MAC authenticity check
  999. */
  1000. inline bool dearmor(const void *key)
  1001. {
  1002. unsigned char mangledKey[32];
  1003. unsigned char macKey[32];
  1004. unsigned char mac[16];
  1005. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  1006. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  1007. unsigned int cs = cipher();
  1008. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  1009. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  1010. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  1011. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  1012. Poly1305::compute(mac,payload,payloadLen,macKey);
  1013. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  1014. return false;
  1015. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1016. s20.decrypt(payload,payload,payloadLen);
  1017. return true;
  1018. } else if (cs == ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM) {
  1019. return false; // not implemented yet
  1020. } else return false; // unrecognized cipher suite
  1021. }
  1022. /**
  1023. * Attempt to compress payload if not already (must be unencrypted)
  1024. *
  1025. * This requires that the payload at least contain the verb byte already
  1026. * set. The compressed flag in the verb is set if compression successfully
  1027. * results in a size reduction. If no size reduction occurs, compression
  1028. * is not done and the flag is left cleared.
  1029. *
  1030. * @return True if compression occurred
  1031. */
  1032. inline bool compress()
  1033. {
  1034. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  1035. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  1036. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  1037. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  1038. if ((cl > 0)&&(cl < pl)) {
  1039. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  1040. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  1041. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  1042. return true;
  1043. }
  1044. }
  1045. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1046. return false;
  1047. }
  1048. /**
  1049. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1050. *
  1051. * If payload is compressed, it is decompressed and the compressed verb
  1052. * flag is cleared. Otherwise nothing is done and true is returned.
  1053. *
  1054. * @return True if data is now decompressed and valid, false on error
  1055. */
  1056. inline bool uncompress()
  1057. {
  1058. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  1059. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  1060. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1061. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1062. int ucl = LZ4_decompress_safe((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  1063. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1064. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1065. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  1066. } else return false;
  1067. }
  1068. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1069. }
  1070. return true;
  1071. }
  1072. private:
  1073. static const unsigned char ZERO_KEY[32];
  1074. /**
  1075. * Deterministically mangle a 256-bit crypto key based on packet
  1076. *
  1077. * This uses extra data from the packet to mangle the secret, giving us an
  1078. * effective IV that is somewhat more than 64 bits. This is "free" for
  1079. * Salsa20 since it has negligible key setup time so using a different
  1080. * key each time is fine.
  1081. *
  1082. * @param in Input key (32 bytes)
  1083. * @param out Output buffer (32 bytes)
  1084. */
  1085. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1086. {
  1087. const unsigned char *d = (const unsigned char *)data();
  1088. // IV and source/destination addresses. Using the addresses divides the
  1089. // key space into two halves-- A->B and B->A (since order will change).
  1090. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1091. out[i] = in[i] ^ d[i];
  1092. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1093. // nodes. It's one of the only parts of a packet modifiable by people
  1094. // without the key.
  1095. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1096. // Raw packet size in bytes -- thus each packet size defines a new
  1097. // key space.
  1098. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1099. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1100. // Rest of raw key is used unchanged
  1101. for(unsigned int i=21;i<32;++i)
  1102. out[i] = in[i];
  1103. }
  1104. };
  1105. } // namespace ZeroTier
  1106. #endif