Skip to content

Feature: simplify tls setup #2567

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions dgraph/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/p
/w
/zw
/tls
187 changes: 187 additions & 0 deletions dgraph/cmd/cm/cert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* Copyright 2017-2018 Dgraph Labs, Inc.
*
* This file is available under the Apache License, Version 2.0,
* with the Commons Clause restriction.
*/

package cm

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
)

// makeKey generates an RSA private key of bitSize length, storing it in the
// file fn. If force is true, the file is replaced.
// Returns the RSA private key, or error otherwise.
func makeKey(fn string, bitSize int, force bool) (*rsa.PrivateKey, error) {
flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
if !force {
flag |= os.O_EXCL
}

f, err := os.OpenFile(fn, flag, 0400)
if err != nil {
// reuse the existing key, if possible.
if os.IsExist(err) {
return readKey(fn)
}
return nil, err
}
defer f.Close()

key, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, err
}

err = pem.Encode(f, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
if err != nil {
return nil, err
}

return key, nil
}

// readKey tries to read and decode the contents of a private key at fn.
// Returns the RSA private key, or error otherwise.
func readKey(fn string) (*rsa.PrivateKey, error) {
b, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}

block, _ := pem.Decode(b)
switch {
case block == nil:
return nil, fmt.Errorf("failed to read key block")
case block.Type != "RSA PRIVATE KEY":
return nil, fmt.Errorf("unknown PEM type: %s", block.Type)
}

return x509.ParsePKCS1PrivateKey(block.Bytes)
}

// readCert tries to read and decode the contents of an RSA-signed cert at fn.
// Returns the x509v3 cert, or error otherwise.
func readCert(fn string) (*x509.Certificate, error) {
b, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}

block, _ := pem.Decode(b)
switch {
case block == nil:
return nil, fmt.Errorf("failed to read cert block")
case block.Type != "CERTIFICATE":
return nil, fmt.Errorf("unknown PEM type: %s", block.Type)
}

return x509.ParseCertificate(block.Bytes)
}

// createCAPair creates a CA certificate and key pair. The key file is created only
// if it doesn't already exist or we force it. The key path can differ from the certsDir
// which case the path must already exist and be writable.
// Returns nil on success, or an error otherwise.
func createCAPair(certsDir, keyPath, certFile string, keySize int, days int, force bool) error {
if err := os.MkdirAll(certsDir, 0700); err != nil {
return err
}

// no path then save it in certsDir.
if path.Base(keyPath) == keyPath {
keyPath = filepath.Join(certsDir, keyPath)
}

r, err := NewRequest(
cfCA(true),
cfDuration(days),
cfKeySize(keySize),
cfOverwrite(force),
)
if err != nil {
return err
}

return r.GeneratePair(
keyPath,
filepath.Join(certsDir, certFile),
)
}

// createNodePair creates a node certificate and key pair. The key file is created only
// if it doesn't already exist or we force it. The key path can differ from the certsDir
// which case the path must already exist and be writable.
// Returns nil on success, or an error otherwise.
func createNodePair(certsDir, keyPath, certFile string, keySize int, days int, force bool, nodes []string) error {
if err := os.MkdirAll(certsDir, 0700); err != nil {
return err
}

// no path then save it in certsDir.
if path.Base(keyPath) == keyPath {
keyPath = filepath.Join(certsDir, keyPath)
}

r, err := NewRequest(
cfParent(filepath.Join(certsDir, defaultCACert)),
cfSignKey(keyPath),
cfDuration(days),
cfKeySize(keySize),
cfOverwrite(force),
cfHosts(nodes...),
)
if err != nil {
return err
}

return r.GeneratePair(
filepath.Join(certsDir, defaultNodeKey),
filepath.Join(certsDir, defaultNodeCert),
)
}

// createClientPair creates a client certificate and key pair. The key file is created only
// if it doesn't already exist or we force it. The key path can differ from the certsDir
// which case the path must already exist and be writable.
// Returns nil on success, or an error otherwise.
func createClientPair(certsDir, keyPath, certFile string, keySize int, days int, force bool, user string) error {
if err := os.MkdirAll(certsDir, 0700); err != nil {
return err
}

// no path then save it in certsDir.
if path.Base(keyPath) == keyPath {
keyPath = filepath.Join(certsDir, keyPath)
}

r, err := NewRequest(
cfParent(filepath.Join(certsDir, defaultCACert)),
cfSignKey(keyPath),
cfDuration(days),
cfKeySize(keySize),
cfOverwrite(force),
cfUser(user),
)
if err != nil {
return err
}

return r.GeneratePair(
filepath.Join(certsDir, fmt.Sprint("client.", user, ".key")),
filepath.Join(certsDir, fmt.Sprint("client.", user, ".crt")),
)
}
76 changes: 76 additions & 0 deletions dgraph/cmd/cm/info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2017-2018 Dgraph Labs, Inc.
*
* This file is available under the Apache License, Version 2.0,
* with the Commons Clause restriction.
*/

package cm

import (
"fmt"
"strings"
"time"
)

type Info struct {
Name string
Expires time.Time
Err error
}

func certInfo(fn string) *Info {
var i Info

switch {
case strings.HasSuffix(fn, ".crt"):
cert, _ := readCert(fn)
i.Expires = cert.NotAfter
i.Name = cert.Subject.CommonName

case strings.HasSuffix(fn, ".key"):
switch {
case strings.HasPrefix(fn, "ca."):
i.Name = dnOrganization + " CA Key"
case strings.HasPrefix(fn, "node."):
i.Name = dnOrganization + " Node Key"
case strings.HasPrefix(fn, "client."):
i.Name = dnOrganization + " Client Key"
}
}

return &i
}

func (i *Info) Format(f fmt.State, c rune) {
var str string

w, wok := f.Width()
p, pok := f.Precision()

switch c {
case 't':
str = i.Name

case 'x':
if i.Expires.IsZero() {
break
}
str = i.Expires.Format(time.RFC822)

case 'e':
if i.Err != nil {
str = i.Err.Error()
}
}

if wok {
str = fmt.Sprintf("%-[2]*[1]s", str, w)
}

if pok && len(str) < p {
str = str[:p]
}

f.Write([]byte(str))
}
Loading