File: chefcrypto.go

package info (click to toggle)
golang-github-ctdk-chefcrypto 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 104 kB
  • sloc: makefile: 2
file content (276 lines) | stat: -rw-r--r-- 8,138 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/* Various cryptographic functions, as needed. */

/*
 * Copyright (c) 2013-2020, Jeremy Bingham (<jeremy@goiardi.gl>)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Package chefcrypto bundles up crytographic routines for goairdi (and anything
// else that might need it).
package chefcrypto

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha512"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
	"math/big"
	"strings"
)

// GenerateRSAKeys creates a pair of private and public keys for a client.
func GenerateRSAKeys() (string, string, error) {
	/* Shamelessly borrowed and adapted from some golang-samples */
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return "", "", err
	}

	privPem, err := PrivateKeyToString(priv)
	if err != nil {
		return "", "", err
	}

	pubPem, err := PublicKeyToString(priv.PublicKey)
	if err != nil {
		return "", "", err
	}

	return privPem, pubPem, nil
}

// ValidatePublicKey checks that the provided public key is valid.
func ValidatePublicKey(publicKey interface{}) (bool, error) {
	switch publicKey := publicKey.(type) {
	case string:
		// at the moment we don't care about the pub interface

		// fix weirdly labeled public keys with an old style BEGIN but
		// a new style END - go 1.8's encoding/pem has become strict
		// about the ending line.
		if strings.HasPrefix(publicKey, "-----BEGIN RSA PUBLIC KEY-----") && strings.HasSuffix(publicKey, "-----END PUBLIC KEY-----") {
			publicKey = strings.Replace(publicKey, "-----BEGIN RSA PUBLIC KEY-----", "-----BEGIN PUBLIC KEY-----", 1)
		}

		decPubKey, z := pem.Decode([]byte(publicKey))
		if decPubKey == nil {
			err := fmt.Errorf("Public key does not validate: %s", z)
			return false, err
		}
		// Add the header to PKCS#1 public keys
		if strings.HasPrefix(publicKey, "-----BEGIN RSA PUBLIC KEY-----") && len(decPubKey.Bytes) == 270 {
			pkcs8head := []byte{0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00}
			pkcs8head = append(pkcs8head, decPubKey.Bytes...)
			decPubKey.Bytes = pkcs8head
		}
		if _, err := x509.ParsePKIXPublicKey(decPubKey.Bytes); err != nil {
			nerr := fmt.Errorf("Public key did not validate: %s", err.Error())
			return false, nerr
		}
		return true, nil
	default:
		err := fmt.Errorf("Public key does not validate")
		return false, err
	}
}

// HeaderDecrypt decrypts the encrypted header with the client or user's public
// key for validating requests. This function is informed by chef-golang's
// privateDecrypt function.
func HeaderDecrypt(pkPem string, data string) ([]byte, error) {
	block, _ := pem.Decode([]byte(pkPem))
	if block == nil {
		return nil, fmt.Errorf("Invalid block size for '%s'", pkPem)
	}
	pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	decData, perr := base64.StdEncoding.DecodeString(data)
	if perr != nil {
		return nil, perr
	}
	dec, derr := decrypt(pubKey.(*rsa.PublicKey), decData)
	if derr != nil {
		return nil, derr
	}
	/* skip past the 0xff padding added to the header before encrypting. */
	skip := 0
	for i := 2; i < len(dec); i++ {
		if i+1 >= len(dec) {
			break
		}
		if dec[i] == 0xff && dec[i+1] == 0 {
			skip = i + 2
			break
		}
	}
	return dec[skip:], nil
}

// Auth12HeaderVerify verifies the newer version 1.2 Chef authentication
// protocol headers.
func Auth12HeaderVerify(pkPem string, hashed, sig []byte) error {
	return signHeaderVerifyBase(pkPem, hashed, sig, crypto.SHA1)
}

// Auth12HeaderVerify verifies the even newer version 1.3 Chef authentication
// protocol headers
func Auth13HeaderVerify(pkPem string, hashed, sig []byte) error {
	return signHeaderVerifyBase(pkPem, hashed, sig, crypto.SHA256)
}

func signHeaderVerifyBase(pkPem string, hashed, sig []byte, algo crypto.Hash) error {
	block, _ := pem.Decode([]byte(pkPem))
	if block == nil {
		return fmt.Errorf("Invalid block size for '%s'", pkPem)
	}
	pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return err
	}
	return rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), algo, hashed, sig)
}

// SignTextBlock signs a block of text using the provided private RSA key. Used
// by shovey to sign requests that the client can verify.
func SignTextBlock(textBlock string, privKey *rsa.PrivateKey) (string, error) {
	if textBlock == "" {
		err := fmt.Errorf("no text to sign provided")
		return "", err
	}
	tbSha := sha1.Sum([]byte(textBlock))
	signed, err := rsa.SignPKCS1v15(rand.Reader, privKey, crypto.SHA1, tbSha[:])
	return base64.StdEncoding.EncodeToString(signed), err
}

// There has been discussion of renaming this and submitting it along with its
// counterpart in chef-golang to crypto/rsa.
func decrypt(pubKey *rsa.PublicKey, data []byte) ([]byte, error) {
	c := new(big.Int)
	m := new(big.Int)
	m.SetBytes(data)
	e := big.NewInt(int64(pubKey.E))
	c.Exp(m, e, pubKey.N)
	out := c.Bytes()

	return out, nil
}

// HashPasswd SHA512 hashes a password string with the provided salt.
func HashPasswd(passwd string, salt []byte) (string, error) {
	if passwd == "" {
		err := fmt.Errorf("Password is empty")
		return "", err
	}
	hashPwByte := sha512.Sum512(append(salt, []byte(passwd)...))
	hashPw := hex.EncodeToString(hashPwByte[:])
	return hashPw, nil
}

// GenerateSalt makes a new salt for hashing a password.
func GenerateSalt() ([]byte, error) {
	numbytes := 64
	b := make([]byte, numbytes)
	_, err := rand.Read(b)
	if err != nil {
		return nil, err
	}
	return b, nil
}

// PrivateKeyToString stringifies a private key.
func PrivateKeyToString(priv *rsa.PrivateKey) (string, error) {
	// may as well check and make sure this is a valid key first
	if err := priv.Validate(); err != nil {
		errStr := fmt.Errorf("RSA key validation failed: %s", err)
		return "", errStr
	}
	privDer := x509.MarshalPKCS1PrivateKey(priv)
	/* For some reason chef doesn't label the keys RSA PRIVATE/PUBLIC KEY */
	privBlk := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privDer,
	}
	privPem := string(pem.EncodeToMemory(&privBlk))
	return privPem, nil
}

// PemToPrivateKey converts a given pem encoded private key into a proper and
// usable *rsa.PrivateKey.
func PemToPrivateKey(privPem string) (*rsa.PrivateKey, error) {
	privBlk, _ := pem.Decode([]byte(privPem))
	if privBlk == nil {
		e := errors.New("Invalid block size for private key")
		return nil, e
	}

	privKey, err := x509.ParsePKCS1PrivateKey(privBlk.Bytes)
	if err != nil {
		return nil, err
	}

	return privKey, nil
}

// PublicKeyToString stringifies a private key.
func PublicKeyToString(pub rsa.PublicKey) (string, error) {
	pubDer, err := x509.MarshalPKIXPublicKey(&pub)
	if err != nil {
		errStr := fmt.Errorf("Failed to get der format for public key: %s", err)
		return "", errStr
	}
	pubBlk := pem.Block{
		Type:    "PUBLIC KEY",
		Headers: nil,
		Bytes:   pubDer,
	}
	pubPem := string(pem.EncodeToMemory(&pubBlk))

	return pubPem, nil
}

// PemToPublicKey converts a pem encoded public key to a proper rsa.PublicKey.
func PemToPublicKey(pubPem string) (rsa.PublicKey, error) {
	var pub rsa.PublicKey
	var err error
	block, _ := pem.Decode([]byte(pubPem))
	if block == nil {
		err = errors.New("Invalid block size for public key")
		return pub, err
	}

	pint, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return pub, err
	}

	switch pint := pint.(type) {
	case rsa.PublicKey:
		pub = pint
	default:
		err = errors.New("Somehow the public key unmarshalled successfully, but still wasn't an rsa.PublicKey")
		return pub, err
	}

	return pub, nil
}