AppleTLSContext.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2013 Nils Maier
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "AppleTLSContext.h"
  36. #include <algorithm>
  37. #include <functional>
  38. #include "LogFactory.h"
  39. #include "Logger.h"
  40. #include "MessageDigest.h"
  41. #include "fmt.h"
  42. #include "message.h"
  43. #include "util.h"
  44. namespace {
  45. using namespace aria2;
  46. #if defined(__MAC_10_6)
  47. #if defined(__MAC_10_7)
  48. static const void *query_keys[] = {
  49. kSecClass,
  50. kSecReturnRef,
  51. kSecMatchPolicy,
  52. kSecMatchLimit
  53. };
  54. #endif // defined(__MAC_10_7)
  55. class cfrelease {
  56. const void *ptr_;
  57. public:
  58. inline cfrelease(const void *ptr) : ptr_(ptr) {}
  59. inline ~cfrelease() { if (ptr_) CFRelease(ptr_); }
  60. };
  61. static inline bool isWhitespace(char c)
  62. {
  63. // Fingerprints are often separated by colons
  64. return isspace(c) || c == ':';
  65. }
  66. static inline std::string stripWhitespace(std::string str)
  67. {
  68. str.erase(std::remove_if(str.begin(), str.end(), isWhitespace), str.end());
  69. return str;
  70. }
  71. struct hash_validator {
  72. const std::string& hash_;
  73. hash_validator(const std::string& hash) : hash_(hash) {}
  74. inline bool operator()(std::string type) const {
  75. return MessageDigest::isValidHash(type, hash_);
  76. }
  77. };
  78. struct hash_finder {
  79. CFDataRef data_;
  80. const std::string& hash_;
  81. hash_finder(CFDataRef data, const std::string& hash)
  82. : data_(data), hash_(hash)
  83. {}
  84. inline bool operator()(std::string type) const {
  85. std::string hash = MessageDigest::create(type)->update(
  86. CFDataGetBytePtr(data_), CFDataGetLength(data_)).digest();
  87. hash = util::toHex(hash);
  88. return hash == hash_;
  89. }
  90. };
  91. std::string errToString(OSStatus err)
  92. {
  93. std::string rv = "Unkown error";
  94. CFStringRef cerr = SecCopyErrorMessageString(err, 0);
  95. if (cerr) {
  96. size_t len = CFStringGetLength(cerr) * 4;
  97. char *buf = new char[len];
  98. if (CFStringGetCString(cerr, buf, len, kCFStringEncodingUTF8)) {
  99. rv = buf;
  100. }
  101. delete [] buf;
  102. CFRelease(cerr);
  103. }
  104. return rv;
  105. }
  106. bool checkIdentity(const SecIdentityRef id, const std::string& fingerPrint,
  107. const std::vector<std::string> supported)
  108. {
  109. SecCertificateRef ref = 0;
  110. if (SecIdentityCopyCertificate(id, &ref) != errSecSuccess) {
  111. A2_LOG_ERROR("Failed to get a certref!");
  112. return false;
  113. }
  114. cfrelease del_ref(ref);
  115. CFDataRef data = SecCertificateCopyData(ref);
  116. if (!data) {
  117. A2_LOG_ERROR("Failed to get a data!");
  118. return false;
  119. }
  120. cfrelease del_data(data);
  121. // Do try all supported hash algorithms.
  122. // Usually the fingerprint would be sha1 or md5, however this is more
  123. // future-proof. Also "usually" doesn't cut it; there is already software
  124. // using SHA-2 class algos, and SHA-3 is standardized and potential users
  125. // cannot be far.
  126. return std::find_if(supported.begin(), supported.end(),
  127. hash_finder(data, fingerPrint)) != supported.end();
  128. }
  129. #endif // defined(__MAC_10_6)
  130. }
  131. namespace aria2 {
  132. TLSContext* TLSContext::make(TLSSessionSide side)
  133. {
  134. return new AppleTLSContext(side);
  135. }
  136. AppleTLSContext::~AppleTLSContext()
  137. {
  138. if (credentials_) {
  139. CFRelease(credentials_);
  140. credentials_ = 0;
  141. }
  142. }
  143. bool AppleTLSContext::addCredentialFile(const std::string& certfile,
  144. const std::string& keyfile)
  145. {
  146. if (tryAsFingerprint(certfile)) {
  147. return true;
  148. }
  149. A2_LOG_WARN("TLS credential files are not supported. Use the KeyChain to manage your certificates and provide a fingerprint. See the manual.");
  150. return false;
  151. }
  152. bool AppleTLSContext::addTrustedCACertFile(const std::string& certfile)
  153. {
  154. A2_LOG_INFO("TLS CA bundle files are not supported. Use the KeyChain to manage your certificates.");
  155. return false;
  156. }
  157. SecIdentityRef AppleTLSContext::getCredentials()
  158. {
  159. return credentials_;
  160. }
  161. bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint)
  162. {
  163. std::string fp = stripWhitespace(fingerprint);
  164. // Verify this is a valid hex representation and normalize.
  165. fp = util::toHex(util::fromHex(fp.begin(), fp.end()));
  166. // Verify this can represent a hash
  167. std::vector<std::string> ht = MessageDigest::getSupportedHashTypes();
  168. if (std::find_if(ht.begin(), ht.end(), hash_validator(fp)) == ht.end()) {
  169. A2_LOG_INFO(fmt("%s is not a fingerprint, invalid hash representation", fingerprint.c_str()));
  170. return false;
  171. }
  172. #if defined(__MAC_10_7)
  173. A2_LOG_DEBUG(fmt("Looking for cert with fingerprint %s", fp.c_str()));
  174. // Build and run the KeyChain the query.
  175. SecPolicyRef policy = SecPolicyCreateSSL(true, 0);
  176. if (!policy) {
  177. A2_LOG_ERROR("Failed to create SecPolicy");
  178. return false;
  179. }
  180. cfrelease del_policy(policy);
  181. const void *query_values[] = {
  182. kSecClassIdentity,
  183. kCFBooleanTrue,
  184. policy,
  185. kSecMatchLimitAll
  186. };
  187. CFDictionaryRef query = CFDictionaryCreate(0, query_keys, query_values,
  188. 4, 0, 0);
  189. if (!query) {
  190. A2_LOG_ERROR("Failed to create identity query");
  191. return false;
  192. }
  193. cfrelease del_query(query);
  194. CFArrayRef identities;
  195. OSStatus err = SecItemCopyMatching(query, (CFTypeRef*)&identities);
  196. if (err != errSecSuccess) {
  197. A2_LOG_ERROR("Query failed: " + errToString(err));
  198. return false;
  199. }
  200. // Alrighty, search the fingerprint.
  201. const size_t nvals = CFArrayGetCount(identities);
  202. for (size_t i = 0; i < nvals; ++i) {
  203. SecIdentityRef id = (SecIdentityRef)CFArrayGetValueAtIndex(identities, i);
  204. if (!id) {
  205. A2_LOG_ERROR("Failed to get a value!");
  206. continue;
  207. }
  208. if (!checkIdentity(id, fp, ht)) {
  209. continue;
  210. }
  211. A2_LOG_INFO("Found cert with matching fingerprint");
  212. credentials_ = id;
  213. CFRetain(id);
  214. return true;
  215. }
  216. A2_LOG_ERROR(fmt("Failed to lookup %s in your KeyChain", fingerprint.c_str()));
  217. return false;
  218. #else // defined(__MAC_10_7)
  219. #if defined(__MAC_10_6)
  220. SecIdentitySearchRef search;
  221. // Deprecated as of 10.7
  222. OSStatus err = SecIdentitySearchCreate(0, CSSM_KEYUSE_SIGN, &search);
  223. if (err != errSecSuccess) {
  224. A2_LOG_ERROR("Certificate search failed: " + errToString(err));
  225. }
  226. cfrelease del_search(search);
  227. SecIdentityRef id;
  228. while (SecIdentitySearchCopyNext(search, &id) == errSecSuccess) {
  229. if (!checkIdentity(id, fp, ht)) {
  230. continue;
  231. }
  232. A2_LOG_INFO("Found cert with matching fingerprint");
  233. credentials_ = id;
  234. return true;
  235. }
  236. A2_LOG_ERROR(fmt("Failed to lookup %s in your KeyChain", fingerprint.c_str()));
  237. return false;
  238. #else // defined(__MAC_10_6)
  239. A2_LOG_ERROR("Your system does not support creditials via fingerprints; Upgrade to OSX 10.6 or later");
  240. return false;
  241. #endif // defined(__MAC_10_6)
  242. #endif // defined(__MAC_10_7)
  243. }
  244. } // namespace aria2