Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

privilege,session: Match loopback connections to 'localhost' accounts (#29995) #30189

Merged
merged 3 commits into from
Dec 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions privilege/privileges/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,9 @@ func decodeSetToPrivilege(s types.Set) mysql.PrivilegeType {
// See https://dev.mysql.com/doc/refman/5.7/en/account-names.html
func (record *baseRecord) hostMatch(s string) bool {
if record.hostIPNet == nil {
if record.Host == "localhost" && net.ParseIP(s).IsLoopback() {
return true
}
return false
}
ip := net.ParseIP(s).To4()
Expand Down
10 changes: 8 additions & 2 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1890,7 +1890,7 @@ func getStmtCnt(content string) (stmtCnt map[string]int) {

const retryTime = 100

func (cli *testServerClient) waitUntilServerOnline() {
func (cli *testServerClient) waitUntilServerCanConnect() {
// connect server
retry := 0
for ; retry < retryTime; retry++ {
Expand All @@ -1907,8 +1907,14 @@ func (cli *testServerClient) waitUntilServerOnline() {
if retry == retryTime {
log.Fatal("failed to connect DB in every 10 ms", zap.Int("retryTime", retryTime))
}
}

for retry = 0; retry < retryTime; retry++ {
func (cli *testServerClient) waitUntilServerOnline() {
// connect server
cli.waitUntilServerCanConnect()

retry := 0
for ; retry < retryTime; retry++ {
// fetch http status
resp, err := cli.fetchStatus("/status")
if err == nil {
Expand Down
116 changes: 109 additions & 7 deletions server/tidb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ func TestSocketAndIp(t *testing.T) {
err := server.Run()
require.NoError(t, err)
}()
time.Sleep(time.Millisecond * 100)
cli.waitUntilServerCanConnect()
defer server.Close()

// Test with Socket connection + Setup user1@% for all host access
Expand Down Expand Up @@ -686,17 +686,19 @@ func TestOnlySocket(t *testing.T) {
db, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) {
config.User = "root"
config.DBName = "test"
config.Addr = "127.0.0.1"
}))
require.NoErrorf(t, err, "Connect succeeded when not configured!?!")
defer db.Close()
require.NoErrorf(t, err, "Open failed")
err = db.Ping()
require.Errorf(t, err, "Connect succeeded when not configured!?!")
db.Close()
db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) {
config.User = "user1"
config.DBName = "test"
config.Addr = "127.0.0.1"
}))
require.NoErrorf(t, err, "Connect succeeded when not configured!?!")
defer db.Close()
require.NoErrorf(t, err, "Open failed")
err = db.Ping()
require.Errorf(t, err, "Connect succeeded when not configured!?!")
db.Close()
// Test with unix domain socket file connection with all hosts
cli.runTests(t, func(config *mysql.Config) {
config.Net = "unix"
Expand Down Expand Up @@ -1674,3 +1676,103 @@ func (ts *tidbTestTopSQLSuite) loopExec(ctx context.Context, t *testing.T, fn fu
fn(db)
}
}

func TestLocalhostClientMapping(t *testing.T) {
t.Parallel()
osTempDir := os.TempDir()
tempDir, err := os.MkdirTemp(osTempDir, "tidb-test.*.socket")
require.NoError(t, err)
socketFile := tempDir + "/tidbtest.sock" // Unix Socket does not work on Windows, so '/' should be OK
defer os.RemoveAll(tempDir)

cli := newTestServerClient()
cfg := newTestConfig()
cfg.Socket = socketFile
cfg.Port = cli.port
cfg.Status.ReportStatus = false

ts, cleanup := createTidbTestSuite(t)
defer cleanup()

server, err := NewServer(cfg, ts.tidbdrv)
require.NoError(t, err)
cli.port = getPortFromTCPAddr(server.listener.Addr())
go func() {
err := server.Run()
require.NoError(t, err)
}()
defer server.Close()
cli.waitUntilServerCanConnect()

cli.port = getPortFromTCPAddr(server.listener.Addr())
// Create a db connection for root
db, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) {
config.User = "root"
config.Net = "unix"
config.DBName = "test"
config.Addr = socketFile
}))
require.NoErrorf(t, err, "Open failed")
err = db.Ping()
require.NoErrorf(t, err, "Ping failed")
defer db.Close()
dbt := testkit.NewDBTestKit(t, db)
rows := dbt.MustQuery("select user()")
cli.checkRows(t, rows, "root@localhost")
rows = dbt.MustQuery("show grants")
cli.checkRows(t, rows, "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION")

dbt.MustExec("CREATE USER 'localhostuser'@'localhost'")
dbt.MustExec("CREATE USER 'localhostuser'@'%'")
defer func() {
dbt.MustExec("DROP USER IF EXISTS 'localhostuser'@'%'")
dbt.MustExec("DROP USER IF EXISTS 'localhostuser'@'localhost'")
dbt.MustExec("DROP USER IF EXISTS 'localhostuser'@'127.0.0.1'")
}()

dbt.MustExec("GRANT SELECT ON test.* TO 'localhostuser'@'%'")
dbt.MustExec("GRANT SELECT,UPDATE ON test.* TO 'localhostuser'@'localhost'")

// Test with loopback interface - Should get access to localhostuser@localhost!
cli.runTests(t, func(config *mysql.Config) {
config.User = "localhostuser"
config.DBName = "test"
},
func(dbt *testkit.DBTestKit) {
rows := dbt.MustQuery("select user()")
// NOTICE: this is not compatible with MySQL! (MySQL would report localhostuser@localhost also for 127.0.0.1)
cli.checkRows(t, rows, "[email protected]")
rows = dbt.MustQuery("show grants")
cli.checkRows(t, rows, "GRANT USAGE ON *.* TO 'localhostuser'@'localhost'\nGRANT SELECT,UPDATE ON test.* TO 'localhostuser'@'localhost'")
})

dbt.MustExec("DROP USER IF EXISTS 'localhostuser'@'localhost'")
dbt.MustExec("CREATE USER 'localhostuser'@'127.0.0.1'")
dbt.MustExec("GRANT SELECT,UPDATE ON test.* TO 'localhostuser'@'127.0.0.1'")
// Test with unix domain socket file connection - Should get access to '%'
cli.runTests(t, func(config *mysql.Config) {
config.Net = "unix"
config.Addr = socketFile
config.User = "localhostuser"
config.DBName = "test"
},
func(dbt *testkit.DBTestKit) {
rows := dbt.MustQuery("select user()")
cli.checkRows(t, rows, "localhostuser@localhost")
rows = dbt.MustQuery("show grants")
cli.checkRows(t, rows, "GRANT USAGE ON *.* TO 'localhostuser'@'%'\nGRANT SELECT ON test.* TO 'localhostuser'@'%'")
})

// Test if only localhost exists
dbt.MustQuery("DROP USER 'localhostuser'@'%'")
dbSocket, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) {
config.User = "localhostuser"
config.Net = "unix"
config.DBName = "test"
config.Addr = socketFile
}))
require.NoErrorf(t, err, "Open failed")
defer dbSocket.Close()
err = dbSocket.Ping()
require.Errorf(t, err, "Connection successful without matching host for unix domain socket!")
}
2 changes: 1 addition & 1 deletion session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -2287,7 +2287,7 @@ func (s *session) AuthWithoutVerification(user *auth.UserIdentity) bool {
}

func (s *session) getHostByIP(ip string) []string {
if ip == "127.0.0.1" {
if net.ParseIP(ip).IsLoopback() {
return []string{variable.DefHostname}
}
skipNameResolve, err := s.GetSessionVars().GlobalVarsAccessor.GetGlobalSysVar(variable.SkipNameResolve)
Expand Down