Tag.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Tag.hpp"
  14. namespace ZeroTier {
  15. bool Tag::sign(const Identity &signer) noexcept
  16. {
  17. uint8_t buf[ZT_TAG_MARSHAL_SIZE_MAX];
  18. if (signer.hasPrivate()) {
  19. m_signedBy = signer.address();
  20. m_signatureLength = signer.sign(buf, (unsigned int)marshal(buf, true), m_signature, sizeof(m_signature));
  21. return true;
  22. }
  23. return false;
  24. }
  25. int Tag::marshal(uint8_t data[ZT_TAG_MARSHAL_SIZE_MAX],bool forSign) const noexcept
  26. {
  27. int p = 0;
  28. if (forSign) {
  29. for(int k=0;k<8;++k)
  30. data[p++] = 0x7f;
  31. }
  32. Utils::storeBigEndian<uint64_t>(data + p, m_networkId); p += 8;
  33. Utils::storeBigEndian<uint64_t>(data + p,(uint64_t)m_ts); p += 8;
  34. Utils::storeBigEndian<uint32_t>(data + p, m_id); p += 4;
  35. Utils::storeBigEndian<uint32_t>(data + p, m_value); p += 4;
  36. m_issuedTo.copyTo(data + p); p += ZT_ADDRESS_LENGTH;
  37. m_signedBy.copyTo(data + p); p += ZT_ADDRESS_LENGTH;
  38. if (!forSign) {
  39. data[p++] = 1;
  40. Utils::storeBigEndian<uint16_t>(data + p,(uint16_t)m_signatureLength); p += 2;
  41. Utils::copy(data + p, m_signature, m_signatureLength);
  42. p += (int)m_signatureLength;
  43. }
  44. data[p++] = 0;
  45. data[p++] = 0;
  46. if (forSign) {
  47. for(int k=0;k<8;++k)
  48. data[p++] = 0x7f;
  49. }
  50. return p;
  51. }
  52. int Tag::unmarshal(const uint8_t *data,int len) noexcept
  53. {
  54. if (len < 37)
  55. return -1;
  56. m_networkId = Utils::loadBigEndian<uint64_t>(data);
  57. m_ts = (int64_t)Utils::loadBigEndian<uint64_t>(data + 8);
  58. m_id = Utils::loadBigEndian<uint32_t>(data + 16);
  59. m_value = Utils::loadBigEndian<uint32_t>(data + 20);
  60. m_issuedTo.setTo(data + 24);
  61. m_signedBy.setTo(data + 29);
  62. // 1 byte reserved
  63. m_signatureLength = Utils::loadBigEndian<uint16_t>(data + 35);
  64. int p = 37 + (int)m_signatureLength;
  65. if ((m_signatureLength > ZT_SIGNATURE_BUFFER_SIZE) || (p > len))
  66. return -1;
  67. Utils::copy(m_signature, data + p, m_signatureLength);
  68. if ((p + 2) > len)
  69. return -1;
  70. p += 2 + Utils::loadBigEndian<uint16_t>(data + p);
  71. if (p > len)
  72. return -1;
  73. return p;
  74. }
  75. } // namespace ZeroTier