Packet.hpp 38 KB

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