chenBright commented on code in PR #3779:
URL: https://github.com/apache/brpc/pull/3779#discussion_r4729585378
##########
src/brpc/policy/mysql/mysql_authenticator.cpp:
##########
@@ -82,39 +104,52 @@ bool MysqlAuthenticator::SerializeToString(std::string*
str) const {
LOG(ERROR) << "handle mysql authentication params failed, ignore it";
return false;
}
+ std::string encoded_key;
+ butil::Base64Encode(_server_public_key, &encoded_key);
+ ss << auth_param_delim << encoded_key;
*str = ss.str();
return true;
}
-void MysqlParseAuthenticator(const butil::StringPiece& raw,
+bool MysqlParseAuthenticator(const butil::StringPiece& raw,
std::string* user,
std::string* password,
std::string* schema,
- std::string* collation) {
- std::vector<size_t> idx;
- idx.reserve(4);
- for (size_t p = raw.find(auth_param_delim); p != butil::StringPiece::npos;
- p = raw.find(auth_param_delim, p + 1)) {
- idx.push_back(p);
- }
- if (idx.size() < 4) {
+ std::string* collation,
+ std::string* server_public_key) {
+ std::vector<butil::StringPiece> fields;
+ MysqlSplitAuthFields(raw, &fields);
+ user->clear();
+ password->clear();
+ schema->clear();
+ collation->clear();
+ server_public_key->clear();
+ // MysqlAuthenticator::SerializeToString() always writes user, password,
+ // schema, collation and params, so anything shorter is malformed.
+ if (fields.size() < 5) {
LOG(ERROR) << "malformed mysql authentication string, expected at
least 4 '\\t' "
- "delimiters but found " << idx.size();
- user->clear();
- password->clear();
- schema->clear();
- collation->clear();
- return;
+ "delimiters but found " << (fields.size() - 1);
+ return false;
}
- user->assign(raw.data(), 0, idx[0]);
- password->assign(raw.data(), idx[0] + 1, idx[1] - idx[0] - 1);
- schema->assign(raw.data(), idx[1] + 1, idx[2] - idx[1] - 1);
- collation->assign(raw.data(), idx[2] + 1, idx[3] - idx[2] - 1);
+ user->assign(fields[0].data(), fields[0].size());
+ password->assign(fields[1].data(), fields[1].size());
+ schema->assign(fields[2].data(), fields[2].size());
+ collation->assign(fields[3].data(), fields[3].size());
+ if (fields.size() >= 6 && !fields[5].empty() &&
+ !butil::Base64Decode(fields[5], server_public_key)) {
+ LOG(ERROR) << "malformed base64 server public key in mysql
authentication string";
+ return false;
Review Comment:
`param_cmd` can contain literal tab characters, but this code always treats
`fields[5]` as the public key. As a result, even when the context is generated
by the local `SerializeToString()`, the second SQL statement in the connection
parameters may be passed to `Base64Decode()`, causing an otherwise valid
connection to fail during the greeting phase. Please use unambiguous field
boundaries for the parameters and public key, and test that both can be
recovered unchanged.
##########
src/brpc/policy/mysql/mysql_protocol.cpp:
##########
@@ -224,8 +249,23 @@ ParseError HandleAuthentication(const InputResponse* msg,
const Socket* socket,
WriteMysqlAuthPacket(socket->fd(), clear, next_seq);
const_cast<AuthContext*>(ctx)->set_group(kCacheSha2Sent);
} else {
- // Plain TCP: request the server's RSA public key (0x02), then
- // wait for the AuthMoreData carrying the PEM.
+ // Plain TCP: the server's public key can only arrive in-band,
+ // so encrypting the password with it would hand the password
+ // to any man-in-the-middle. Require an out-of-band pin.
+ if (server_public_key.empty()) {
+ parseCode = PARSE_ERROR_ABSOLUTELY_WRONG;
+ LOG(ERROR) << "[MYSQL PARSE] caching_sha2_password full
authentication "
+ "over a non-TLS connection requires a pinned
server public "
+ "key; use TLS or
MysqlAuthenticator::set_server_public_key()";
+ *error_desc = "Fail to authenticate with Mysql:
caching_sha2_password full "
+ "authentication over a non-TLS connection
requires a pinned "
+ "server public key (use TLS or "
+ "MysqlAuthenticator::set_server_public_key)";
Review Comment:
The `use TLS` advice here leads users connecting directly to `mysqld` down a
recovery path that will not work. `Channel` starts the TLS handshake
immediately after establishing the TCP connection, whereas MySQL must first
receive the greeting and send an `SSLRequest` before upgrading the connection.
The current test only checks the password payload. Consider recommending only
`set_server_public_key()` for now in the error message, setter comment, and
client documentation. [MySQL connection phase
protocol](https://dev.mysql.com/doc/dev/mysql-server/8.0.46/page_protocol_connection_phase.html)
##########
src/brpc/policy/mysql/mysql_protocol.cpp:
##########
@@ -224,8 +249,23 @@ ParseError HandleAuthentication(const InputResponse* msg,
const Socket* socket,
WriteMysqlAuthPacket(socket->fd(), clear, next_seq);
const_cast<AuthContext*>(ctx)->set_group(kCacheSha2Sent);
} else {
- // Plain TCP: request the server's RSA public key (0x02), then
- // wait for the AuthMoreData carrying the PEM.
+ // Plain TCP: the server's public key can only arrive in-band,
+ // so encrypting the password with it would hand the password
+ // to any man-in-the-middle. Require an out-of-band pin.
+ if (server_public_key.empty()) {
+ parseCode = PARSE_ERROR_ABSOLUTELY_WRONG;
Review Comment:
The new missing-public-key branch will also reject four example programs
bundled with the repository, including `mysql_cli`, but they currently have no
command-line option for supplying a trusted PEM. After the server's
authentication cache is cleared, users cannot continue using these programs
even if they have the correct public key. Please add a consistent public-key
file argument to the examples and call the setter before `Channel::Init()`.
##########
src/brpc/policy/mysql/mysql_auth_scramble.cpp:
##########
@@ -38,6 +40,119 @@ bool Sha256Bytes(const unsigned char* data, size_t len,
unsigned char out[32]) {
&& digest_len == 32;
}
+// Appends |len| in DER length encoding.
+void AppendDerLength(size_t len, std::string* out) {
+ if (len < 0x80) {
+ out->push_back(static_cast<char>(len));
+ return;
+ }
+ char bytes[sizeof(size_t)];
+ size_t n = 0;
+ while (len > 0) {
+ bytes[n++] = static_cast<char>(len & 0xff);
+ len >>= 8;
+ }
+ out->push_back(static_cast<char>(0x80 | n));
+ while (n > 0) {
+ out->push_back(bytes[--n]);
+ }
+}
+
+// Decodes the base64 body of the PEM block delimited by |label|.
+bool DecodePemBody(const butil::StringPiece& pem, const char* label,
+ std::string* der) {
+ const std::string begin = std::string("-----BEGIN ") + label + "-----";
+ const std::string end = std::string("-----END ") + label + "-----";
+ const size_t b = pem.find(begin);
+ const size_t e = pem.find(end);
+ if (b == butil::StringPiece::npos || e == butil::StringPiece::npos ||
+ e < b + begin.size()) {
+ return false;
+ }
+ std::string body;
+ for (size_t i = b + begin.size(); i < e; ++i) {
+ const char c = pem[i];
+ if (c != '\r' && c != '\n' && c != ' ' && c != '\t') {
+ body.push_back(c);
+ }
+ }
+ return butil::Base64Decode(body, der);
+}
+
+// Wraps a PKCS#1 RSAPublicKey DER in a SubjectPublicKeyInfo DER:
+// SEQUENCE {
+// SEQUENCE { OID rsaEncryption, NULL },
+// BIT STRING { unused-bits=0, RSAPublicKey }
+// }
+std::string WrapRsaPublicKeyAsSubjectPublicKeyInfo(const std::string& pkcs1) {
+ static const char kRsaAlgorithmIdentifier[] =
+ "\x30\x0d" // SEQUENCE, 13 bytes
+ "\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01" // OID rsaEncryption
+ "\x05\x00"; // NULL
+ std::string bit_string;
+ bit_string.push_back('\0'); // no unused bits
+ bit_string.append(pkcs1);
+ std::string bit_string_tlv;
+ bit_string_tlv.push_back('\x03');
+ AppendDerLength(bit_string.size(), &bit_string_tlv);
+ bit_string_tlv.append(bit_string);
+
+ std::string spki;
+ spki.push_back('\x30');
+ AppendDerLength(sizeof(kRsaAlgorithmIdentifier) - 1 +
bit_string_tlv.size(), &spki);
+ spki.append(kRsaAlgorithmIdentifier, sizeof(kRsaAlgorithmIdentifier) - 1);
+ spki.append(bit_string_tlv);
+ return spki;
+}
+
+// Parses a PEM-encoded public key. Both "BEGIN PUBLIC KEY"
+// (SubjectPublicKeyInfo) and "BEGIN RSA PUBLIC KEY" (PKCS#1) are accepted.
+// Returns nullptr when |pem| is not a parseable public key.
+EVP_PKEY* ReadPublicKeyPem(const butil::StringPiece& pem) {
+ if (pem.empty()) {
+ return nullptr;
+ }
+ // PEM_read_bio_PUBKEY() does not read the PKCS#1 form on every supported
+ // OpenSSL version, so normalize that form to SubjectPublicKeyInfo and
+ // decode it uniformly.
+ if (pem.find("-----BEGIN RSA PUBLIC KEY-----") !=
butil::StringPiece::npos) {
+ std::string pkcs1;
+ if (!DecodePemBody(pem, "RSA PUBLIC KEY", &pkcs1)) {
+ return nullptr;
+ }
+ const std::string spki = WrapRsaPublicKeyAsSubjectPublicKeyInfo(pkcs1);
+ const unsigned char* p = reinterpret_cast<const unsigned
char*>(spki.data());
+ return d2i_PUBKEY(nullptr, &p, static_cast<long>(spki.size()));
Review Comment:
This PKCS#1 branch retains the decoded result before OpenSSL validates the
public key and creates three additional DER buffers of roughly the same size.
The input comes from a server that has not yet been authenticated, and the
MySQL packet size is much larger than what a normal public key requires. Please
set a public key size limit before decoding to avoid multiplying temporary
allocations for an abnormal response on each connection attempt.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]