1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #define TRACE_TAG AUTH 18 19 #include <dirent.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #if defined(__linux__) 24 #include <sys/inotify.h> 25 #endif 26 27 #include <map> 28 #include <mutex> 29 #include <set> 30 #include <string> 31 32 #include <android-base/errors.h> 33 #include <android-base/file.h> 34 #include <android-base/stringprintf.h> 35 #include <android-base/strings.h> 36 #include <crypto_utils/android_pubkey.h> 37 #include <openssl/base64.h> 38 #include <openssl/evp.h> 39 #include <openssl/objects.h> 40 #include <openssl/pem.h> 41 #include <openssl/rsa.h> 42 #include <openssl/sha.h> 43 44 #include "adb.h" 45 #include "adb_auth.h" 46 #include "adb_utils.h" 47 #include "sysdeps.h" 48 #include "transport.h" 49 50 static std::mutex& g_keys_mutex = *new std::mutex; 51 static std::map<std::string, std::shared_ptr<RSA>>& g_keys = 52 *new std::map<std::string, std::shared_ptr<RSA>>; 53 static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>; 54 55 static std::string get_user_info() { 56 LOG(INFO) << "get_user_info..."; 57 58 std::string hostname; 59 if (getenv("HOSTNAME")) hostname = getenv("HOSTNAME"); 60 #if !defined(_WIN32) 61 char buf[64]; 62 if (hostname.empty() && gethostname(buf, sizeof(buf)) != -1) hostname = buf; 63 #endif 64 if (hostname.empty()) hostname = "unknown"; 65 66 std::string username; 67 if (getenv("LOGNAME")) username = getenv("LOGNAME"); 68 #if !defined _WIN32 && !defined ADB_HOST_ON_TARGET 69 if (username.empty() && getlogin()) username = getlogin(); 70 #endif 71 if (username.empty()) hostname = "unknown"; 72 73 return " " + username + "@" + hostname; 74 } 75 76 static bool write_public_keyfile(RSA* private_key, const std::string& private_key_path) { 77 LOG(INFO) << "write_public_keyfile..."; 78 79 uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE]; 80 if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) { 81 LOG(ERROR) << "Failed to convert to public key"; 82 return false; 83 } 84 85 size_t expected_length; 86 if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) { 87 LOG(ERROR) << "Public key too large to base64 encode"; 88 return false; 89 } 90 91 std::string content; 92 content.resize(expected_length); 93 size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&content[0]), binary_key_data, 94 sizeof(binary_key_data)); 95 content.resize(actual_length); 96 97 content += get_user_info(); 98 99 std::string path(private_key_path + ".pub"); 100 if (!android::base::WriteStringToFile(content, path)) { 101 PLOG(ERROR) << "Failed to write public key to '" << path << "'"; 102 return false; 103 } 104 105 return true; 106 } 107 108 static int generate_key(const std::string& file) { 109 LOG(INFO) << "generate_key(" << file << ")..."; 110 111 mode_t old_mask; 112 FILE *f = NULL; 113 int ret = 0; 114 115 EVP_PKEY* pkey = EVP_PKEY_new(); 116 BIGNUM* exponent = BN_new(); 117 RSA* rsa = RSA_new(); 118 if (!pkey || !exponent || !rsa) { 119 LOG(ERROR) << "Failed to allocate key"; 120 goto out; 121 } 122 123 BN_set_word(exponent, RSA_F4); 124 RSA_generate_key_ex(rsa, 2048, exponent, NULL); 125 EVP_PKEY_set1_RSA(pkey, rsa); 126 127 old_mask = umask(077); 128 129 f = fopen(file.c_str(), "w"); 130 if (!f) { 131 PLOG(ERROR) << "Failed to open " << file; 132 umask(old_mask); 133 goto out; 134 } 135 136 umask(old_mask); 137 138 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) { 139 D("Failed to write key"); 140 goto out; 141 } 142 143 if (!write_public_keyfile(rsa, file)) { 144 D("Failed to write public key"); 145 goto out; 146 } 147 148 ret = 1; 149 150 out: 151 if (f) fclose(f); 152 EVP_PKEY_free(pkey); 153 RSA_free(rsa); 154 BN_free(exponent); 155 return ret; 156 } 157 158 static std::string hash_key(RSA* key) { 159 unsigned char* pubkey = nullptr; 160 int len = i2d_RSA_PUBKEY(key, &pubkey); 161 if (len < 0) { 162 LOG(ERROR) << "failed to encode RSA public key"; 163 return std::string(); 164 } 165 166 std::string result; 167 result.resize(SHA256_DIGEST_LENGTH); 168 SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0])); 169 OPENSSL_free(pubkey); 170 return result; 171 } 172 173 static bool read_key_file(const std::string& file) { 174 LOG(INFO) << "read_key_file '" << file << "'..."; 175 176 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose); 177 if (!fp) { 178 PLOG(ERROR) << "Failed to open '" << file << "'"; 179 return false; 180 } 181 182 RSA* key = RSA_new(); 183 if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) { 184 LOG(ERROR) << "Failed to read key"; 185 RSA_free(key); 186 return false; 187 } 188 189 std::lock_guard<std::mutex> lock(g_keys_mutex); 190 std::string fingerprint = hash_key(key); 191 if (g_keys.find(fingerprint) != g_keys.end()) { 192 LOG(INFO) << "ignoring already-loaded key: " << file; 193 RSA_free(key); 194 } else { 195 g_keys[fingerprint] = std::shared_ptr<RSA>(key, RSA_free); 196 } 197 198 return true; 199 } 200 201 static bool read_keys(const std::string& path, bool allow_dir = true) { 202 LOG(INFO) << "read_keys '" << path << "'..."; 203 204 struct stat st; 205 if (stat(path.c_str(), &st) != 0) { 206 PLOG(ERROR) << "failed to stat '" << path << "'"; 207 return false; 208 } 209 210 if (S_ISREG(st.st_mode)) { 211 return read_key_file(path); 212 } else if (S_ISDIR(st.st_mode)) { 213 if (!allow_dir) { 214 // inotify isn't recursive. It would break expectations to load keys in nested 215 // directories but not monitor them for new keys. 216 LOG(WARNING) << "refusing to recurse into directory '" << path << "'"; 217 return false; 218 } 219 220 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir); 221 if (!dir) { 222 PLOG(ERROR) << "failed to open directory '" << path << "'"; 223 return false; 224 } 225 226 bool result = false; 227 while (struct dirent* dent = readdir(dir.get())) { 228 std::string name = dent->d_name; 229 230 // We can't use dent->d_type here because it's not available on Windows. 231 if (name == "." || name == "..") { 232 continue; 233 } 234 235 if (!android::base::EndsWith(name, ".adb_key")) { 236 LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'"; 237 continue; 238 } 239 240 result |= read_key_file((path + OS_PATH_SEPARATOR + name)); 241 } 242 return result; 243 } 244 245 LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode; 246 return false; 247 } 248 249 static std::string get_user_key_path() { 250 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey"; 251 } 252 253 static bool get_user_key() { 254 std::string path = get_user_key_path(); 255 if (path.empty()) { 256 PLOG(ERROR) << "Error getting user key filename"; 257 return false; 258 } 259 260 struct stat buf; 261 if (stat(path.c_str(), &buf) == -1) { 262 LOG(INFO) << "User key '" << path << "' does not exist..."; 263 if (!generate_key(path)) { 264 LOG(ERROR) << "Failed to generate new key"; 265 return false; 266 } 267 } 268 269 return read_key_file(path); 270 } 271 272 static std::set<std::string> get_vendor_keys() { 273 const char* adb_keys_path = getenv("ADB_VENDOR_KEYS"); 274 if (adb_keys_path == nullptr) { 275 return std::set<std::string>(); 276 } 277 278 std::set<std::string> result; 279 for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) { 280 result.emplace(path); 281 } 282 return result; 283 } 284 285 std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() { 286 std::deque<std::shared_ptr<RSA>> result; 287 288 // Copy all the currently known keys. 289 std::lock_guard<std::mutex> lock(g_keys_mutex); 290 for (const auto& it : g_keys) { 291 result.push_back(it.second); 292 } 293 294 // Add a sentinel to the list. Our caller uses this to mean "out of private keys, 295 // but try using the public key" (the empty deque could otherwise mean this _or_ 296 // that this function hasn't been called yet to request the keys). 297 result.push_back(nullptr); 298 299 return result; 300 } 301 302 static std::string adb_auth_sign(RSA* key, const char* token, size_t token_size) { 303 if (token_size != TOKEN_SIZE) { 304 D("Unexpected token size %zd", token_size); 305 return 0; 306 } 307 308 std::string result; 309 result.resize(MAX_PAYLOAD); 310 311 unsigned int len; 312 if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size, 313 reinterpret_cast<uint8_t*>(&result[0]), &len, key)) { 314 return std::string(); 315 } 316 317 result.resize(len); 318 319 D("adb_auth_sign len=%d", len); 320 return result; 321 } 322 323 std::string adb_auth_get_userkey() { 324 std::string path = get_user_key_path(); 325 if (path.empty()) { 326 PLOG(ERROR) << "Error getting user key filename"; 327 return ""; 328 } 329 path += ".pub"; 330 331 std::string content; 332 if (!android::base::ReadFileToString(path, &content)) { 333 PLOG(ERROR) << "Can't load '" << path << "'"; 334 return ""; 335 } 336 return content; 337 } 338 339 int adb_auth_keygen(const char* filename) { 340 return (generate_key(filename) == 0); 341 } 342 343 #if defined(__linux__) 344 static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) { 345 LOG(INFO) << "adb_auth_inotify_update called"; 346 if (!(fd_event & FDE_READ)) { 347 return; 348 } 349 350 char buf[sizeof(struct inotify_event) + NAME_MAX + 1]; 351 while (true) { 352 ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf))); 353 if (rc == -1) { 354 if (errno == EAGAIN) { 355 LOG(INFO) << "done reading inotify fd"; 356 break; 357 } 358 PLOG(FATAL) << "read of inotify event failed"; 359 } 360 361 // The read potentially returned multiple events. 362 char* start = buf; 363 char* end = buf + rc; 364 365 while (start < end) { 366 inotify_event* event = reinterpret_cast<inotify_event*>(start); 367 auto root_it = g_monitored_paths.find(event->wd); 368 if (root_it == g_monitored_paths.end()) { 369 LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd; 370 } 371 372 std::string path = root_it->second; 373 if (event->len > 0) { 374 path += '/'; 375 path += event->name; 376 } 377 378 if (event->mask & (IN_CREATE | IN_MOVED_TO)) { 379 if (event->mask & IN_ISDIR) { 380 LOG(INFO) << "ignoring new directory at '" << path << "'"; 381 } else { 382 LOG(INFO) << "observed new file at '" << path << "'"; 383 read_keys(path, false); 384 } 385 } else { 386 LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex 387 << event->mask; 388 } 389 390 start += sizeof(struct inotify_event) + event->len; 391 } 392 } 393 } 394 395 static void adb_auth_inotify_init(const std::set<std::string>& paths) { 396 LOG(INFO) << "adb_auth_inotify_init..."; 397 398 int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK); 399 if (infd < 0) { 400 PLOG(ERROR) << "failed to create inotify fd"; 401 return; 402 } 403 404 for (const std::string& path : paths) { 405 int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO); 406 if (wd < 0) { 407 PLOG(ERROR) << "failed to inotify_add_watch on path '" << path; 408 continue; 409 } 410 411 g_monitored_paths[wd] = path; 412 LOG(INFO) << "watch descriptor " << wd << " registered for " << path; 413 } 414 415 fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr); 416 fdevent_add(event, FDE_READ); 417 } 418 #endif 419 420 void adb_auth_init() { 421 LOG(INFO) << "adb_auth_init..."; 422 423 if (!get_user_key()) { 424 LOG(ERROR) << "Failed to get user key"; 425 return; 426 } 427 428 const auto& key_paths = get_vendor_keys(); 429 430 #if defined(__linux__) 431 adb_auth_inotify_init(key_paths); 432 #endif 433 434 for (const std::string& path : key_paths) { 435 read_keys(path.c_str()); 436 } 437 } 438 439 static void send_auth_publickey(atransport* t) { 440 LOG(INFO) << "Calling send_auth_publickey"; 441 442 std::string key = adb_auth_get_userkey(); 443 if (key.empty()) { 444 D("Failed to get user public key"); 445 return; 446 } 447 448 if (key.size() >= MAX_PAYLOAD_V1) { 449 D("User public key too large (%zu B)", key.size()); 450 return; 451 } 452 453 apacket* p = get_apacket(); 454 p->msg.command = A_AUTH; 455 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY; 456 457 p->payload = std::move(key); 458 459 // adbd expects a null-terminated string. 460 p->payload.push_back('\0'); 461 p->msg.data_length = p->payload.size(); 462 send_packet(p, t); 463 } 464 465 void send_auth_response(const char* token, size_t token_size, atransport* t) { 466 std::shared_ptr<RSA> key = t->NextKey(); 467 if (key == nullptr) { 468 // No more private keys to try, send the public key. 469 send_auth_publickey(t); 470 return; 471 } 472 473 LOG(INFO) << "Calling send_auth_response"; 474 apacket* p = get_apacket(); 475 476 std::string result = adb_auth_sign(key.get(), token, token_size); 477 if (result.empty()) { 478 D("Error signing the token"); 479 put_apacket(p); 480 return; 481 } 482 483 p->msg.command = A_AUTH; 484 p->msg.arg0 = ADB_AUTH_SIGNATURE; 485 p->payload = std::move(result); 486 p->msg.data_length = p->payload.size(); 487 send_packet(p, t); 488 } 489