forked from greenpau/go-identity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublic_key.go
275 lines (258 loc) · 8.74 KB
/
public_key.go
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
// Copyright 2020 Paul Greenberg [email protected]
//
// 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 identity
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"fmt"
"github.com/greenpau/go-identity/pkg/errors"
"github.com/greenpau/go-identity/pkg/requests"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/ssh"
"strconv"
"strings"
"time"
)
var supportedPublicKeyTypes = map[string]bool{
"ssh": true,
"gpg": true,
}
// PublicKeyBundle is a collection of public keys.
type PublicKeyBundle struct {
keys []*PublicKey
size int
}
// PublicKey is a puiblic key in a public-private key pair.
type PublicKey struct {
ID string `json:"id,omitempty" xml:"id,omitempty" yaml:"id,omitempty"`
Usage string `json:"usage,omitempty" xml:"usage,omitempty" yaml:"usage,omitempty"`
// Type is any of the following: dsa, rsa, ecdsa, ed25519
Type string `json:"type,omitempty" xml:"type,omitempty" yaml:"type,omitempty"`
Fingerprint string `json:"fingerprint,omitempty" xml:"fingerprint,omitempty" yaml:"fingerprint,omitempty"`
FingerprintMD5 string `json:"fingerprint_md5,omitempty" xml:"fingerprint_md5,omitempty" yaml:"fingerprint_md5,omitempty"`
Comment string `json:"comment,omitempty" xml:"comment,omitempty" yaml:"comment,omitempty"`
Payload string `json:"payload,omitempty" xml:"payload,omitempty" yaml:"payload,omitempty"`
OpenSSH string `json:"openssh,omitempty" xml:"openssh,omitempty" yaml:"openssh,omitempty"`
Expired bool `json:"expired,omitempty" xml:"expired,omitempty" yaml:"expired,omitempty"`
ExpiredAt time.Time `json:"expired_at,omitempty" xml:"expired_at,omitempty" yaml:"expired_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty" xml:"created_at,omitempty" yaml:"created_at,omitempty"`
Disabled bool `json:"disabled,omitempty" xml:"disabled,omitempty" yaml:"disabled,omitempty"`
DisabledAt time.Time `json:"disabled_at,omitempty" xml:"disabled_at,omitempty" yaml:"disabled_at,omitempty"`
}
// NewPublicKeyBundle returns an instance of PublicKeyBundle.
func NewPublicKeyBundle() *PublicKeyBundle {
return &PublicKeyBundle{
keys: []*PublicKey{},
}
}
// Add adds PublicKey to PublicKeyBundle.
func (b *PublicKeyBundle) Add(k *PublicKey) {
b.keys = append(b.keys, k)
b.size++
}
// Get returns PublicKey instances of the PublicKeyBundle.
func (b *PublicKeyBundle) Get() []*PublicKey {
return b.keys
}
// Size returns the number of PublicKey instances in PublicKeyBundle.
func (b *PublicKeyBundle) Size() int {
return b.size
}
// NewPublicKey returns an instance of PublicKey.
func NewPublicKey(r *requests.Request) (*PublicKey, error) {
p := &PublicKey{
Comment: r.Key.Comment,
ID: GetRandomString(40),
Payload: r.Key.Payload,
Usage: r.Key.Usage,
CreatedAt: time.Now().UTC(),
}
if err := p.parse(); err != nil {
return nil, err
}
if r.Key.Disabled {
p.Disabled = true
p.DisabledAt = time.Now().UTC()
}
return p, nil
}
// Disable disables PublicKey instance.
func (p *PublicKey) Disable() {
p.Expired = true
p.ExpiredAt = time.Now().UTC()
p.Disabled = true
p.DisabledAt = time.Now().UTC()
}
func (p *PublicKey) parse() error {
if _, exists := supportedPublicKeyTypes[p.Usage]; !exists {
return errors.ErrPublicKeyInvalidUsage.WithArgs(p.Usage)
}
if p.Payload == "" {
return errors.ErrPublicKeyEmptyPayload
}
switch {
case strings.Contains(p.Payload, "RSA PUBLIC KEY"):
return p.parsePublicKeyRSA()
case strings.HasPrefix(p.Payload, "ssh-rsa "):
return p.parsePublicKeyOpenSSH()
case strings.Contains(p.Payload, "BEGIN PGP PUBLIC KEY BLOCK"):
return p.parsePublicKeyPGP()
}
return errors.ErrPublicKeyUsageUnsupported.WithArgs(p.Usage)
}
func (p *PublicKey) parsePublicKeyOpenSSH() error {
// Attempt parsing as authorized OpenSSH keys.
payloadBytes := bytes.TrimSpace([]byte(p.Payload))
i := bytes.IndexAny(payloadBytes, " \t")
if i == -1 {
i = len(payloadBytes)
}
var comment []byte
payloadBase64 := payloadBytes[:i]
if len(payloadBase64) < 20 {
// skip preamble, i.e. ssh-rsa, etc.
payloadBase64 = bytes.TrimSpace(payloadBytes[i:])
i = bytes.IndexAny(payloadBase64, " \t")
if i > 0 {
comment = bytes.TrimSpace(payloadBase64[i:])
payloadBase64 = payloadBase64[:i]
}
p.OpenSSH = string(payloadBase64)
}
k := make([]byte, base64.StdEncoding.DecodedLen(len(payloadBase64)))
n, err := base64.StdEncoding.Decode(k, payloadBase64)
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
publicKey, err := ssh.ParsePublicKey(k[:n])
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
p.Type = publicKey.Type()
if string(comment) != "" {
p.Comment = string(comment)
}
p.FingerprintMD5 = ssh.FingerprintLegacyMD5(publicKey)
p.Fingerprint = ssh.FingerprintSHA256(publicKey)
// Convert OpenSSH key to RSA PUBLIC KEY
switch publicKey.Type() {
case "ssh-rsa":
publicKeyBytes := publicKey.Marshal()
parsedPublicKey, err := ssh.ParsePublicKey(publicKeyBytes)
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
cryptoKey := parsedPublicKey.(ssh.CryptoPublicKey)
publicCryptoKey := cryptoKey.CryptoPublicKey()
rsaKey := publicCryptoKey.(*rsa.PublicKey)
rsaKeyASN1, err := x509.MarshalPKIXPublicKey(rsaKey)
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
encodedKey := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
//Bytes: x509.MarshalPKCS1PublicKey(rsaKey),
Bytes: rsaKeyASN1,
})
p.Payload = string(encodedKey)
default:
return errors.ErrPublicKeyTypeUnsupported.WithArgs(publicKey.Type())
}
return nil
}
func (p *PublicKey) parsePublicKeyPGP() error {
var user, algo, comment string
p.Payload = strings.TrimSpace(p.Payload)
for _, w := range []string{"BEGIN", "END"} {
s := fmt.Sprintf("-----%s PGP PUBLIC KEY BLOCK-----", w)
if (w == "BEGIN" && !strings.HasPrefix(p.Payload, s)) || (w == "END" && !strings.HasSuffix(p.Payload, s)) {
return errors.ErrPublicKeyParse.WithArgs(fmt.Errorf("%s PGP PUBLIC KEY BLOCK not found", w))
}
}
kr, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(p.Payload))
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
if len(kr) != 1 {
return errors.ErrPublicKeyParse.WithArgs(fmt.Errorf("PGP keyring contains %d entries", len(kr)))
}
if kr[0].PrimaryKey == nil {
return errors.ErrPublicKeyParse.WithArgs(fmt.Errorf("PGP keyring entry has no public key"))
}
if kr[0].Identities == nil || len(kr[0].Identities) == 0 {
return errors.ErrPublicKeyParse.WithArgs(fmt.Errorf("PGP keyring entry has no identities"))
}
pk := kr[0].PrimaryKey
p.ID = strconv.FormatUint(pk.KeyId, 16)
p.Fingerprint = hex.EncodeToString(pk.Fingerprint[:])
switch pk.PubKeyAlgo {
case 1, 2, 3:
algo = "RSA"
p.Type = "rsa"
case 17:
algo = "DSA"
p.Type = "dsa"
case 18:
algo = "ECDH"
p.Type = "ecdh"
case 19:
algo = "ECDSA"
p.Type = "ecdsa"
default:
return errors.ErrPublicKeyParse.WithArgs(fmt.Errorf("PGP keyring entry has unsupported public key algo %v", pk.PubKeyAlgo))
}
for _, u := range kr[0].Identities {
user = u.Name
break
}
comment = fmt.Sprintf("%s, algo %s, created %s", user, algo, pk.CreationTime.UTC())
if p.Comment != "" {
p.Comment = fmt.Sprintf("%s (%s)", p.Comment, comment)
} else {
p.Comment = comment
}
return nil
}
func (p *PublicKey) parsePublicKeyRSA() error {
// Processing PEM file format
if p.Usage != "ssh" {
return errors.ErrPublicKeyUsagePayloadMismatch.WithArgs(p.Usage)
}
block, _ := pem.Decode(bytes.TrimSpace([]byte(p.Payload)))
if block == nil {
return errors.ErrPublicKeyBlockType.WithArgs("")
}
if block.Type != "RSA PUBLIC KEY" {
return errors.ErrPublicKeyBlockType.WithArgs(block.Type)
}
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return errors.ErrPublicKeyParse.WithArgs(err)
}
publicKey, err := ssh.NewPublicKey(publicKeyInterface)
if err != nil {
return fmt.Errorf("failed ssh.NewPublicKey: %s", err)
}
p.Type = publicKey.Type()
p.FingerprintMD5 = ssh.FingerprintLegacyMD5(publicKey)
p.Fingerprint = ssh.FingerprintSHA256(publicKey)
p.Fingerprint = strings.ReplaceAll(p.Fingerprint, "SHA256:", "")
p.OpenSSH = string(ssh.MarshalAuthorizedKey(publicKey))
p.OpenSSH = strings.TrimLeft(p.OpenSSH, p.Type+" ")
return nil
}