Skip to content

Commit

Permalink
rpcclient: Add cookie auth
Browse files Browse the repository at this point in the history
Based on Hugo Landau's cookie auth implementation for Namecoin's ncdns.

Fixes btcsuite#1054
  • Loading branch information
JeremyRand committed Aug 2, 2019
1 parent c26ffa8 commit f9862a8
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 2 deletions.
64 changes: 64 additions & 0 deletions rpcclient/cookiefile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) 2017 The Namecoin developers
// Copyright (c) 2019 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package rpcclient

import (
"fmt"
"io/ioutil"
"os"
"strings"
"time"
)

func readCookieFile(path string) (username, password string, err error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return
}

s := strings.TrimSpace(string(b))
parts := strings.SplitN(s, ":", 2)
if len(parts) != 2 {
err = fmt.Errorf("malformed cookie file")
return
}

username, password = parts[0], parts[1]
return
}

func cookieRetriever(path string) func() (username, password string, err error) {
lastCheckTime := time.Time{}
lastModTime := time.Time{}

curUsername, curPassword := "", ""
var curError error

doUpdate := func() {
if !lastCheckTime.IsZero() && time.Now().Before(lastCheckTime.Add(30*time.Second)) {
return
}

lastCheckTime = time.Now()

st, err := os.Stat(path)
if err != nil {
curError = err
return
}

modTime := st.ModTime()
if !modTime.Equal(lastModTime) {
lastModTime = modTime
curUsername, curPassword, curError = readCookieFile(path)
}
}

return func() (username, password string, err error) {
doUpdate()
return curUsername, curPassword, curError
}
}
37 changes: 35 additions & 2 deletions rpcclient/infrastructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,12 @@ func (c *Client) sendPost(jReq *jsonRequest) {
httpReq.Header.Set("Content-Type", "application/json")

// Configure basic access authorization.
httpReq.SetBasicAuth(c.config.User, c.config.Pass)
user, pass, err := c.config.GetAuth()
if err != nil {
jReq.responseChan <- &response{result: nil, err: err}
return
}
httpReq.SetBasicAuth(user, pass)

log.Tracef("Sending command [%s] with id %d", jReq.method, jReq.id)
c.sendPostRequest(httpReq, jReq)
Expand Down Expand Up @@ -1065,6 +1070,15 @@ type ConnConfig struct {
// Pass is the passphrase to use to authenticate to the RPC server.
Pass string

// CookiePath is the path to a cookie file containing the username and
// passphrase to use to authenticate to the RPC server. It is used
// instead of User and Pass if non-empty.
CookiePath string

// retrieveCookie is a function that returns the cookie username and
// passphrase.
retrieveCookie func() (username, passphrase string, err error)

// DisableTLS specifies whether transport layer security should be
// disabled. It is recommended to always use TLS if the RPC server
// supports it as otherwise your username and password is sent across
Expand Down Expand Up @@ -1113,6 +1127,21 @@ type ConnConfig struct {
EnableBCInfoHacks bool
}

func (config *ConnConfig) GetAuth() (username, passphrase string, err error) {
// If cookie auth isn't in use, just use the supplied
// username/passphrase.
if config.CookiePath == "" {
return config.User, config.Pass, nil
}

// Initialize the cookie retriever on first run.
if config.retrieveCookie == nil {
config.retrieveCookie = cookieRetriever(config.CookiePath)
}

return config.retrieveCookie()
}

// newHTTPClient returns a new http client that is configured according to the
// proxy and TLS settings in the associated connection configuration.
func newHTTPClient(config *ConnConfig) (*http.Client, error) {
Expand Down Expand Up @@ -1182,7 +1211,11 @@ func dial(config *ConnConfig) (*websocket.Conn, error) {

// The RPC server requires basic authorization, so create a custom
// request header with the Authorization header set.
login := config.User + ":" + config.Pass
user, pass, err := config.GetAuth()
if err != nil {
return nil, err
}
login := user + ":" + pass
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
requestHeader := make(http.Header)
requestHeader.Add("Authorization", auth)
Expand Down

0 comments on commit f9862a8

Please sign in to comment.