Packet.hpp 44 KB

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