Packet.hpp 27 KB

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