Packet.hpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 "Constants.hpp"
  35. #include "Address.hpp"
  36. #include "Poly1305.hpp"
  37. #include "Salsa20.hpp"
  38. #include "Utils.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 ... CURRENT
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  58. /**
  59. * Minimum supported protocol version
  60. */
  61. #define ZT_PROTO_VERSION_MIN 4
  62. /**
  63. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  64. *
  65. * This is not necessarily the maximum hop counter after which
  66. * relaying is no longer performed.
  67. */
  68. #define ZT_PROTO_MAX_HOPS 7
  69. /**
  70. * Cipher suite: Curve25519/Poly1305/Salsa20/12 without payload encryption
  71. *
  72. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  73. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  74. * but the payload is not encrypted. This is currently only used to send
  75. * HELLO since that's the public key specification packet and must be
  76. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  77. * curve Diffie-Hellman.
  78. */
  79. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  80. /**
  81. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  82. *
  83. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  84. * stream as its one-time-use key followed by payload encryption with
  85. * the remaining Salsa20/12 key stream. Key agreement is performed using
  86. * Curve25519 elliptic curve Diffie-Hellman.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  89. /**
  90. * Cipher suite: PFS negotiated ephemeral cipher suite and authentication
  91. *
  92. * This message is encrypted with the latest negotiated ephemeral (PFS)
  93. * key pair and cipher suite. If authentication fails, VERB_SET_EPHEMERAL_KEY
  94. * may be sent to renegotiate ephemeral keys. To prevent attacks, this
  95. * attempted renegotiation should be limited to some sane rate such as
  96. * once per second.
  97. */
  98. #define ZT_PROTO_CIPHER_SUITE__EPHEMERAL 7
  99. /**
  100. * DEPRECATED payload encrypted flag, will be removed for re-use soon.
  101. *
  102. * This has been replaced by the two-bit cipher suite selection field where
  103. * a value of 0 indicated unencrypted (but authenticated) messages.
  104. */
  105. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  106. /**
  107. * Header flag indicating that a packet is fragmented
  108. *
  109. * If this flag is set, the receiver knows to expect more than one fragment.
  110. * See Packet::Fragment for details.
  111. */
  112. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  113. /**
  114. * Verb flag indicating payload is compressed with LZ4
  115. */
  116. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  117. /**
  118. * Rounds used for Salsa20 encryption in ZT
  119. */
  120. #define ZT_PROTO_SALSA20_ROUNDS 12
  121. // Indices of fields in normal packet header -- do not change as this
  122. // might require both code rework and will break compatibility.
  123. #define ZT_PACKET_IDX_IV 0
  124. #define ZT_PACKET_IDX_DEST 8
  125. #define ZT_PACKET_IDX_SOURCE 13
  126. #define ZT_PACKET_IDX_FLAGS 18
  127. #define ZT_PACKET_IDX_MAC 19
  128. #define ZT_PACKET_IDX_VERB 27
  129. #define ZT_PACKET_IDX_PAYLOAD 28
  130. /**
  131. * Packet buffer size (can be changed)
  132. */
  133. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  134. /**
  135. * Minimum viable packet length (also length of header)
  136. */
  137. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  138. // Indexes of fields in fragment header -- also can't be changed without
  139. // breaking compatibility.
  140. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  141. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  142. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  143. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  144. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  145. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  146. /**
  147. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  148. */
  149. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  150. /**
  151. * Minimum viable fragment length
  152. */
  153. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  154. /**
  155. * Length of LAN beacon packets
  156. */
  157. #define ZT_PROTO_BEACON_LENGTH 13
  158. /**
  159. * Index of address in a LAN beacon
  160. */
  161. #define ZT_PROTO_BEACON_IDX_ADDRESS 8
  162. // Destination address types from HELLO and OK(HELLO)
  163. #define ZT_PROTO_DEST_ADDRESS_TYPE_NONE 0
  164. #define ZT_PROTO_DEST_ADDRESS_TYPE_ETHERNET 1
  165. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV4 4
  166. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV6 6
  167. // Ephemeral key record flags
  168. #define ZT_PROTO_EPHEMERAL_KEY_FLAG_FIPS 0x01
  169. // Ephemeral key record symmetric cipher types
  170. #define ZT_PROTO_EPHEMERAL_KEY_SYMMETRIC_CIPHER_SALSA2012_POLY1305 0x01
  171. #define ZT_PROTO_EPHEMERAL_KEY_SYMMETRIC_CIPHER_AES256_GCM 0x02
  172. // Ephemeral key record public key types
  173. #define ZT_PROTO_EPHEMERAL_KEY_PK_C25519 0x01
  174. #define ZT_PROTO_EPHEMERAL_KEY_PK_NISTP256 0x02
  175. // Field incides for parsing verbs -------------------------------------------
  176. // Some verbs have variable-length fields. Those aren't fully defined here
  177. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  178. // See their respective handler functions.
  179. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  180. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  181. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  182. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  183. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  184. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  185. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  186. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  187. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  188. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  189. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  190. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  191. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  192. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  193. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  194. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  195. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  196. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  197. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  198. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  199. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  200. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  201. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  202. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  203. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  204. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  205. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  206. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  207. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  208. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  209. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  210. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  211. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  212. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  213. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  214. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  215. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  216. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  217. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  218. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  219. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  220. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  221. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  222. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  223. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  224. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  225. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  226. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  227. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  228. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  229. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  230. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  231. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  232. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  233. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  234. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  235. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  236. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  237. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  238. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  239. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  240. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  241. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  242. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  243. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  244. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  245. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  246. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  247. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  248. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  249. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  250. // ---------------------------------------------------------------------------
  251. namespace ZeroTier {
  252. /**
  253. * ZeroTier packet
  254. *
  255. * Packet format:
  256. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  257. * <[5] destination ZT address>
  258. * <[5] source ZT address>
  259. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  260. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  261. * [... -- begin encryption envelope -- ...]
  262. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  263. * [... verb-specific payload ...]
  264. *
  265. * Packets smaller than 28 bytes are invalid and silently discarded.
  266. *
  267. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  268. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  269. * and H is hop count.
  270. *
  271. * The three-bit hop count is the only part of a packet that is mutable in
  272. * transit without invalidating the MAC. All other bits in the packet are
  273. * immutable. This is because intermediate nodes can increment the hop
  274. * count up to 7 (protocol max).
  275. *
  276. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  277. *
  278. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  279. * sent in the clear, as it's the "here is my public key" message.
  280. *
  281. * Beacon format and beacon packets:
  282. * <[8] 8 random bytes>
  283. * <[5] sender ZT address>
  284. *
  285. * A beacon is a 13-byte packet containing only the address of the sender.
  286. * Receiving peers may or may not respond to beacons with a HELLO or other
  287. * message to initiate direct communication.
  288. *
  289. * Beacons may be used for direct LAN announcement or NAT traversal.
  290. */
  291. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  292. {
  293. public:
  294. /**
  295. * A packet fragment
  296. *
  297. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  298. * is sent with its normal header with the fragmented flag set. Remaining
  299. * fragments are sent this way.
  300. *
  301. * The fragmented bit indicates that there is at least one fragment. Fragments
  302. * themselves contain the total, so the receiver must "learn" this from the
  303. * first fragment it receives.
  304. *
  305. * Fragments are sent with the following format:
  306. * <[8] packet ID of packet whose fragment this belongs to>
  307. * <[5] destination ZT address>
  308. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  309. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  310. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  311. * <[...] fragment data>
  312. *
  313. * The protocol supports a maximum of 16 fragments. If a fragment is received
  314. * before its main packet header, it should be cached for a brief period of
  315. * time to see if its parent arrives. Loss of any fragment constitutes packet
  316. * loss; there is no retransmission mechanism. The receiver must wait for full
  317. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  318. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  319. */
  320. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  321. {
  322. public:
  323. Fragment() :
  324. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  325. {
  326. }
  327. template<unsigned int C2>
  328. Fragment(const Buffer<C2> &b)
  329. throw(std::out_of_range) :
  330. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  331. {
  332. }
  333. Fragment(const void *data,unsigned int len) :
  334. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  335. {
  336. }
  337. /**
  338. * Initialize from a packet
  339. *
  340. * @param p Original assembled packet
  341. * @param fragStart Start of fragment (raw index in packet data)
  342. * @param fragLen Length of fragment in bytes
  343. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  344. * @param fragTotal Total number of fragments (including 0)
  345. * @throws std::out_of_range Packet size would exceed buffer
  346. */
  347. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  348. throw(std::out_of_range)
  349. {
  350. init(p,fragStart,fragLen,fragNo,fragTotal);
  351. }
  352. /**
  353. * Initialize from a packet
  354. *
  355. * @param p Original assembled packet
  356. * @param fragStart Start of fragment (raw index in packet data)
  357. * @param fragLen Length of fragment in bytes
  358. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  359. * @param fragTotal Total number of fragments (including 0)
  360. * @throws std::out_of_range Packet size would exceed buffer
  361. */
  362. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  363. throw(std::out_of_range)
  364. {
  365. if ((fragStart + fragLen) > p.size())
  366. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  367. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  368. // NOTE: this copies both the IV/packet ID and the destination address.
  369. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  370. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  371. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  372. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  373. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  374. }
  375. /**
  376. * Get this fragment's destination
  377. *
  378. * @return Destination ZT address
  379. */
  380. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  381. /**
  382. * @return True if fragment is of a valid length
  383. */
  384. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  385. /**
  386. * @return ID of packet this is a fragment of
  387. */
  388. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  389. /**
  390. * @return Total number of fragments in packet
  391. */
  392. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  393. /**
  394. * @return Fragment number of this fragment
  395. */
  396. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  397. /**
  398. * @return Fragment ZT hop count
  399. */
  400. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  401. /**
  402. * Increment this packet's hop count
  403. */
  404. inline void incrementHops()
  405. {
  406. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  407. }
  408. /**
  409. * @return Length of payload in bytes
  410. */
  411. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  412. /**
  413. * @return Raw packet payload
  414. */
  415. inline const unsigned char *payload() const
  416. {
  417. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  418. }
  419. };
  420. /**
  421. * ZeroTier protocol verbs
  422. */
  423. enum Verb /* Max value: 32 (5 bits) */
  424. {
  425. /* No operation, payload ignored, no reply */
  426. VERB_NOP = 0,
  427. /* Announcement of a node's existence:
  428. * <[1] protocol version>
  429. * <[1] software major version>
  430. * <[1] software minor version>
  431. * <[2] software revision>
  432. * <[8] timestamp (ms since epoch)>
  433. * <[...] binary serialized identity (see Identity)>
  434. * <[1] destination address type>
  435. * [<[...] destination address>]
  436. *
  437. * This is the only message that ever must be sent in the clear, since it
  438. * is used to push an identity to a new peer.
  439. *
  440. * The destination address is the wire address to which this packet is
  441. * being sent, and in OK is *also* the destination address of the OK
  442. * packet. This can be used by the receiver to detect NAT, learn its real
  443. * external address if behind NAT, and detect changes to its external
  444. * address that require re-establishing connectivity.
  445. *
  446. * Destination address types and formats (not all of these are used now):
  447. * 0 - None -- no destination address data present
  448. * 1 - Ethernet address -- format: <[6] Ethernet MAC>
  449. * 4 - 6-byte IPv4 UDP address/port -- format: <[4] IP>, <[2] port>
  450. * 6 - 18-byte IPv6 UDP address/port -- format: <[16] IP>, <[2] port>
  451. *
  452. * OK payload:
  453. * <[8] timestamp (echoed from original HELLO)>
  454. * <[1] protocol version (of responder)>
  455. * <[1] software major version (of responder)>
  456. * <[1] software minor version (of responder)>
  457. * <[2] software revision (of responder)>
  458. * <[1] destination address type (for this OK, not copied from HELLO)>
  459. * [<[...] destination address>]
  460. *
  461. * ERROR has no payload.
  462. */
  463. VERB_HELLO = 1,
  464. /* Error response:
  465. * <[1] in-re verb>
  466. * <[8] in-re packet ID>
  467. * <[1] error code>
  468. * <[...] error-dependent payload>
  469. */
  470. VERB_ERROR = 2,
  471. /* Success response:
  472. * <[1] in-re verb>
  473. * <[8] in-re packet ID>
  474. * <[...] request-specific payload>
  475. */
  476. VERB_OK = 3,
  477. /* Query an identity by address:
  478. * <[5] address to look up>
  479. *
  480. * OK response payload:
  481. * <[...] binary serialized identity>
  482. *
  483. * ERROR response payload:
  484. * <[5] address>
  485. */
  486. VERB_WHOIS = 4,
  487. /* Meet another node at a given protocol address:
  488. * <[1] flags (unused, currently 0)>
  489. * <[5] ZeroTier address of peer that might be found at this address>
  490. * <[2] 16-bit protocol address port>
  491. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  492. * <[...] protocol address (network byte order)>
  493. *
  494. * This is sent by a relaying node to initiate NAT traversal between two
  495. * peers that are communicating by way of indirect relay. The relay will
  496. * send this to both peers at the same time on a periodic basis, telling
  497. * each where it might find the other on the network.
  498. *
  499. * Upon receipt a peer sends HELLO to establish a direct link.
  500. *
  501. * Nodes should implement rate control, limiting the rate at which they
  502. * respond to these packets to prevent their use in DDOS attacks. Nodes
  503. * may also ignore these messages if a peer is not known or is not being
  504. * actively communicated with.
  505. *
  506. * No OK or ERROR is generated.
  507. */
  508. VERB_RENDEZVOUS = 5,
  509. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  510. * <[8] 64-bit network ID>
  511. * <[2] 16-bit ethertype>
  512. * <[...] ethernet payload>
  513. *
  514. * MAC addresses are derived from the packet's source and destination
  515. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  516. * Ethernet framing and other optional flags and features when they
  517. * are not necessary.
  518. *
  519. * ERROR may be generated if a membership certificate is needed for a
  520. * closed network. Payload will be network ID.
  521. */
  522. VERB_FRAME = 6,
  523. /* Full Ethernet frame with MAC addressing and optional fields:
  524. * <[8] 64-bit network ID>
  525. * <[1] flags>
  526. * [<[...] certificate of network membership>]
  527. * <[6] destination MAC or all zero for destination node>
  528. * <[6] source MAC or all zero for node of origin>
  529. * <[2] 16-bit ethertype>
  530. * <[...] ethernet payload>
  531. *
  532. * Flags:
  533. * 0x01 - Certificate of network membership is attached
  534. *
  535. * An extended frame carries full MAC addressing, making them a
  536. * superset of VERB_FRAME. They're used for bridging or when we
  537. * want to attach a certificate since FRAME does not support that.
  538. *
  539. * Multicast frames may not be sent as EXT_FRAME.
  540. *
  541. * ERROR may be generated if a membership certificate is needed for a
  542. * closed network. Payload will be network ID.
  543. */
  544. VERB_EXT_FRAME = 7,
  545. /* DEPRECATED */
  546. VERB_P5_MULTICAST_FRAME = 8,
  547. /* Announce interest in multicast group(s):
  548. * <[8] 64-bit network ID>
  549. * <[6] multicast Ethernet address>
  550. * <[4] multicast additional distinguishing information (ADI)>
  551. * [... additional tuples of network/address/adi ...]
  552. *
  553. * LIKEs are sent to peers with whom you have a direct peer to peer
  554. * connection, and always including rootservers.
  555. *
  556. * OK/ERROR are not generated.
  557. */
  558. VERB_MULTICAST_LIKE = 9,
  559. /* Network member certificate replication/push:
  560. * <[...] serialized certificate of membership>
  561. * [ ... additional certificates may follow ...]
  562. *
  563. * Certificate contains network ID, peer it was issued for, etc.
  564. *
  565. * OK/ERROR are not generated.
  566. */
  567. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  568. /* Network configuration request:
  569. * <[8] 64-bit network ID>
  570. * <[2] 16-bit length of request meta-data dictionary>
  571. * <[...] string-serialized request meta-data>
  572. * [<[8] 64-bit revision of netconf we currently have>]
  573. *
  574. * This message requests network configuration from a node capable of
  575. * providing it. If the optional revision is included, a response is
  576. * only generated if there is a newer network configuration available.
  577. *
  578. * OK response payload:
  579. * <[8] 64-bit network ID>
  580. * <[2] 16-bit length of network configuration dictionary>
  581. * <[...] network configuration dictionary>
  582. *
  583. * OK returns a Dictionary (string serialized) containing the network's
  584. * configuration and IP address assignment information for the querying
  585. * node. It also contains a membership certificate that the querying
  586. * node can push to other peers to demonstrate its right to speak on
  587. * a given network.
  588. *
  589. * When a new network configuration is received, another config request
  590. * should be sent with the new netconf's revision. This confirms receipt
  591. * and also causes any subsequent changes to rapidly propagate as this
  592. * cycle will repeat until there are no changes. This is optional but
  593. * recommended behavior.
  594. *
  595. * ERROR response payload:
  596. * <[8] 64-bit network ID>
  597. *
  598. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  599. * and OBJ_NOT_FOUND if the queried network ID was not found.
  600. */
  601. VERB_NETWORK_CONFIG_REQUEST = 11,
  602. /* Network configuration refresh request:
  603. * <[...] array of 64-bit network IDs>
  604. *
  605. * This message can be sent by the network configuration master node
  606. * to request that nodes refresh their network configuration. It can
  607. * thus be used to "push" updates so that network config changes will
  608. * take effect quickly.
  609. *
  610. * It does not generate an OK or ERROR message, and is treated only as
  611. * a hint to refresh now.
  612. */
  613. VERB_NETWORK_CONFIG_REFRESH = 12,
  614. /* Request endpoints for multicast distribution:
  615. * <[8] 64-bit network ID>
  616. * <[1] flags>
  617. * <[6] MAC address of multicast group being queried>
  618. * <[4] 32-bit ADI for multicast group being queried>
  619. * <[4] 32-bit requested max number of multicast peers>
  620. * [<[...] network certificate of membership>]
  621. *
  622. * Flags:
  623. * 0x01 - Network certificate of membership is attached
  624. *
  625. * This message asks a peer for additional known endpoints that have
  626. * LIKEd a given multicast group. It's sent when the sender wishes
  627. * to send multicast but does not have the desired number of recipient
  628. * peers.
  629. *
  630. * OK response payload:
  631. * <[8] 64-bit network ID>
  632. * <[6] MAC address of multicast group being queried>
  633. * <[4] 32-bit ADI for multicast group being queried>
  634. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  635. * <[4] 32-bit total number of known members in this multicast group>
  636. * <[2] 16-bit number of members enumerated in this packet>
  637. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  638. *
  639. * If no endpoints are known, OK and ERROR are both optional. It's okay
  640. * to return nothing in that case since gathering is "lazy."
  641. *
  642. * ERROR response payload:
  643. * <[8] 64-bit network ID>
  644. * <[6] MAC address of multicast group being queried>
  645. * <[4] 32-bit ADI for multicast group being queried>
  646. *
  647. * ERRORs are optional and are only generated if permission is denied,
  648. * certificate of membership is out of date, etc.
  649. */
  650. VERB_MULTICAST_GATHER = 13,
  651. /* Multicast frame:
  652. * <[8] 64-bit network ID>
  653. * <[1] flags>
  654. * [<[...] network certificate of membership>]
  655. * [<[4] 32-bit implicit gather limit>]
  656. * [<[6] source MAC>]
  657. * <[6] destination MAC (multicast address)>
  658. * <[4] 32-bit multicast ADI (multicast address extension)>
  659. * <[2] 16-bit ethertype>
  660. * <[...] ethernet payload>
  661. *
  662. * Flags:
  663. * 0x01 - Network certificate of membership is attached
  664. * 0x02 - Implicit gather limit field is present
  665. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  666. *
  667. * OK and ERROR responses are optional. OK may be generated if there are
  668. * implicit gather results or if the recipient wants to send its own
  669. * updated certificate of network membership to the sender. ERROR may be
  670. * generated if a certificate is needed or if multicasts to this group
  671. * are no longer wanted (multicast unsubscribe).
  672. *
  673. * OK response payload:
  674. * <[8] 64-bit network ID>
  675. * <[6] MAC address of multicast group>
  676. * <[4] 32-bit ADI for multicast group>
  677. * <[1] flags>
  678. * [<[...] network certficate of membership>]
  679. * [<[...] implicit gather results if flag 0x01 is set>]
  680. *
  681. * OK flags (same bits as request flags):
  682. * 0x01 - OK includes certificate of network membership
  683. * 0x02 - OK includes implicit gather results
  684. *
  685. * ERROR response payload:
  686. * <[8] 64-bit network ID>
  687. * <[6] multicast group MAC>
  688. * <[4] 32-bit multicast group ADI>
  689. */
  690. VERB_MULTICAST_FRAME = 14,
  691. /* Ephemeral (PFS) key push:
  692. * <[2] flags (unused and reserved, must be 0)>
  693. * <[2] length of padding / extra field section>
  694. * <[...] padding / extra field section>
  695. * <[8] 64-bit PFS key set ID sender holds for recipient (0==none)>
  696. * <[8] 64-bit PFS key set ID of this key set>
  697. * [... begin PFS key record ...]
  698. * <[1] flags>
  699. * <[1] symmetric cipher ID>
  700. * <[1] public key type ID>
  701. * <[2] public key length in bytes>
  702. * <[...] public key>
  703. * [... additional records may follow up to max packet length ...]
  704. *
  705. * This message is sent to negotiate an ephemeral key. If the recipient's
  706. * current key pair for the sender does not match the one the sender
  707. * claims to have on file, it must respond with its own SET_EPHEMERAL_KEY.
  708. *
  709. * PFS key IDs are random and must not be zero, since zero indicates that
  710. * the sender does not have an ephemeral key on file for the recipient.
  711. *
  712. * One or more records may be sent. If multiple records are present,
  713. * the first record with common symmetric cipher, public key type,
  714. * and relevant flags must be used.
  715. *
  716. * The padding section may be filled with an arbitrary amount of random
  717. * or empty payload. This may be used as a countermeasure to prevent PFS
  718. * key pushes from being recognized by packet size vs. other packets in
  719. * the stream. This also provides potential space for additional fields
  720. * that might be indicated in the future by flags.
  721. *
  722. * Flags (all unspecified flags must be zero):
  723. * 0x01 - FIPS mode, only use record if FIPS compliant crypto in use
  724. *
  725. * Symmetric cipher IDs:
  726. * 0x01 - Salsa20/12 with Poly1305 authentication (ZT default)
  727. * 0x02 - AES256-GCM combined crypto and authentication
  728. *
  729. * Public key types:
  730. * 0x01 - Curve25519 ECDH with SHA-512 KDF
  731. * 0x02 - NIST P-256 ECDH with SHA-512 KDF
  732. *
  733. * Once both peers have a PFS key, they will attempt to send PFS key
  734. * encrypted messages with the PFS flag set using the negotiated
  735. * cipher/auth type.
  736. *
  737. * Note: most of these features such as FIPS and other cipher suites are
  738. * not implemented yet. They're just specified in the protocol for future
  739. * use to support e.g. FIPS requirements.
  740. *
  741. * OK response payload:
  742. * <[8] PFS key set ID of received key set>
  743. * <[1] index in record list of chosen key record>
  744. */
  745. VERB_SET_EPHEMERAL_KEY = 15,
  746. /* "Call me at" -- push of potential endpoints for direct communication:
  747. * <[1] flags>
  748. * <[2] number of addresses>
  749. * <[...] address types and addresses>
  750. *
  751. * Address types and addresses are of the same format as the destination
  752. * address type and address in HELLO.
  753. *
  754. * The receiver may, upon receiving a CMA push, attempt to establish a
  755. * direct link to one or more of the indicated addresses. Senders should
  756. * only send CMA pushes to peers that they have some relationship
  757. * with such as a shared network membership or a mutual trust.
  758. *
  759. * OK/ERROR are not generated.
  760. */
  761. VERB_CMA = 16
  762. };
  763. /**
  764. * Error codes for VERB_ERROR
  765. */
  766. enum ErrorCode
  767. {
  768. /* No error, not actually used in transit */
  769. ERROR_NONE = 0,
  770. /* Invalid request */
  771. ERROR_INVALID_REQUEST = 1,
  772. /* Bad/unsupported protocol version */
  773. ERROR_BAD_PROTOCOL_VERSION = 2,
  774. /* Unknown object queried (e.g. with WHOIS) */
  775. ERROR_OBJ_NOT_FOUND = 3,
  776. /* HELLO pushed an identity whose address is already claimed */
  777. ERROR_IDENTITY_COLLISION = 4,
  778. /* Verb or use case not supported/enabled by this node */
  779. ERROR_UNSUPPORTED_OPERATION = 5,
  780. /* Message to private network rejected -- no unexpired certificate on file */
  781. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  782. /* Tried to join network, but you're not a member */
  783. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  784. /* Multicasts to this group are not wanted */
  785. ERROR_UNWANTED_MULTICAST = 8
  786. };
  787. /**
  788. * @param v Verb
  789. * @return String representation (e.g. HELLO, OK)
  790. */
  791. static const char *verbString(Verb v)
  792. throw();
  793. /**
  794. * @param e Error code
  795. * @return String error name
  796. */
  797. static const char *errorString(ErrorCode e)
  798. throw();
  799. template<unsigned int C2>
  800. Packet(const Buffer<C2> &b) :
  801. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  802. {
  803. }
  804. Packet(const void *data,unsigned int len) :
  805. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  806. {
  807. }
  808. /**
  809. * Construct a new empty packet with a unique random packet ID
  810. *
  811. * Flags and hops will be zero. Other fields and data region are undefined.
  812. * Use the header access methods (setDestination() and friends) to fill out
  813. * the header. Payload should be appended; initial size is header size.
  814. */
  815. Packet() :
  816. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  817. {
  818. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  819. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  820. }
  821. /**
  822. * Make a copy of a packet with a new initialization vector and destination address
  823. *
  824. * This can be used to take one draft prototype packet and quickly make copies to
  825. * encrypt for different destinations.
  826. *
  827. * @param prototype Prototype packet
  828. * @param dest Destination ZeroTier address for new packet
  829. */
  830. Packet(const Packet &prototype,const Address &dest) :
  831. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  832. {
  833. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  834. setDestination(dest);
  835. }
  836. /**
  837. * Construct a new empty packet with a unique random packet ID
  838. *
  839. * @param dest Destination ZT address
  840. * @param source Source ZT address
  841. * @param v Verb
  842. */
  843. Packet(const Address &dest,const Address &source,const Verb v) :
  844. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  845. {
  846. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  847. setDestination(dest);
  848. setSource(source);
  849. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  850. setVerb(v);
  851. }
  852. /**
  853. * Reset this packet structure for reuse in place
  854. *
  855. * @param dest Destination ZT address
  856. * @param source Source ZT address
  857. * @param v Verb
  858. */
  859. inline void reset(const Address &dest,const Address &source,const Verb v)
  860. {
  861. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  862. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  863. setDestination(dest);
  864. setSource(source);
  865. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  866. setVerb(v);
  867. }
  868. /**
  869. * Generate a new IV / packet ID in place
  870. *
  871. * This can be used to re-use a packet buffer multiple times to send
  872. * technically different but otherwise identical copies of the same
  873. * packet.
  874. */
  875. inline void newInitializationVector() { Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8); }
  876. /**
  877. * Set this packet's destination
  878. *
  879. * @param dest ZeroTier address of destination
  880. */
  881. inline void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  882. /**
  883. * Set this packet's source
  884. *
  885. * @param source ZeroTier address of source
  886. */
  887. inline void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  888. /**
  889. * Get this packet's destination
  890. *
  891. * @return Destination ZT address
  892. */
  893. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  894. /**
  895. * Get this packet's source
  896. *
  897. * @return Source ZT address
  898. */
  899. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  900. /**
  901. * @return True if packet is of valid length
  902. */
  903. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  904. /**
  905. * @return True if packet is fragmented (expect fragments)
  906. */
  907. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  908. /**
  909. * Set this packet's fragmented flag
  910. *
  911. * @param f Fragmented flag value
  912. */
  913. inline void setFragmented(bool f)
  914. {
  915. if (f)
  916. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  917. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  918. }
  919. /**
  920. * @return True if compressed (result only valid if unencrypted)
  921. */
  922. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  923. /**
  924. * @return ZeroTier forwarding hops (0 to 7)
  925. */
  926. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  927. /**
  928. * Increment this packet's hop count
  929. */
  930. inline void incrementHops()
  931. {
  932. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  933. b = (b & 0xf8) | ((b + 1) & 0x07);
  934. }
  935. /**
  936. * @return Cipher suite selector: 0 - 7 (see #defines)
  937. */
  938. inline unsigned int cipher() const
  939. {
  940. // Note: this uses the new cipher spec field, which is incompatible with <1.0.0 peers
  941. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  942. }
  943. /**
  944. * Set this packet's cipher suite
  945. */
  946. inline void setCipher(unsigned int c)
  947. {
  948. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  949. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  950. // DEPRECATED "encrypted" flag -- used by pre-1.0.3 peers
  951. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  952. b |= ZT_PROTO_FLAG_ENCRYPTED;
  953. else b &= (~ZT_PROTO_FLAG_ENCRYPTED);
  954. }
  955. /**
  956. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  957. *
  958. * @return Packet ID
  959. */
  960. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  961. /**
  962. * Set packet verb
  963. *
  964. * This also has the side-effect of clearing any verb flags, such as
  965. * compressed, and so must only be done during packet composition.
  966. *
  967. * @param v New packet verb
  968. */
  969. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  970. /**
  971. * @return Packet verb (not including flag bits)
  972. */
  973. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  974. /**
  975. * @return Length of packet payload
  976. */
  977. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  978. /**
  979. * @return Raw packet payload
  980. */
  981. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  982. /**
  983. * Armor packet for transport
  984. *
  985. * @param key 32-byte key
  986. * @param encryptPayload If true, encrypt packet payload, else just MAC
  987. */
  988. void armor(const void *key,bool encryptPayload);
  989. /**
  990. * Verify and (if encrypted) decrypt packet
  991. *
  992. * @param key 32-byte key
  993. * @return False if packet is invalid or failed MAC authenticity check
  994. */
  995. bool dearmor(const void *key);
  996. /**
  997. * Attempt to compress payload if not already (must be unencrypted)
  998. *
  999. * This requires that the payload at least contain the verb byte already
  1000. * set. The compressed flag in the verb is set if compression successfully
  1001. * results in a size reduction. If no size reduction occurs, compression
  1002. * is not done and the flag is left cleared.
  1003. *
  1004. * @return True if compression occurred
  1005. */
  1006. bool compress();
  1007. /**
  1008. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1009. *
  1010. * If payload is compressed, it is decompressed and the compressed verb
  1011. * flag is cleared. Otherwise nothing is done and true is returned.
  1012. *
  1013. * @return True if data is now decompressed and valid, false on error
  1014. */
  1015. bool uncompress();
  1016. private:
  1017. static const unsigned char ZERO_KEY[32];
  1018. /**
  1019. * Deterministically mangle a 256-bit crypto key based on packet
  1020. *
  1021. * This uses extra data from the packet to mangle the secret, giving us an
  1022. * effective IV that is somewhat more than 64 bits. This is "free" for
  1023. * Salsa20 since it has negligible key setup time so using a different
  1024. * key each time is fine.
  1025. *
  1026. * @param in Input key (32 bytes)
  1027. * @param out Output buffer (32 bytes)
  1028. */
  1029. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1030. {
  1031. const unsigned char *d = (const unsigned char *)data();
  1032. // IV and source/destination addresses. Using the addresses divides the
  1033. // key space into two halves-- A->B and B->A (since order will change).
  1034. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1035. out[i] = in[i] ^ d[i];
  1036. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1037. // nodes. It's one of the only parts of a packet modifiable by people
  1038. // without the key.
  1039. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1040. // Raw packet size in bytes -- thus each packet size defines a new
  1041. // key space.
  1042. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1043. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1044. // Rest of raw key is used unchanged
  1045. for(unsigned int i=21;i<32;++i)
  1046. out[i] = in[i];
  1047. }
  1048. };
  1049. } // namespace ZeroTier
  1050. #endif