Packet.hpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 "HMAC.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
  43. *
  44. * 1 - 0.2.0 ... 0.2.5
  45. * 2 - 0.3.0 ...
  46. * * Added signature and originating peer to multicast frame
  47. * * Double size of multicast frame bloom filter
  48. */
  49. #define ZT_PROTO_VERSION 2
  50. /**
  51. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  52. *
  53. * This is not necessarily the maximum hop counter after which
  54. * relaying is no longer performed.
  55. */
  56. #define ZT_PROTO_MAX_HOPS 7
  57. /**
  58. * Header flag indicating that a packet is encrypted with Salsa20
  59. *
  60. * If this is not set, then the packet's payload is in the clear and the
  61. * HMAC is over this (since there is no ciphertext). Otherwise the HMAC is
  62. * of the ciphertext after encryption.
  63. */
  64. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  65. /**
  66. * Header flag indicating that a packet is fragmented
  67. *
  68. * If this flag is set, the receiver knows to expect more than one fragment.
  69. * See Packet::Fragment for details.
  70. */
  71. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  72. /**
  73. * Verb flag indicating payload is compressed with LZ4
  74. */
  75. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  76. // Indices of fields in normal packet header -- do not change as this
  77. // might require both code rework and will break compatibility.
  78. #define ZT_PACKET_IDX_IV 0
  79. #define ZT_PACKET_IDX_DEST 8
  80. #define ZT_PACKET_IDX_SOURCE 13
  81. #define ZT_PACKET_IDX_FLAGS 18
  82. #define ZT_PACKET_IDX_HMAC 19
  83. #define ZT_PACKET_IDX_VERB 27
  84. #define ZT_PACKET_IDX_PAYLOAD 28
  85. /**
  86. * ZeroTier packet buffer size
  87. *
  88. * This can be changed. This provides enough room for MTU-size packet
  89. * payloads plus some overhead. The subtraction of sizeof(unsigned int)
  90. * makes it an even multiple of 1024 (see Buffer), which might reduce
  91. * memory use a little.
  92. */
  93. #define ZT_PROTO_MAX_PACKET_LENGTH (3072 - sizeof(unsigned int))
  94. /**
  95. * Minimum viable packet length (also length of header)
  96. */
  97. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  98. // Indexes of fields in fragment header -- also can't be changed without
  99. // breaking compatibility.
  100. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  101. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  102. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  103. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  104. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  105. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  106. /**
  107. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  108. */
  109. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  110. /**
  111. * Minimum viable fragment length
  112. */
  113. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  114. // Size of bloom filter used in multicast propagation
  115. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS 512
  116. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES 64
  117. // Field incides for parsing verbs
  118. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  119. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  120. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  121. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  122. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  123. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  124. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  125. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  126. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  127. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  128. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  129. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  130. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  131. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  132. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  133. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  134. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  135. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  136. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  137. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  138. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  139. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  140. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  141. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  142. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS + 5)
  143. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC + 6)
  144. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC + 6)
  145. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM_FILTER (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI + 4)
  146. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM_FILTER + 64)
  147. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT + 1)
  148. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD_LENGTH (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  149. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SIGNATURE_LENGTH (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD_LENGTH + 2)
  150. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SIGNATURE_LENGTH + 2)
  151. // Field indices for parsing OK and ERROR payloads of replies
  152. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  153. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  154. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  155. namespace ZeroTier {
  156. /**
  157. * ZeroTier packet
  158. *
  159. * Packet format:
  160. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  161. * <[5] destination ZT address>
  162. * <[5] source ZT address>
  163. * <[1] flags (LS 5 bits) and ZT hop count (MS 3 bits)>
  164. * <[8] first 8 bytes of 32-byte HMAC-SHA-256 MAC>
  165. * [... -- begin encryption envelope -- ...]
  166. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  167. * [... verb-specific payload ...]
  168. *
  169. * Packets smaller than 28 bytes are invalid and silently discarded.
  170. *
  171. * MAC is computed on ciphertext *after* encryption. See also:
  172. *
  173. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  174. *
  175. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  176. * sent in the clear, as it's the "here is my public key" message.
  177. */
  178. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  179. {
  180. public:
  181. /**
  182. * A packet fragment
  183. *
  184. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  185. * is sent with its normal header with the fragmented flag set. Remaining
  186. * fragments are sent this way.
  187. *
  188. * The fragmented bit indicates that there is at least one fragment. Fragments
  189. * themselves contain the total, so the receiver must "learn" this from the
  190. * first fragment it receives.
  191. *
  192. * Fragments are sent with the following format:
  193. * <[8] packet ID of packet whose fragment this belongs to>
  194. * <[5] destination ZT address>
  195. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  196. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  197. * <[1] ZT hop count>
  198. * <[...] fragment data>
  199. *
  200. * The protocol supports a maximum of 16 fragments. If a fragment is received
  201. * before its main packet header, it should be cached for a brief period of
  202. * time to see if its parent arrives. Loss of any fragment constitutes packet
  203. * loss; there is no retransmission mechanism. The receiver must wait for full
  204. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  205. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  206. */
  207. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  208. {
  209. public:
  210. Fragment() :
  211. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  212. {
  213. }
  214. template<unsigned int C2>
  215. Fragment(const Buffer<C2> &b)
  216. throw(std::out_of_range) :
  217. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  218. {
  219. }
  220. /**
  221. * Initialize from a packet
  222. *
  223. * @param p Original assembled packet
  224. * @param fragStart Start of fragment (raw index in packet data)
  225. * @param fragLen Length of fragment in bytes
  226. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  227. * @param fragTotal Total number of fragments (including 0)
  228. * @throws std::out_of_range Packet size would exceed buffer
  229. */
  230. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  231. throw(std::out_of_range)
  232. {
  233. init(p,fragStart,fragLen,fragNo,fragTotal);
  234. }
  235. /**
  236. * Initialize from a packet
  237. *
  238. * @param p Original assembled packet
  239. * @param fragStart Start of fragment (raw index in packet data)
  240. * @param fragLen Length of fragment in bytes
  241. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  242. * @param fragTotal Total number of fragments (including 0)
  243. * @throws std::out_of_range Packet size would exceed buffer
  244. */
  245. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  246. throw(std::out_of_range)
  247. {
  248. if ((fragStart + fragLen) > p.size())
  249. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  250. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  251. // NOTE: this copies both the IV/packet ID and the destination address.
  252. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.data() + ZT_PACKET_IDX_IV,13);
  253. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  254. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  255. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  256. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.data() + fragStart,fragLen);
  257. }
  258. /**
  259. * Get this fragment's destination
  260. *
  261. * @return Destination ZT address
  262. */
  263. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  264. /**
  265. * @return True if fragment is of a valid length
  266. */
  267. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  268. /**
  269. * @return ID of packet this is a fragment of
  270. */
  271. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  272. /**
  273. * @return Total number of fragments in packet
  274. */
  275. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  276. /**
  277. * @return Fragment number of this fragment
  278. */
  279. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  280. /**
  281. * @return Fragment ZT hop count
  282. */
  283. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  284. /**
  285. * Increment this packet's hop count
  286. */
  287. inline void incrementHops()
  288. {
  289. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  290. }
  291. /**
  292. * @return Length of payload in bytes
  293. */
  294. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  295. /**
  296. * @return Raw packet payload
  297. */
  298. inline const unsigned char *payload() const
  299. {
  300. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  301. }
  302. };
  303. /**
  304. * ZeroTier protocol verbs
  305. */
  306. enum Verb /* Max value: 32 (5 bits) */
  307. {
  308. /* No operation, payload ignored, no reply */
  309. VERB_NOP = 0,
  310. /* Announcement of a node's existence:
  311. * <[1] protocol version>
  312. * <[1] software major version>
  313. * <[1] software minor version>
  314. * <[2] software revision>
  315. * <[8] timestamp (ms since epoch)>
  316. * <[...] binary serialized identity (see Identity)>
  317. *
  318. * OK payload:
  319. * <[8] timestamp (echoed from original HELLO)>
  320. *
  321. * ERROR has no payload.
  322. */
  323. VERB_HELLO = 1,
  324. /* Error response:
  325. * <[1] in-re verb>
  326. * <[8] in-re packet ID>
  327. * <[1] error code>
  328. * <[...] error-dependent payload>
  329. */
  330. VERB_ERROR = 2,
  331. /* Success response:
  332. * <[1] in-re verb>
  333. * <[8] in-re packet ID>
  334. * <[...] request-specific payload>
  335. */
  336. VERB_OK = 3,
  337. /* Query an identity by address:
  338. * <[5] address to look up>
  339. *
  340. * OK response payload:
  341. * <[...] binary serialized identity>
  342. *
  343. * Error payload will be address queried.
  344. */
  345. VERB_WHOIS = 4,
  346. /* Meet another node at a given protocol address:
  347. * <[5] ZeroTier address of peer that might be found at this address>
  348. * <[2] 16-bit protocol address port>
  349. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  350. * <[...] protocol address (network byte order)>
  351. *
  352. * This is sent by a relaying node to initiate NAT traversal between two
  353. * peers that are communicating by way of indirect relay. The relay will
  354. * send this to both peers at the same time on a periodic basis, telling
  355. * each where it might find the other on the network.
  356. *
  357. * Upon receipt, a peer sends a message such as NOP or HELLO to the other
  358. * peer. Peers only "learn" one anothers' direct addresses when they
  359. * successfully *receive* a message and authenticate it. Optionally, peers
  360. * will usually preface these messages with one or more firewall openers
  361. * to clear the path.
  362. *
  363. * Nodes should implement rate control, limiting the rate at which they
  364. * respond to these packets to prevent their use in DDOS attacks. Nodes
  365. * may also ignore these messages if a peer is not known or is not being
  366. * actively communicated with.
  367. *
  368. * No OK or ERROR is generated.
  369. */
  370. VERB_RENDEZVOUS = 5,
  371. /* A ZT-to-ZT unicast ethernet frame:
  372. * <[8] 64-bit network ID>
  373. * <[2] 16-bit ethertype>
  374. * <[...] ethernet payload>
  375. *
  376. * MAC addresses are derived from the packet's source and destination
  377. * ZeroTier addresses. ZeroTier does not support VLANs or other extensions
  378. * beyond core Ethernet.
  379. *
  380. * No OK or ERROR is generated.
  381. */
  382. VERB_FRAME = 6,
  383. /* 7 - old VERB_MULTICAST_FRAME, might be reused once all old 0.2
  384. * clients are off the net. */
  385. /* Announce interest in multicast group(s):
  386. * <[8] 64-bit network ID>
  387. * <[6] multicast Ethernet address>
  388. * <[4] multicast additional distinguishing information (ADI)>
  389. * [... additional tuples of network/address/adi ...]
  390. *
  391. * OK is generated on successful receipt.
  392. */
  393. VERB_MULTICAST_LIKE = 8,
  394. /* A multicast frame:
  395. * <[1] flags, currently unused and must be 0>
  396. * <[8] 64-bit network ID>
  397. * <[5] ZeroTier address of original submitter of this multicast>
  398. * <[6] source MAC address>
  399. * <[6] destination multicast Ethernet address>
  400. * <[4] multicast additional distinguishing information (ADI)>
  401. * <[64] multicast propagation bloom filter>
  402. * <[1] 8-bit propagation hop count>
  403. * <[2] 16-bit ethertype>
  404. * <[2] 16-bit length of payload>
  405. * <[2] 16-bit length of signature>
  406. * <[...] ethernet payload>
  407. * <[...] ECDSA signature of SHA-256 hash (see below)>
  408. *
  409. * The signature is made using the key of the original submitter, and
  410. * can be used to authenticate the submitter for security and rate
  411. * control purposes. Fields in the signature are: network ID, source
  412. * MAC, destination MAC, multicast ADI, ethertype, and payload. All
  413. * integers are hashed in big-endian byte order. A zero byte is added
  414. * to the hash between each field.
  415. *
  416. * In the future flags could indicate additional fields appended to the
  417. * end or a different signature algorithm.
  418. *
  419. * No OK or ERROR is generated.
  420. */
  421. VERB_MULTICAST_FRAME = 9,
  422. /* Network member certificate for sending peer:
  423. * <[8] 64-bit network ID>
  424. * <[2] 16-bit length of certificate>
  425. * <[2] 16-bit length of signature>
  426. * <[...] string-serialized certificate dictionary>
  427. * <[...] ECDSA signature of certificate>
  428. *
  429. * OK is generated on acceptance. ERROR is returned on failure. In both
  430. * cases the payload is the network ID.
  431. */
  432. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  433. /* Network configuration request:
  434. * <[8] 64-bit network ID>
  435. * <[2] 16-bit length of request meta-data dictionary>
  436. * <[...] string-serialized request meta-data>
  437. *
  438. * This message requests network configuration from a node capable of
  439. * providing it. Such nodes run the netconf service, which must be
  440. * installed into the ZeroTier home directory.
  441. *
  442. * OK response payload:
  443. * <[8] 64-bit network ID>
  444. * <[2] 16-bit length of network configuration dictionary>
  445. * <[...] network configuration dictionary>
  446. *
  447. * OK returns a Dictionary (string serialized) containing the network's
  448. * configuration and IP address assignment information for the querying
  449. * node. It also contains a membership certificate that the querying
  450. * node can push to other peers to demonstrate its right to speak on
  451. * a given network.
  452. *
  453. * ERROR may be NOT_FOUND if no such network is known, or
  454. * UNSUPPORTED_OPERATION if the netconf service isn't available. The
  455. * payload will be the network ID.
  456. */
  457. VERB_NETWORK_CONFIG_REQUEST = 11,
  458. /* Network configuration refresh request:
  459. * <[8] 64-bit network ID>
  460. *
  461. * This message can be sent by the network configuration master node
  462. * to request that nodes refresh their network configuration. It can
  463. * thus be used to "push" updates.
  464. *
  465. * It does not generate an OK or ERROR message, and is treated only as
  466. * a hint to refresh now.
  467. */
  468. VERB_NETWORK_CONFIG_REFRESH = 12
  469. };
  470. /**
  471. * Error codes for VERB_ERROR
  472. */
  473. enum ErrorCode
  474. {
  475. /* No error, not actually used in transit */
  476. ERROR_NONE = 0,
  477. /* Invalid request */
  478. ERROR_INVALID_REQUEST = 1,
  479. /* Bad/unsupported protocol version */
  480. ERROR_BAD_PROTOCOL_VERSION = 2,
  481. /* Unknown object queried (e.g. with WHOIS) */
  482. ERROR_NOT_FOUND = 3,
  483. /* HELLO pushed an identity whose address is already claimed */
  484. ERROR_IDENTITY_COLLISION = 4,
  485. /* Identity was not valid */
  486. ERROR_IDENTITY_INVALID = 5,
  487. /* Verb or use case not supported/enabled by this node */
  488. ERROR_UNSUPPORTED_OPERATION = 6,
  489. /* Message to private network rejected -- no unexpired certificate on file */
  490. ERROR_NO_MEMBER_CERTIFICATE = 7
  491. };
  492. /**
  493. * @param v Verb
  494. * @return String representation (e.g. HELLO, OK)
  495. */
  496. static const char *verbString(Verb v)
  497. throw();
  498. /**
  499. * @param e Error code
  500. * @return String error name
  501. */
  502. static const char *errorString(ErrorCode e)
  503. throw();
  504. template<unsigned int C2>
  505. Packet(const Buffer<C2> &b)
  506. throw(std::out_of_range) :
  507. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  508. {
  509. }
  510. /**
  511. * Construct a new empty packet with a unique random packet ID
  512. *
  513. * Flags and hops will be zero. Other fields and data region are undefined.
  514. * Use the header access methods (setDestination() and friends) to fill out
  515. * the header. Payload should be appended; initial size is header size.
  516. */
  517. Packet() :
  518. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  519. {
  520. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  521. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  522. }
  523. /**
  524. * Construct a new empty packet with a unique random packet ID
  525. *
  526. * @param dest Destination ZT address
  527. * @param source Source ZT address
  528. * @param v Verb
  529. */
  530. Packet(const Address &dest,const Address &source,const Verb v) :
  531. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  532. {
  533. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  534. setDestination(dest);
  535. setSource(source);
  536. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  537. setVerb(v);
  538. }
  539. /**
  540. * Reset this packet structure for reuse in place
  541. *
  542. * @param dest Destination ZT address
  543. * @param source Source ZT address
  544. * @param v Verb
  545. */
  546. inline void reset(const Address &dest,const Address &source,const Verb v)
  547. {
  548. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  549. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  550. setDestination(dest);
  551. setSource(source);
  552. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  553. setVerb(v);
  554. }
  555. /**
  556. * Generate a new IV / packet ID in place
  557. *
  558. * This can be used to re-use a packet buffer multiple times to send
  559. * technically different but otherwise identical copies of the same
  560. * packet.
  561. */
  562. inline void newInitializationVector()
  563. {
  564. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  565. }
  566. /**
  567. * Set this packet's destination
  568. *
  569. * @param dest ZeroTier address of destination
  570. */
  571. inline void setDestination(const Address &dest)
  572. {
  573. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  574. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  575. d[i] = dest[i];
  576. }
  577. /**
  578. * Set this packet's source
  579. *
  580. * @param source ZeroTier address of source
  581. */
  582. inline void setSource(const Address &source)
  583. {
  584. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  585. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  586. s[i] = source[i];
  587. }
  588. /**
  589. * Get this packet's destination
  590. *
  591. * @return Destination ZT address
  592. */
  593. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  594. /**
  595. * Get this packet's source
  596. *
  597. * @return Source ZT address
  598. */
  599. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  600. /**
  601. * @return True if packet is of valid length
  602. */
  603. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  604. /**
  605. * @return True if packet is encrypted
  606. */
  607. inline bool encrypted() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_ENCRYPTED)); }
  608. /**
  609. * @return True if packet is fragmented (expect fragments)
  610. */
  611. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED)); }
  612. /**
  613. * Set this packet's fragmented flag
  614. *
  615. * @param f Fragmented flag value
  616. */
  617. inline void setFragmented(bool f)
  618. {
  619. if (f)
  620. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  621. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  622. }
  623. /**
  624. * @return True if compressed (result only valid if unencrypted)
  625. */
  626. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED)); }
  627. /**
  628. * @return ZeroTier forwarding hops (0 to 7)
  629. */
  630. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  631. /**
  632. * Increment this packet's hop count
  633. */
  634. inline void incrementHops()
  635. {
  636. (*this)[ZT_PACKET_IDX_FLAGS] = (char)((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8) | (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] + 1) & 0x07);
  637. }
  638. /**
  639. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  640. *
  641. * @return Packet ID
  642. */
  643. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  644. /**
  645. * Set packet verb
  646. *
  647. * This also has the side-effect of clearing any verb flags, such as
  648. * compressed, and so must only be done during packet composition.
  649. *
  650. * @param v New packet verb
  651. */
  652. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  653. /**
  654. * @return Packet verb (not including flag bits)
  655. */
  656. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  657. /**
  658. * @return Length of packet payload
  659. */
  660. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  661. /**
  662. * @return Raw packet payload
  663. */
  664. inline const unsigned char *payload() const
  665. {
  666. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  667. }
  668. /**
  669. * Compute the HMAC of this packet's payload and set HMAC field
  670. *
  671. * For encrypted packets, this must be called after encryption.
  672. *
  673. * @param key 256-bit (32 byte) key
  674. */
  675. inline void hmacSet(const void *key)
  676. {
  677. unsigned char mac[32];
  678. unsigned char key2[32];
  679. _mangleKey((const unsigned char *)key,key2);
  680. unsigned int hmacLen = (size() >= ZT_PACKET_IDX_VERB) ? (size() - ZT_PACKET_IDX_VERB) : 0;
  681. HMAC::sha256(key2,sizeof(key2),field(ZT_PACKET_IDX_VERB,hmacLen),hmacLen,mac);
  682. memcpy(field(ZT_PACKET_IDX_HMAC,8),mac,8);
  683. }
  684. /**
  685. * Check the HMAC of this packet's payload
  686. *
  687. * For encrypted packets, this must be checked before decryption.
  688. *
  689. * @param key 256-bit (32 byte) key
  690. */
  691. inline bool hmacVerify(const void *key) const
  692. {
  693. unsigned char mac[32];
  694. unsigned char key2[32];
  695. if (size() < ZT_PACKET_IDX_VERB)
  696. return false; // incomplete packets fail
  697. _mangleKey((const unsigned char *)key,key2);
  698. unsigned int hmacLen = size() - ZT_PACKET_IDX_VERB;
  699. HMAC::sha256(key2,sizeof(key2),field(ZT_PACKET_IDX_VERB,hmacLen),hmacLen,mac);
  700. return (!memcmp(field(ZT_PACKET_IDX_HMAC,8),mac,8));
  701. }
  702. /**
  703. * Encrypt this packet
  704. *
  705. * @param key 256-bit (32 byte) key
  706. */
  707. inline void encrypt(const void *key)
  708. {
  709. (*this)[ZT_PACKET_IDX_FLAGS] |= ZT_PROTO_FLAG_ENCRYPTED;
  710. unsigned char key2[32];
  711. if (size() >= ZT_PACKET_IDX_VERB) {
  712. _mangleKey((const unsigned char *)key,key2);
  713. Salsa20 s20(key2,256,field(ZT_PACKET_IDX_IV,8));
  714. unsigned int encLen = size() - ZT_PACKET_IDX_VERB;
  715. unsigned char *const encBuf = field(ZT_PACKET_IDX_VERB,encLen);
  716. s20.encrypt(encBuf,encBuf,encLen);
  717. }
  718. }
  719. /**
  720. * Decrypt this packet
  721. *
  722. * @param key 256-bit (32 byte) key
  723. */
  724. inline void decrypt(const void *key)
  725. {
  726. unsigned char key2[32];
  727. if (size() >= ZT_PACKET_IDX_VERB) {
  728. _mangleKey((const unsigned char *)key,key2);
  729. Salsa20 s20(key2,256,field(ZT_PACKET_IDX_IV,8));
  730. unsigned int decLen = size() - ZT_PACKET_IDX_VERB;
  731. unsigned char *const decBuf = field(ZT_PACKET_IDX_VERB,decLen);
  732. s20.decrypt(decBuf,decBuf,decLen);
  733. }
  734. (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_ENCRYPTED);
  735. }
  736. /**
  737. * Attempt to compress payload if not already (must be unencrypted)
  738. *
  739. * This requires that the payload at least contain the verb byte already
  740. * set. The compressed flag in the verb is set if compression successfully
  741. * results in a size reduction. If no size reduction occurs, compression
  742. * is not done and the flag is left cleared.
  743. *
  744. * @return True if compression occurred
  745. */
  746. inline bool compress()
  747. {
  748. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  749. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  750. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  751. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  752. if ((cl > 0)&&(cl < pl)) {
  753. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  754. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  755. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  756. return true;
  757. }
  758. }
  759. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  760. return false;
  761. }
  762. /**
  763. * Attempt to decompress payload if it is compressed (must be unencrypted)
  764. *
  765. * If payload is compressed, it is decompressed and the compressed verb
  766. * flag is cleared. Otherwise nothing is done and true is returned.
  767. *
  768. * @return True if data is now decompressed and valid, false on error
  769. */
  770. inline bool uncompress()
  771. {
  772. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  773. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  774. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  775. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  776. int ucl = LZ4_uncompress_unknownOutputSize((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  777. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  778. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  779. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  780. } else return false;
  781. }
  782. (*this)[ZT_PACKET_IDX_VERB] &= ~ZT_PROTO_VERB_FLAG_COMPRESSED;
  783. }
  784. return true;
  785. }
  786. private:
  787. /**
  788. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  789. *
  790. * This takes the static agreed-upon input key and mangles it using
  791. * info from the packet. This serves two purposes:
  792. *
  793. * (1) It reduces the (already minute) probability of a duplicate key /
  794. * IV combo, which is good since keys are extremely long-lived. Another
  795. * way of saying this is that it increases the effective IV size by
  796. * using other parts of the packet as IV material.
  797. * (2) It causes HMAC to fail should any of the following change: ordering
  798. * of source and dest addresses, flags, IV, or packet size. HMAC has
  799. * no explicit scheme for AAD (additional authenticated data).
  800. *
  801. * NOTE: this function will have to be changed if the order of any packet
  802. * fields or their sizes/padding changes in the spec.
  803. *
  804. * @param in Input key (32 bytes)
  805. * @param out Output buffer (32 bytes)
  806. */
  807. inline void _mangleKey(const unsigned char *in,unsigned char *out) const
  808. {
  809. // Random IV (Salsa20 also uses the IV natively, but HMAC doesn't), and
  810. // destination and source addresses. Using dest and source addresses
  811. // gives us a (likely) different key space for a->b vs b->a.
  812. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  813. out[i] = in[i] ^ (unsigned char)(*this)[i];
  814. // Flags, but masking off hop count which is altered by forwarding nodes
  815. out[18] = in[18] ^ ((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8);
  816. // Raw packet size in bytes -- each raw packet size defines a possibly
  817. // different space of keys.
  818. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  819. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  820. // Rest of raw key is used unchanged
  821. for(unsigned int i=21;i<32;++i)
  822. out[i] = in[i];
  823. }
  824. };
  825. } // namespace ZeroTier
  826. #endif