AppleTLSContext.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 <sstream>
  39. #ifdef __MAC_10_6
  40. #include <Security/SecImportExport.h>
  41. #endif
  42. #include "LogFactory.h"
  43. #include "BufferedFile.h"
  44. #include "Logger.h"
  45. #include "MessageDigest.h"
  46. #include "fmt.h"
  47. #include "message.h"
  48. #include "util.h"
  49. namespace {
  50. using namespace aria2;
  51. #if defined(__MAC_10_6)
  52. #if defined(__MAC_10_7)
  53. static const void* query_keys[] = {kSecClass, kSecReturnRef, kSecMatchPolicy,
  54. kSecMatchLimit};
  55. #endif // defined(__MAC_10_7)
  56. template <typename T> class CFRef {
  57. T ref_;
  58. public:
  59. CFRef() : ref_(nullptr) {}
  60. CFRef(T ref) : ref_(ref) {}
  61. ~CFRef() { reset(nullptr); }
  62. void reset(T ref)
  63. {
  64. if (ref_) {
  65. CFRelease(ref_);
  66. }
  67. ref_ = ref;
  68. }
  69. T get() { return ref_; }
  70. const T get() const { return ref_; }
  71. operator bool() const { return !!ref_; }
  72. };
  73. static inline bool isWhitespace(char c)
  74. {
  75. // Fingerprints are often separated by colons
  76. return isspace(c) || c == ':';
  77. }
  78. static inline std::string stripWhitespace(std::string str)
  79. {
  80. str.erase(std::remove_if(std::begin(str), std::end(str), isWhitespace),
  81. std::end(str));
  82. return str;
  83. }
  84. struct hash_validator {
  85. const std::string& hash_;
  86. hash_validator(const std::string& hash) : hash_(hash) {}
  87. inline bool operator()(std::string type) const
  88. {
  89. return MessageDigest::isValidHash(type, hash_);
  90. }
  91. };
  92. struct hash_finder {
  93. CFDataRef data_;
  94. const std::string& hash_;
  95. hash_finder(CFDataRef data, const std::string& hash)
  96. : data_(data), hash_(hash)
  97. {
  98. }
  99. inline bool operator()(std::string type) const
  100. {
  101. std::string hash =
  102. MessageDigest::create(type)
  103. ->update(CFDataGetBytePtr(data_), CFDataGetLength(data_))
  104. .digest();
  105. hash = util::toHex(hash);
  106. return hash == hash_;
  107. }
  108. };
  109. std::string errToString(OSStatus err)
  110. {
  111. std::string rv = "Unkown error";
  112. CFRef<CFStringRef> cerr(SecCopyErrorMessageString(err, nullptr));
  113. if (!cerr) {
  114. return rv;
  115. }
  116. size_t len = CFStringGetLength(cerr.get()) * 4;
  117. auto buf = make_unique<char[]>(len);
  118. if (CFStringGetCString(cerr.get(), buf.get(), len, kCFStringEncodingUTF8)) {
  119. rv = buf.get();
  120. }
  121. return rv;
  122. }
  123. bool checkIdentity(const SecIdentityRef id, const std::string& fingerPrint,
  124. const std::vector<std::string> supported)
  125. {
  126. CFRef<SecCertificateRef> ref;
  127. SecCertificateRef raw_ref = nullptr;
  128. if (SecIdentityCopyCertificate(id, &raw_ref) != errSecSuccess) {
  129. A2_LOG_ERROR("Failed to get a certref!");
  130. return false;
  131. }
  132. ref.reset(raw_ref);
  133. CFRef<CFDataRef> data(SecCertificateCopyData(ref.get()));
  134. if (!data) {
  135. A2_LOG_ERROR("Failed to get a data!");
  136. return false;
  137. }
  138. // Do try all supported hash algorithms.
  139. // Usually the fingerprint would be sha1 or md5, however this is more
  140. // future-proof. Also "usually" doesn't cut it; there is already software
  141. // using SHA-2 class algos, and SHA-3 is standardized and potential users
  142. // cannot be far.
  143. return std::find_if(std::begin(supported), std::end(supported),
  144. hash_finder(data.get(), fingerPrint)) !=
  145. std::end(supported);
  146. }
  147. #endif // defined(__MAC_10_6)
  148. } // namespace
  149. namespace aria2 {
  150. TLSContext* TLSContext::make(TLSSessionSide side, TLSVersion ver)
  151. {
  152. return new AppleTLSContext(side, ver);
  153. }
  154. AppleTLSContext::~AppleTLSContext()
  155. {
  156. if (credentials_) {
  157. CFRelease(credentials_);
  158. credentials_ = nullptr;
  159. }
  160. }
  161. bool AppleTLSContext::addCredentialFile(const std::string& certfile,
  162. const std::string& keyfile)
  163. {
  164. if (certfile.empty()) {
  165. return false;
  166. }
  167. if (tryAsFingerprint(certfile)) {
  168. return true;
  169. }
  170. if (tryAsPKCS12(certfile)) {
  171. return true;
  172. }
  173. A2_LOG_WARN("Only PKCS12/PFX files with a blank password and fingerprints of "
  174. "certificates in your KeyChain are supported. See the manual.");
  175. return false;
  176. }
  177. bool AppleTLSContext::addTrustedCACertFile(const std::string& certfile)
  178. {
  179. A2_LOG_INFO("TLS CA bundle files are not supported. Use the KeyChain to "
  180. "manage your certificates.");
  181. return false;
  182. }
  183. SecIdentityRef AppleTLSContext::getCredentials() { return credentials_; }
  184. bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint)
  185. {
  186. auto fp = stripWhitespace(fingerprint);
  187. // Verify this is a valid hex representation and normalize.
  188. fp = util::toHex(util::fromHex(std::begin(fp), std::end(fp)));
  189. // Verify this can represent a hash
  190. auto ht = MessageDigest::getSupportedHashTypes();
  191. if (std::find_if(std::begin(ht), std::end(ht), hash_validator(fp)) ==
  192. std::end(ht)) {
  193. A2_LOG_INFO(fmt("%s is not a fingerprint, invalid hash representation",
  194. fingerprint.c_str()));
  195. return false;
  196. }
  197. #if defined(__MAC_10_7)
  198. A2_LOG_DEBUG(fmt("Looking for cert with fingerprint %s", fp.c_str()));
  199. // Build and run the KeyChain the query.
  200. CFRef<SecPolicyRef> policy(SecPolicyCreateSSL(true, nullptr));
  201. if (!policy) {
  202. A2_LOG_ERROR("Failed to create SecPolicy");
  203. return false;
  204. }
  205. const void* query_values[] = {kSecClassIdentity, kCFBooleanTrue, policy.get(),
  206. kSecMatchLimitAll};
  207. CFRef<CFDictionaryRef> query(CFDictionaryCreate(
  208. nullptr, query_keys, query_values, 4, nullptr, nullptr));
  209. if (!query) {
  210. A2_LOG_ERROR("Failed to create identity query");
  211. return false;
  212. }
  213. CFArrayRef identities;
  214. OSStatus err = SecItemCopyMatching(query.get(), (CFTypeRef*)&identities);
  215. if (err != errSecSuccess) {
  216. A2_LOG_ERROR("Query failed: " + errToString(err));
  217. return false;
  218. }
  219. // Alrighty, search the fingerprint.
  220. const size_t nvals = CFArrayGetCount(identities);
  221. for (size_t i = 0; i < nvals; ++i) {
  222. SecIdentityRef id = (SecIdentityRef)CFArrayGetValueAtIndex(identities, i);
  223. if (!id) {
  224. A2_LOG_ERROR("Failed to get a value!");
  225. continue;
  226. }
  227. if (!checkIdentity(id, fp, ht)) {
  228. continue;
  229. }
  230. A2_LOG_INFO("Found cert with matching fingerprint");
  231. credentials_ = id;
  232. CFRetain(id);
  233. return true;
  234. }
  235. A2_LOG_ERROR(
  236. fmt("Failed to lookup %s in your KeyChain", fingerprint.c_str()));
  237. return false;
  238. #else // defined(__MAC_10_7)
  239. #if defined(__MAC_10_6)
  240. CFRef<SecIdentitySearchRef> search;
  241. SecIdentitySearchRef raw_search;
  242. // Deprecated as of 10.7
  243. OSStatus err = SecIdentitySearchCreate(0, CSSM_KEYUSE_SIGN, &raw_search);
  244. if (err != errSecSuccess) {
  245. A2_LOG_ERROR("Certificate search failed: " + errToString(err));
  246. }
  247. search.reset(raw_search);
  248. SecIdentityRef id;
  249. while (SecIdentitySearchCopyNext(search, &id) == errSecSuccess) {
  250. if (!checkIdentity(id, fp, ht)) {
  251. continue;
  252. }
  253. A2_LOG_INFO("Found cert with matching fingerprint");
  254. credentials_ = id;
  255. return true;
  256. }
  257. A2_LOG_ERROR(
  258. fmt("Failed to lookup %s in your KeyChain", fingerprint.c_str()));
  259. return false;
  260. #else // defined(__MAC_10_6)
  261. A2_LOG_ERROR("Your system does not support creditials via fingerprints; "
  262. "Upgrade to OSX 10.6 or later");
  263. return false;
  264. #endif // defined(__MAC_10_6)
  265. #endif // defined(__MAC_10_7)
  266. }
  267. bool AppleTLSContext::tryAsPKCS12(const std::string& certfile)
  268. {
  269. #if defined(__MAC_10_6)
  270. std::stringstream ss;
  271. BufferedFile(certfile.c_str(), BufferedFile::READ).transfer(ss);
  272. auto data = ss.str();
  273. if (data.empty()) {
  274. A2_LOG_ERROR("Couldn't read certificate file.");
  275. return false;
  276. }
  277. CFRef<CFDataRef> dataRef(
  278. CFDataCreate(nullptr, (const UInt8*)data.c_str(), data.size()));
  279. if (!dataRef) {
  280. A2_LOG_ERROR("Couldn't allocate PKCS12 data");
  281. return false;
  282. }
  283. return tryAsPKCS12(dataRef.get(), "") || tryAsPKCS12(dataRef.get(), nullptr);
  284. #else // defined(__MAC_10_6)
  285. A2_LOG_INFO("PKCS12 files are only supported in OSX 10.6 or later.");
  286. return false;
  287. #endif // defined(__MAC_10_6)
  288. }
  289. bool AppleTLSContext::tryAsPKCS12(CFDataRef data, const char* password)
  290. {
  291. #if defined(__MAC_10_6)
  292. CFRef<CFStringRef> passwordRef;
  293. if (password) {
  294. passwordRef.reset(CFStringCreateWithBytes(nullptr, (const UInt8*)password,
  295. strlen(password),
  296. kCFStringEncodingUTF8, false));
  297. }
  298. const void* keys[] = {kSecImportExportPassphrase};
  299. const void* values[] = {passwordRef.get()};
  300. CFRef<CFDictionaryRef> options(
  301. CFDictionaryCreate(nullptr, keys, values, 1, nullptr, nullptr));
  302. if (!options) {
  303. A2_LOG_ERROR("Failed to create options");
  304. return false;
  305. }
  306. CFRef<CFArrayRef> items;
  307. CFArrayRef raw_items = nullptr;
  308. OSStatus rv = SecPKCS12Import(data, options.get(), &raw_items);
  309. if (rv != errSecSuccess) {
  310. A2_LOG_DEBUG(
  311. fmt("Failed to parse PKCS12 data: %s", errToString(rv).c_str()));
  312. return false;
  313. }
  314. items.reset(raw_items);
  315. CFDictionaryRef idAndTrust =
  316. (CFDictionaryRef)CFArrayGetValueAtIndex(items.get(), 0);
  317. if (!idAndTrust) {
  318. A2_LOG_ERROR("Failed to get identity and trust from PKCS12 data");
  319. return false;
  320. }
  321. credentials_ =
  322. (SecIdentityRef)CFDictionaryGetValue(idAndTrust, kSecImportItemIdentity);
  323. if (!credentials_) {
  324. A2_LOG_ERROR("Failed to get credentials PKCS12 data");
  325. return false;
  326. }
  327. CFRetain(credentials_);
  328. A2_LOG_INFO("Loaded certificate from file");
  329. return true;
  330. #else // defined(__MAC_10_6)
  331. return false;
  332. #endif // defined(__MAC_10_6)
  333. }
  334. } // namespace aria2