Packet.hpp 41 KB

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