Skip to content

Commit

Permalink
auth: allow using a local server pub key
Browse files Browse the repository at this point in the history
  • Loading branch information
julienschmidt committed May 25, 2018
1 parent e902149 commit cee8f7d
Show file tree
Hide file tree
Showing 5 changed files with 360 additions and 29 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,19 @@ other cases. You should ensure your application will never cause an ERROR 1290
except for `read-only` mode when enabling this option.


##### `serverPubKey`

```
Type: string
Valid Values: <name>
Default: none
```

Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN.
Public keys are used to transmit encrypted data, e.g. for authentication.
If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required.


##### `timeout`

```
Expand Down
129 changes: 102 additions & 27 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,72 @@ import (
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"sync"
)

// server pub keys registry
var (
serverPubKeyLock sync.RWMutex
serverPubKeyRegistry map[string]*rsa.PublicKey
)

// RegisterServerPubKey registers a server RSA public key which can be used to
// send data in a secure manner to the server without receiving the public key
// in a potentially insecure way from the server first.
// Registered keys can afterwards be used adding serverPubKey=<name> to the DSN.
//
// Note: The provided rsa.PublicKey instance is exclusively owned by the driver
// after registering it and may not be modified.
//
// data, err := ioutil.ReadFile("mykey.pem")
// if err != nil {
// log.Fatal(err)
// }
//
// block, _ := pem.Decode(data)
// if block == nil || block.Type != "PUBLIC KEY" {
// log.Fatal("failed to decode PEM block containing public key")
// }
//
// pub, err := x509.ParsePKIXPublicKey(block.Bytes)
// if err != nil {
// log.Fatal(err)
// }
//
// if rsaPubKey, ok := pub.(*rsa.PublicKey); ok {
// mysql.RegisterServerPubKey("mykey", rsaPubKey)
// } else {
// log.Fatal("not a RSA public key")
// }
//
func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) {
serverPubKeyLock.Lock()
if serverPubKeyRegistry == nil {
serverPubKeyRegistry = make(map[string]*rsa.PublicKey)
}

serverPubKeyRegistry[name] = pubKey
serverPubKeyLock.Unlock()
}

// DeregisterServerPubKey removes the public key registered with the given name.
func DeregisterServerPubKey(name string) {
serverPubKeyLock.Lock()
if serverPubKeyRegistry != nil {
delete(serverPubKeyRegistry, name)
}
serverPubKeyLock.Unlock()
}

func getServerPubKey(name string) (pubKey *rsa.PublicKey) {
serverPubKeyLock.RLock()
if v, ok := serverPubKeyRegistry[name]; ok {
pubKey = v
}
serverPubKeyLock.RUnlock()
return
}

// Hash password using pre 4.1 (old password) method
// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c
type myRnd struct {
Expand Down Expand Up @@ -154,19 +218,22 @@ func scrambleSHA256Password(scramble []byte, password string) []byte {
return message1
}

func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error {
plain := make([]byte, len(mc.cfg.Passwd)+1)
copy(plain, mc.cfg.Passwd)
func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) {
plain := make([]byte, len(password)+1)
copy(plain, password)
for i := range plain {
j := i % len(seed)
plain[i] ^= seed[j]
}
sha1 := sha1.New()
enc, err := rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil)
return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil)
}

func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error {
enc, err := encryptPassword(mc.cfg.Passwd, seed, pub)
if err != nil {
return err
}

return mc.writeAuthSwitchPacket(enc, false)
}

Expand Down Expand Up @@ -211,9 +278,16 @@ func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, bool, error)
// write cleartext auth packet
return []byte(mc.cfg.Passwd), true, nil
}
// request public key
// TODO: allow to specify a local file with the pub key via the DSN
return []byte{1}, false, nil

pubKey := mc.cfg.pubKey
if pubKey == nil {
// request public key from server
return []byte{1}, false, nil
}

// encrypted password
enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey)
return enc, false, err

default:
errLog.Print("unknown auth plugin:", plugin)
Expand Down Expand Up @@ -283,28 +357,29 @@ func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error {
return err
}
} else {
// TODO: allow to specify a local file with the pub key via
// the DSN

// request public key
data := mc.buf.takeSmallBuffer(4 + 1)
data[4] = cachingSha2PasswordRequestPublicKey
mc.writePacket(data)

// parse public key
data, err := mc.readPacket()
if err != nil {
return err
}

block, _ := pem.Decode(data[1:])
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
pubKey := mc.cfg.pubKey
if pubKey == nil {
// request public key from server
data := mc.buf.takeSmallBuffer(4 + 1)
data[4] = cachingSha2PasswordRequestPublicKey
mc.writePacket(data)

// parse public key
data, err := mc.readPacket()
if err != nil {
return err
}

block, _ := pem.Decode(data[1:])
pkix, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
pubKey = pkix.(*rsa.PublicKey)
}

// send encrypted password
err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey))
err = mc.sendEncryptedPassword(oldAuthData, pubKey)
if err != nil {
return err
}
Expand Down
Loading

0 comments on commit cee8f7d

Please sign in to comment.