Packet.hpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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_P5_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_PROPAGATION_FIFO + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_FLAGS)
  202. #define ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_P5_MULTICAST_FRAME_IDX_FLAGS + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_ORIGIN + ZT_PROTO_VERB_P5_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_P5_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_P5_MULTICAST_FRAME_IDX_ORIGIN_MCID + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_SOURCE_MAC + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_DEST_MAC + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_DEST_ADI + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_P5_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_P5_MULTICAST_FRAME_IDX_FRAME_LEN + ZT_PROTO_VERB_P5_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. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  237. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  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_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  240. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  241. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  242. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  243. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  244. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  245. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  246. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  247. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  248. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  249. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  250. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  251. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  252. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  253. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  254. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  255. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  256. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  257. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  258. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  259. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  260. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  261. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  262. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  263. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  264. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_PAYLOAD (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  265. // ---------------------------------------------------------------------------
  266. namespace ZeroTier {
  267. /**
  268. * ZeroTier packet
  269. *
  270. * Packet format:
  271. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  272. * <[5] destination ZT address>
  273. * <[5] source ZT address>
  274. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  275. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  276. * [... -- begin encryption envelope -- ...]
  277. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  278. * [... verb-specific payload ...]
  279. *
  280. * Packets smaller than 28 bytes are invalid and silently discarded.
  281. *
  282. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  283. * selection allowing up to 8 cipher suites, F is flags (reserved, currently
  284. * all zero), and H is hop count.
  285. *
  286. * The three-bit hop count is the only part of a packet that is mutable in
  287. * transit without invalidating the MAC. All other bits in the packet are
  288. * immutable. This is because intermediate nodes can increment the hop
  289. * count up to 7 (protocol max).
  290. *
  291. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  292. *
  293. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  294. * sent in the clear, as it's the "here is my public key" message.
  295. *
  296. * Beacon format and beacon packets:
  297. * <[8] 8 random bytes>
  298. * <[5] sender ZT address>
  299. *
  300. * A beacon is a 13-byte packet containing only the address of the sender.
  301. * Receiving peers may or may not respond to beacons with a HELLO or other
  302. * message to initiate direct communication.
  303. *
  304. * Beacons may be used for direct LAN announcement or NAT traversal.
  305. */
  306. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  307. {
  308. public:
  309. /**
  310. * A packet fragment
  311. *
  312. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  313. * is sent with its normal header with the fragmented flag set. Remaining
  314. * fragments are sent this way.
  315. *
  316. * The fragmented bit indicates that there is at least one fragment. Fragments
  317. * themselves contain the total, so the receiver must "learn" this from the
  318. * first fragment it receives.
  319. *
  320. * Fragments are sent with the following format:
  321. * <[8] packet ID of packet whose fragment this belongs to>
  322. * <[5] destination ZT address>
  323. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  324. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  325. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  326. * <[...] fragment data>
  327. *
  328. * The protocol supports a maximum of 16 fragments. If a fragment is received
  329. * before its main packet header, it should be cached for a brief period of
  330. * time to see if its parent arrives. Loss of any fragment constitutes packet
  331. * loss; there is no retransmission mechanism. The receiver must wait for full
  332. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  333. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  334. */
  335. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  336. {
  337. public:
  338. Fragment() :
  339. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  340. {
  341. }
  342. template<unsigned int C2>
  343. Fragment(const Buffer<C2> &b)
  344. throw(std::out_of_range) :
  345. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  346. {
  347. }
  348. /**
  349. * Initialize from a packet
  350. *
  351. * @param p Original assembled packet
  352. * @param fragStart Start of fragment (raw index in packet data)
  353. * @param fragLen Length of fragment in bytes
  354. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  355. * @param fragTotal Total number of fragments (including 0)
  356. * @throws std::out_of_range Packet size would exceed buffer
  357. */
  358. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  359. throw(std::out_of_range)
  360. {
  361. init(p,fragStart,fragLen,fragNo,fragTotal);
  362. }
  363. /**
  364. * Initialize from a packet
  365. *
  366. * @param p Original assembled packet
  367. * @param fragStart Start of fragment (raw index in packet data)
  368. * @param fragLen Length of fragment in bytes
  369. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  370. * @param fragTotal Total number of fragments (including 0)
  371. * @throws std::out_of_range Packet size would exceed buffer
  372. */
  373. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  374. throw(std::out_of_range)
  375. {
  376. if ((fragStart + fragLen) > p.size())
  377. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  378. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  379. // NOTE: this copies both the IV/packet ID and the destination address.
  380. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),field(ZT_PACKET_IDX_IV,13),13);
  381. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  382. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  383. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  384. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),field(fragStart,fragLen),fragLen);
  385. }
  386. /**
  387. * Get this fragment's destination
  388. *
  389. * @return Destination ZT address
  390. */
  391. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  392. /**
  393. * @return True if fragment is of a valid length
  394. */
  395. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  396. /**
  397. * @return ID of packet this is a fragment of
  398. */
  399. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  400. /**
  401. * @return Total number of fragments in packet
  402. */
  403. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  404. /**
  405. * @return Fragment number of this fragment
  406. */
  407. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  408. /**
  409. * @return Fragment ZT hop count
  410. */
  411. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  412. /**
  413. * Increment this packet's hop count
  414. */
  415. inline void incrementHops()
  416. {
  417. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  418. }
  419. /**
  420. * @return Length of payload in bytes
  421. */
  422. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  423. /**
  424. * @return Raw packet payload
  425. */
  426. inline const unsigned char *payload() const
  427. {
  428. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  429. }
  430. };
  431. /**
  432. * ZeroTier protocol verbs
  433. */
  434. enum Verb /* Max value: 32 (5 bits) */
  435. {
  436. /* No operation, payload ignored, no reply */
  437. VERB_NOP = 0,
  438. /* Announcement of a node's existence:
  439. * <[1] protocol version>
  440. * <[1] software major version>
  441. * <[1] software minor version>
  442. * <[2] software revision>
  443. * <[8] timestamp (ms since epoch)>
  444. * <[...] binary serialized identity (see Identity)>
  445. *
  446. * OK payload:
  447. * <[8] timestamp (echoed from original HELLO)>
  448. * <[1] protocol version (of responder)>
  449. * <[1] software major version (of responder)>
  450. * <[1] software minor version (of responder)>
  451. * <[2] software revision (of responder)>
  452. *
  453. * ERROR has no payload.
  454. */
  455. VERB_HELLO = 1,
  456. /* Error response:
  457. * <[1] in-re verb>
  458. * <[8] in-re packet ID>
  459. * <[1] error code>
  460. * <[...] error-dependent payload>
  461. */
  462. VERB_ERROR = 2,
  463. /* Success response:
  464. * <[1] in-re verb>
  465. * <[8] in-re packet ID>
  466. * <[...] request-specific payload>
  467. */
  468. VERB_OK = 3,
  469. /* Query an identity by address:
  470. * <[5] address to look up>
  471. *
  472. * OK response payload:
  473. * <[...] binary serialized identity>
  474. *
  475. * ERROR response payload:
  476. * <[5] address>
  477. */
  478. VERB_WHOIS = 4,
  479. /* Meet another node at a given protocol address:
  480. * <[1] flags (unused, currently 0)>
  481. * <[5] ZeroTier address of peer that might be found at this address>
  482. * <[2] 16-bit protocol address port>
  483. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  484. * <[...] protocol address (network byte order)>
  485. *
  486. * This is sent by a relaying node to initiate NAT traversal between two
  487. * peers that are communicating by way of indirect relay. The relay will
  488. * send this to both peers at the same time on a periodic basis, telling
  489. * each where it might find the other on the network.
  490. *
  491. * Upon receipt a peer sends HELLO to establish a direct link.
  492. *
  493. * Nodes should implement rate control, limiting the rate at which they
  494. * respond to these packets to prevent their use in DDOS attacks. Nodes
  495. * may also ignore these messages if a peer is not known or is not being
  496. * actively communicated with.
  497. *
  498. * No OK or ERROR is generated.
  499. */
  500. VERB_RENDEZVOUS = 5,
  501. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  502. * <[8] 64-bit network ID>
  503. * <[2] 16-bit ethertype>
  504. * <[...] ethernet payload>
  505. *
  506. * MAC addresses are derived from the packet's source and destination
  507. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  508. * Ethernet framing and other optional flags and features when they
  509. * are not necessary.
  510. *
  511. * ERROR may be generated if a membership certificate is needed for a
  512. * closed network. Payload will be network ID.
  513. */
  514. VERB_FRAME = 6,
  515. /* Full Ethernet frame with MAC addressing and optional fields:
  516. * <[8] 64-bit network ID>
  517. * <[1] flags>
  518. * [<[...] certificate of network membership>]
  519. * <[6] destination MAC or all zero for destination node>
  520. * <[6] source MAC or all zero for node of origin>
  521. * <[2] 16-bit ethertype>
  522. * <[...] ethernet payload>
  523. *
  524. * Flags:
  525. * 0x01 - Certificate of network membership is attached
  526. *
  527. * An extended frame carries full MAC addressing, making them a
  528. * superset of VERB_FRAME. They're used for bridging or when we
  529. * want to attach a certificate since FRAME does not support that.
  530. *
  531. * Multicast frames may not be sent as EXT_FRAME.
  532. *
  533. * ERROR may be generated if a membership certificate is needed for a
  534. * closed network. Payload will be network ID.
  535. */
  536. VERB_EXT_FRAME = 7,
  537. /* A multicast frame [old multicast protocol, deprecated]:
  538. * <[2] 16-bit propagation depth or 0xffff for "do not forward">
  539. * <[320] propagation FIFO>
  540. * <[1024] propagation bloom filter>
  541. * [... begin signed portion ...]
  542. * <[1] 8-bit flags, currently unused and must be 0>
  543. * <[8] 64-bit network ID>
  544. * <[2] 16-bit random propagation bloom filter nonce>
  545. * <[1] number of significant bits in propagation restrict prefix>
  546. * <[1] propagation restriction prefix (sig bits right to left)>
  547. * <[5] ZeroTier address of node of origin>
  548. * <[3] 24-bit multicast ID, together with origin forms GUID>
  549. * <[6] source MAC address>
  550. * <[6] destination multicast group MAC address>
  551. * <[4] destination multicast group ADI field>
  552. * <[2] 16-bit frame ethertype>
  553. * <[2] 16-bit length of payload>
  554. * <[...] ethernet frame payload>
  555. * [... end of signed portion ...]
  556. * <[2] 16-bit length of signature>
  557. * <[...] signature (currently Ed25519/SHA-512, 96 bytes in length)>
  558. * [<[...] network membership certificate (optional)>]
  559. *
  560. * Flags:
  561. * 0x01 - Multicast frame includes network membership certificate
  562. * for original sender for this network.
  563. *
  564. * When a multicast frame is received:
  565. *
  566. * (1) Check the signature of the signed portion of packet, discard on fail
  567. * (2) Check for duplicate multicast, STOP if duplicate
  568. * (3) Check rate limits, STOP if over limit
  569. * (4) Inject into tap if member of network and packet passes other checks
  570. * (5) Increment propagation depth, STOP if over limit
  571. * (6) Pop topmost element off FIFO -- this is next hop
  572. * (7) Push suggested next hops onto FIFO until full -- set corresponding
  573. * bits in bloom filter
  574. * (8) Send to next hop, or to a supernode if none
  575. *
  576. * When choosing next hops, exclude addresses corresponding to bits already
  577. * set in the bloom filter and addresses outside the propagation restrict
  578. * prefix.
  579. *
  580. * Active bridges on a network are always added as next hops for all
  581. * multicast and broadcast traffic, as if they "like" all groups.
  582. *
  583. * Algorithm for setting bits in bloom filter:
  584. *
  585. * (1) Place the address in the least significant 40 bits of a 64-bit int.
  586. * (2) Add the bloom filter nonce to this value.
  587. * (3) XOR the least significant 13 bits of this value with the next most
  588. * significant 13 bits and so on, 4 times.
  589. * (4) This value ANDed with 0x1fff is the bit to set in the bloom filter.
  590. * (5) Set this bit via: byte[bit >> 3] |= (0x80 >> (bit & 7))
  591. *
  592. * To check bits in bloom filter perform the same computation but mask the
  593. * bit instead of ORing it.
  594. *
  595. * Propagation occurs within a restrict prefix. The restrict prefix is
  596. * applied to the least significant 16 bits of an address. The original
  597. * sender of the multicast sets the restrict prefix and sends 2^N copies
  598. * of the multicast frame, one for each address prefix.
  599. *
  600. * ERROR may be generated if a membership certificate is needed for a
  601. * closed network. Payload will be network ID.
  602. */
  603. VERB_P5_MULTICAST_FRAME = 8,
  604. /* Announce interest in multicast group(s):
  605. * <[8] 64-bit network ID>
  606. * <[6] multicast Ethernet address>
  607. * <[4] multicast additional distinguishing information (ADI)>
  608. * [... additional tuples of network/address/adi ...]
  609. *
  610. * LIKEs are sent to peers with whom you have a direct peer to peer
  611. * connection, and always including supernodes.
  612. *
  613. * OK/ERROR are not generated.
  614. */
  615. VERB_MULTICAST_LIKE = 9,
  616. /* Network member certificate replication/push:
  617. * <[...] serialized certificate of membership>
  618. * [ ... additional certificates may follow ...]
  619. *
  620. * Certificate contains network ID, peer it was issued for, etc.
  621. *
  622. * OK/ERROR are not generated.
  623. */
  624. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  625. /* Network configuration request:
  626. * <[8] 64-bit network ID>
  627. * <[2] 16-bit length of request meta-data dictionary>
  628. * <[...] string-serialized request meta-data>
  629. *
  630. * This message requests network configuration from a node capable of
  631. * providing it. Such nodes run the netconf service, which must be
  632. * installed into the ZeroTier home directory.
  633. *
  634. * OK response payload:
  635. * <[8] 64-bit network ID>
  636. * <[2] 16-bit length of network configuration dictionary>
  637. * <[...] network configuration dictionary>
  638. *
  639. * OK returns a Dictionary (string serialized) containing the network's
  640. * configuration and IP address assignment information for the querying
  641. * node. It also contains a membership certificate that the querying
  642. * node can push to other peers to demonstrate its right to speak on
  643. * a given network.
  644. *
  645. * ERROR response payload:
  646. * <[8] 64-bit network ID>
  647. *
  648. * Support is optional. Nodes should return UNSUPPORTED_OPERATION if
  649. * not supported or enabled.
  650. */
  651. VERB_NETWORK_CONFIG_REQUEST = 11,
  652. /* Network configuration refresh request:
  653. * <[...] array of 64-bit network IDs>
  654. *
  655. * This message can be sent by the network configuration master node
  656. * to request that nodes refresh their network configuration. It can
  657. * thus be used to "push" updates so that network config changes will
  658. * take effect quickly.
  659. *
  660. * It does not generate an OK or ERROR message, and is treated only as
  661. * a hint to refresh now.
  662. */
  663. VERB_NETWORK_CONFIG_REFRESH = 12,
  664. /* Request endpoints for multicast distribution:
  665. * <[8] 64-bit network ID>
  666. * <[1] flags>
  667. * <[6] MAC address of multicast group being queried>
  668. * <[4] 32-bit ADI for multicast group being queried>
  669. * <[4] 32-bit requested max number of multicast peers>
  670. * [<[...] network certificate of membership>]
  671. *
  672. * Flags:
  673. * 0x01 - Network certificate of membership is attached
  674. *
  675. * This message asks a peer for additional known endpoints that have
  676. * LIKEd a given multicast group. It's sent when the sender wishes
  677. * to send multicast but does not have the desired number of recipient
  678. * peers.
  679. *
  680. * OK response payload:
  681. * <[8] 64-bit network ID>
  682. * <[6] MAC address of multicast group being queried>
  683. * <[4] 32-bit ADI for multicast group being queried>
  684. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  685. * <[4] 32-bit total number of known members in this multicast group>
  686. * <[2] 16-bit number of members enumerated in this packet>
  687. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  688. *
  689. * If no endpoints are known, OK and ERROR are both optional. It's okay
  690. * to return nothing in that case since gathering is "lazy."
  691. *
  692. * ERROR response payload:
  693. * <[8] 64-bit network ID>
  694. * <[6] MAC address of multicast group being queried>
  695. * <[4] 32-bit ADI for multicast group being queried>
  696. *
  697. * ERRORs are optional and are only generated if permission is denied,
  698. * certificate of membership is out of date, etc.
  699. */
  700. VERB_MULTICAST_GATHER = 13,
  701. /* Multicast frame:
  702. * <[8] 64-bit network ID>
  703. * <[1] flags>
  704. * [<[...] network certificate of membership>]
  705. * [<[4] 32-bit implicit gather limit>]
  706. * [<[6] source MAC>]
  707. * <[6] destination MAC (multicast address)>
  708. * <[4] 32-bit multicast ADI (multicast address extension)>
  709. * <[2] 16-bit ethertype>
  710. * <[...] ethernet payload>
  711. *
  712. * Flags:
  713. * 0x01 - Network certificate of membership is attached
  714. * 0x02 - Implicit gather limit field is present
  715. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  716. *
  717. * OK and ERROR responses are optional. OK may be generated if there are
  718. * implicit gather results or if the recipient wants to send its own
  719. * updated certificate of network membership to the sender. ERROR may be
  720. * generated if a certificate is needed or if multicasts to this group
  721. * are no longer wanted (multicast unsubscribe).
  722. *
  723. * OK response payload:
  724. * <[8] 64-bit network ID>
  725. * <[6] MAC address of multicast group>
  726. * <[4] 32-bit ADI for multicast group>
  727. * <[1] flags>
  728. * [<[...] network certficate of membership>]
  729. * [<[...] implicit gather results if flag 0x01 is set>]
  730. *
  731. * OK flags (same bits as request flags):
  732. * 0x01 - OK includes certificate of network membership
  733. * 0x02 - OK includes implicit gather results
  734. *
  735. * ERROR response payload:
  736. * <[8] 64-bit network ID>
  737. * <[6] multicast group MAC>
  738. * <[4] 32-bit multicast group ADI>
  739. */
  740. VERB_MULTICAST_FRAME = 14
  741. };
  742. /**
  743. * Error codes for VERB_ERROR
  744. */
  745. enum ErrorCode
  746. {
  747. /* No error, not actually used in transit */
  748. ERROR_NONE = 0,
  749. /* Invalid request */
  750. ERROR_INVALID_REQUEST = 1,
  751. /* Bad/unsupported protocol version */
  752. ERROR_BAD_PROTOCOL_VERSION = 2,
  753. /* Unknown object queried (e.g. with WHOIS) */
  754. ERROR_OBJ_NOT_FOUND = 3,
  755. /* HELLO pushed an identity whose address is already claimed */
  756. ERROR_IDENTITY_COLLISION = 4,
  757. /* Verb or use case not supported/enabled by this node */
  758. ERROR_UNSUPPORTED_OPERATION = 5,
  759. /* Message to private network rejected -- no unexpired certificate on file */
  760. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  761. /* Tried to join network, but you're not a member */
  762. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  763. /* Multicasts to this group are not wanted */
  764. ERROR_UNWANTED_MULTICAST = 8
  765. };
  766. /**
  767. * @param v Verb
  768. * @return String representation (e.g. HELLO, OK)
  769. */
  770. static const char *verbString(Verb v)
  771. throw();
  772. /**
  773. * @param e Error code
  774. * @return String error name
  775. */
  776. static const char *errorString(ErrorCode e)
  777. throw();
  778. template<unsigned int C2>
  779. Packet(const Buffer<C2> &b)
  780. throw(std::out_of_range) :
  781. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  782. {
  783. }
  784. /**
  785. * Construct a new empty packet with a unique random packet ID
  786. *
  787. * Flags and hops will be zero. Other fields and data region are undefined.
  788. * Use the header access methods (setDestination() and friends) to fill out
  789. * the header. Payload should be appended; initial size is header size.
  790. */
  791. Packet() :
  792. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  793. {
  794. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  795. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  796. }
  797. /**
  798. * Make a copy of a packet with a new initialization vector and destination address
  799. *
  800. * This can be used to take one draft prototype packet and quickly make copies to
  801. * encrypt for different destinations.
  802. *
  803. * @param prototype Prototype packet
  804. * @param dest Destination ZeroTier address for new packet
  805. */
  806. Packet(const Packet &prototype,const Address &dest) :
  807. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  808. {
  809. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  810. setDestination(dest);
  811. }
  812. /**
  813. * Construct a new empty packet with a unique random packet ID
  814. *
  815. * @param dest Destination ZT address
  816. * @param source Source ZT address
  817. * @param v Verb
  818. */
  819. Packet(const Address &dest,const Address &source,const Verb v) :
  820. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  821. {
  822. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  823. setDestination(dest);
  824. setSource(source);
  825. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  826. setVerb(v);
  827. }
  828. /**
  829. * Reset this packet structure for reuse in place
  830. *
  831. * @param dest Destination ZT address
  832. * @param source Source ZT address
  833. * @param v Verb
  834. */
  835. inline void reset(const Address &dest,const Address &source,const Verb v)
  836. {
  837. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  838. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  839. setDestination(dest);
  840. setSource(source);
  841. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  842. setVerb(v);
  843. }
  844. /**
  845. * Generate a new IV / packet ID in place
  846. *
  847. * This can be used to re-use a packet buffer multiple times to send
  848. * technically different but otherwise identical copies of the same
  849. * packet.
  850. */
  851. inline void newInitializationVector()
  852. {
  853. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  854. }
  855. /**
  856. * Set this packet's destination
  857. *
  858. * @param dest ZeroTier address of destination
  859. */
  860. inline void setDestination(const Address &dest)
  861. {
  862. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  863. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  864. d[i] = dest[i];
  865. }
  866. /**
  867. * Set this packet's source
  868. *
  869. * @param source ZeroTier address of source
  870. */
  871. inline void setSource(const Address &source)
  872. {
  873. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  874. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  875. s[i] = source[i];
  876. }
  877. /**
  878. * Get this packet's destination
  879. *
  880. * @return Destination ZT address
  881. */
  882. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  883. /**
  884. * Get this packet's source
  885. *
  886. * @return Source ZT address
  887. */
  888. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  889. /**
  890. * @return True if packet is of valid length
  891. */
  892. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  893. /**
  894. * @return True if packet is fragmented (expect fragments)
  895. */
  896. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  897. /**
  898. * Set this packet's fragmented flag
  899. *
  900. * @param f Fragmented flag value
  901. */
  902. inline void setFragmented(bool f)
  903. {
  904. if (f)
  905. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  906. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  907. }
  908. /**
  909. * @return True if compressed (result only valid if unencrypted)
  910. */
  911. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  912. /**
  913. * @return ZeroTier forwarding hops (0 to 7)
  914. */
  915. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  916. /**
  917. * Increment this packet's hop count
  918. */
  919. inline void incrementHops()
  920. {
  921. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  922. b = (b & 0xf8) | ((b + 1) & 0x07);
  923. }
  924. /**
  925. * @return Cipher suite selector: 0 - 7 (see #defines)
  926. */
  927. inline unsigned int cipher() const
  928. {
  929. //return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  930. // Use DEPRECATED 0x80 "encrypted" flag -- this will go away once there are no more <1.0.0 peers on the net
  931. return (((*this)[ZT_PACKET_IDX_FLAGS] & 0x80) == 0) ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012;
  932. }
  933. /**
  934. * Set this packet's cipher suite
  935. *
  936. * This normally shouldn't be called directly as armor() will set it after
  937. * encrypting and MACing the packet.
  938. */
  939. inline void setCipher(unsigned int c)
  940. {
  941. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  942. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38);
  943. // Set both the new cipher suite spec field and the old DEPRECATED "encrypted" flag as long as there's <1.0.0 peers online
  944. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  945. b |= 0x80;
  946. else b &= 0x7f;
  947. }
  948. /**
  949. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  950. *
  951. * @return Packet ID
  952. */
  953. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  954. /**
  955. * Set packet verb
  956. *
  957. * This also has the side-effect of clearing any verb flags, such as
  958. * compressed, and so must only be done during packet composition.
  959. *
  960. * @param v New packet verb
  961. */
  962. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  963. /**
  964. * @return Packet verb (not including flag bits)
  965. */
  966. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  967. /**
  968. * @return Length of packet payload
  969. */
  970. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  971. /**
  972. * @return Raw packet payload
  973. */
  974. inline const unsigned char *payload() const
  975. {
  976. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  977. }
  978. /**
  979. * Armor packet for transport
  980. *
  981. * @param key 32-byte key
  982. * @param encryptPayload If true, encrypt packet payload, else just MAC
  983. */
  984. inline void armor(const void *key,bool encryptPayload)
  985. {
  986. unsigned char mangledKey[32];
  987. unsigned char macKey[32];
  988. unsigned char mac[16];
  989. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  990. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  991. // Set flag now, since it affects key mangle function
  992. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  993. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  994. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  995. // MAC key is always the first 32 bytes of the Salsa20 key stream
  996. // This is the same construction DJB's NaCl library uses
  997. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  998. if (encryptPayload)
  999. s20.encrypt(payload,payload,payloadLen);
  1000. Poly1305::compute(mac,payload,payloadLen,macKey);
  1001. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  1002. }
  1003. /**
  1004. * Verify and (if encrypted) decrypt packet
  1005. *
  1006. * @param key 32-byte key
  1007. * @return False if packet is invalid or failed MAC authenticity check
  1008. */
  1009. inline bool dearmor(const void *key)
  1010. {
  1011. unsigned char mangledKey[32];
  1012. unsigned char macKey[32];
  1013. unsigned char mac[16];
  1014. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  1015. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  1016. unsigned int cs = cipher();
  1017. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  1018. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  1019. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  1020. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  1021. Poly1305::compute(mac,payload,payloadLen,macKey);
  1022. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  1023. return false;
  1024. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1025. s20.decrypt(payload,payload,payloadLen);
  1026. return true;
  1027. } else if (cs == ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM) {
  1028. return false; // not implemented yet
  1029. } else return false; // unrecognized cipher suite
  1030. }
  1031. /**
  1032. * Attempt to compress payload if not already (must be unencrypted)
  1033. *
  1034. * This requires that the payload at least contain the verb byte already
  1035. * set. The compressed flag in the verb is set if compression successfully
  1036. * results in a size reduction. If no size reduction occurs, compression
  1037. * is not done and the flag is left cleared.
  1038. *
  1039. * @return True if compression occurred
  1040. */
  1041. inline bool compress()
  1042. {
  1043. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  1044. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  1045. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  1046. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  1047. if ((cl > 0)&&(cl < pl)) {
  1048. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  1049. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  1050. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  1051. return true;
  1052. }
  1053. }
  1054. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1055. return false;
  1056. }
  1057. /**
  1058. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1059. *
  1060. * If payload is compressed, it is decompressed and the compressed verb
  1061. * flag is cleared. Otherwise nothing is done and true is returned.
  1062. *
  1063. * @return True if data is now decompressed and valid, false on error
  1064. */
  1065. inline bool uncompress()
  1066. {
  1067. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  1068. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  1069. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1070. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1071. int ucl = LZ4_decompress_safe((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  1072. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1073. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1074. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  1075. } else return false;
  1076. }
  1077. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1078. }
  1079. return true;
  1080. }
  1081. private:
  1082. static const unsigned char ZERO_KEY[32];
  1083. /**
  1084. * Deterministically mangle a 256-bit crypto key based on packet
  1085. *
  1086. * This uses extra data from the packet to mangle the secret, giving us an
  1087. * effective IV that is somewhat more than 64 bits. This is "free" for
  1088. * Salsa20 since it has negligible key setup time so using a different
  1089. * key each time is fine.
  1090. *
  1091. * @param in Input key (32 bytes)
  1092. * @param out Output buffer (32 bytes)
  1093. */
  1094. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1095. {
  1096. const unsigned char *d = (const unsigned char *)data();
  1097. // IV and source/destination addresses. Using the addresses divides the
  1098. // key space into two halves-- A->B and B->A (since order will change).
  1099. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1100. out[i] = in[i] ^ d[i];
  1101. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1102. // nodes. It's one of the only parts of a packet modifiable by people
  1103. // without the key.
  1104. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1105. // Raw packet size in bytes -- thus each packet size defines a new
  1106. // key space.
  1107. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1108. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1109. // Rest of raw key is used unchanged
  1110. for(unsigned int i=21;i<32;++i)
  1111. out[i] = in[i];
  1112. }
  1113. };
  1114. } // namespace ZeroTier
  1115. #endif