util_security.h 7.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/* <!-- copyright */
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2014 Nils Maier
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */

#ifndef D_UTIL_SECURITY_H
#define D_UTIL_SECURITY_H

#include "common.h"

#include <string>
#include <stdexcept>

#include "a2functional.h"
#include "MessageDigest.h"

namespace aria2 {
namespace util {
namespace security {

/**
 * Compare to bytes in constant time.
 *
 * @param a First byte.
 * @param b Second byte.
 * @return True, if both match, false otherwise.
 */
bool compare(const uint8_t a, const uint8_t b);

/**
 * Compare two byte arrays in constant time. The arrays must have the same
 * length!
 *
 * @param a First byte array.
 * @param b Second byte array.
 * @return True, if both match, false otherwise.
 */
bool compare(const uint8_t* a, const uint8_t* b, size_t length);
inline bool compare(const char* a, const char* b, size_t length)
{
  return compare(reinterpret_cast<const uint8_t*>(a),
72
                 reinterpret_cast<const uint8_t*>(b), length * sizeof(char));
73 74 75 76 77 78 79 80 81
}

/**
 * HMAC Result wrapper. While it is still possible to get the raw result bytes,
 * when using this wrapper it is ensured that constant-time comparison is used.
 * Also, this wrapper makes it an error to compare results of a different
 * length, helping to prevent logic errors either during development, or
 * triggering in the wild. Therefore |.getBytes()| use should be avoided.
 */
82
class HMACResult {
83 84
public:
  HMACResult(const std::string& result) : result_(result), len_(result.length())
85 86
  {
  }
87 88

  HMACResult(const char* result, size_t length)
89 90 91
      : result_(result, length), len_(length)
  {
  }
92

93
  HMACResult(const HMACResult& other) = default;
94

95
  HMACResult& operator=(const HMACResult& other) = default;
96 97 98 99 100 101 102 103 104

  bool operator==(const HMACResult& other) const
  {
    if (len_ != other.len_) {
      throw std::domain_error("comparing different hmac is undefined");
    }
    return compare(result_.data(), other.result_.data(), len_);
  }

105
  bool operator!=(const HMACResult& other) const { return !(*this == other); }
106

107
  size_t length() const { return len_; }
108

109
  const std::string& getBytes() const { return result_; }
110 111 112 113 114 115 116 117 118 119 120

private:
  std::string result_;
  size_t len_;
};

/**
 * Implements HMAC-SHA* per RFC 6234. It supports the same cryptographic hash
 * algorithms that MessageDigest supports, but at most the SHA-1, SHA-2
 * algorithms as specified in the RFC.
 */
121
class HMAC {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
public:
  /**
   * Constructs a new HMAC. It is recommended to use the |create| or
   * |createRandom| factory methods instead.
   *
   * @see create
   * @see createRandom
   */
  HMAC(const std::string& algorithm, const char* secret, size_t length);

  /**
   * Creates a new instance using the specified algorithm and secret.
   */
  static std::unique_ptr<HMAC> create(const std::string& algorithm,
                                      const std::string& secret)
  {
    return create(algorithm, secret.data(), secret.length());
  }

  /**
   * Creates a new instance using the specified algorithm and secret.
   */
144 145
  static std::unique_ptr<HMAC> create(const std::string& algorithm,
                                      const char* secret, size_t length)
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  {
    if (!supports(algorithm)) {
      return nullptr;
    }
    return make_unique<HMAC>(algorithm, secret, length);
  }

  /**
   * Creates a new instance using sha-1 and the specified secret.
   */
  static std::unique_ptr<HMAC> create(const std::string& secret)
  {
    return create("sha-1", secret.data(), secret.length());
  }

  /**
   * Creates a new instance using sha-1 and the specified secret.
   */
  static std::unique_ptr<HMAC> create(const char* secret, size_t length)
  {
    return create("sha-1", secret, length);
  }

  /**
   * Creates a new instance using the specified algorithm and a random secret.
   */
  static std::unique_ptr<HMAC> createRandom(const std::string& algorithm);

  /**
   * Creates a new instance using sha-1 and a random secret.
   */
177
  static std::unique_ptr<HMAC> createRandom() { return createRandom("sha-1"); }
178 179 180 181 182 183 184 185 186

  /**
   * Tells if this implementation supports a specific hash algorithm.
   */
  static bool supports(const std::string& algorithm);

  /**
   * Tells the length in bytes of the resulting HMAC.
   */
187
  size_t length() const { return md_->getDigestLength(); }
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

  /**
   * Resets the instance, clearing the internal state. The instance can be
   * re-used afterwards.
   */
  void reset()
  {
    if (clean_) {
      return;
    }
    md_->reset();
    md_->update(ipad_.data(), ipad_.length());
    clean_ = true;
  }

  /**
   * Updates the HMAC with new message data.
   */
  void update(const std::string& data)
  {
    md_->update(data.data(), data.length());
    clean_ = false;
  }

  /**
   * Updates the HMAC with new message data.
   */
  void update(const char* data, size_t length)
  {
    md_->update(data, length);
    clean_ = false;
  }

  /**
   * Returns the result. This can only be called once. After the call the
   * internal state is reset and new HMACs can be computed with the same
   * instance.
   */
  HMACResult getResult()
  {
    auto rv = md_->digest();
    md_->reset();
    md_->update(opad_.data(), opad_.length());
    md_->update(rv.data(), rv.length());
    rv = md_->digest();
    clean_ = false;
    reset();
    return HMACResult(rv);
  }

  /**
   * Returns the resulting HMAC of string in one go. You cannot mix call to this
   * method with calls to update.
   */
  HMACResult getResult(const std::string& str)
  {
    reset();
    update(str);
    return getResult();
  }

  /**
   * Returns the resulting HMAC of string in one go. You cannot mix call to this
   * method with calls to update.
   */
  HMACResult getResult(const char* data, size_t len)
  {
    reset();
    update(data, len);
    return getResult();
  }

private:
  const size_t blockSize_;
  std::unique_ptr<MessageDigest> md_;
  std::string ipad_, opad_;
  bool clean_;
};

/**
 * Create A PKBDF2-HMAC. See RFC 2898.
 *
 * Example:
 *   result = PBKDF2(HMAC::create("password"), random_salt, salt_len, 1000);
 */
273 274
HMACResult PBKDF2(HMAC* hmac, const char* salt, size_t salt_length,
                  size_t iterations, size_t key_length = 0);
275 276 277 278 279 280 281

/**
 * Create A PKBDF2-HMAC. See RFC 2898.
 *
 * Example:
 *   result = PBKDF2(HMAC::create("password"), random_salt, 1000);
 */
282
inline HMACResult PBKDF2(HMAC* hmac, const std::string& salt, size_t iterations,
283 284 285 286 287 288 289 290 291 292
                         size_t key_length = 0)
{
  return PBKDF2(hmac, salt.data(), salt.length(), iterations, key_length);
}

} // namespace security
} // namespace util
} // namespace aria2

#endif // D_UTIL_SECURITY_H