keys.go 14.1 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ssh

import (
8
	"bytes"
9
	"crypto"
10
	"crypto/dsa"
11 12
	"crypto/ecdsa"
	"crypto/elliptic"
13
	"crypto/rsa"
14
	"crypto/x509"
15
	"encoding/asn1"
16
	"encoding/base64"
17 18 19 20
	"encoding/pem"
	"errors"
	"fmt"
	"io"
21 22 23
	"math/big"
)

24 25
// These constants represent the algorithm names for key types supported by this
// package.
26
const (
27 28 29 30 31
	KeyAlgoRSA      = "ssh-rsa"
	KeyAlgoDSA      = "ssh-dss"
	KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
	KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
	KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
32 33
)

34 35 36 37
// parsePubKey parses a public key of the given algorithm.
// Use ParsePublicKey for keys with prepended algorithm.
func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, ok bool) {
	switch algo {
38
	case KeyAlgoRSA:
39
		return parseRSA(in)
40
	case KeyAlgoDSA:
41
		return parseDSA(in)
42
	case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
43
		return parseECDSA(in)
44
	case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
45
		return parseOpenSSHCertV01(in, algo)
46
	}
47
	return nil, nil, false
48 49
}

50 51 52
// parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
// (see sshd(8) manual page) once the options and key type fields have been
// removed.
53
func parseAuthorizedKey(in []byte) (out PublicKey, comment string, ok bool) {
54 55 56 57 58 59 60 61 62 63 64 65 66 67
	in = bytes.TrimSpace(in)

	i := bytes.IndexAny(in, " \t")
	if i == -1 {
		i = len(in)
	}
	base64Key := in[:i]

	key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
	n, err := base64.StdEncoding.Decode(key, base64Key)
	if err != nil {
		return
	}
	key = key[:n]
68
	out, _, ok = ParsePublicKey(key)
69 70 71 72 73 74 75 76 77
	if !ok {
		return nil, "", false
	}
	comment = string(bytes.TrimSpace(in[i:]))
	return
}

// ParseAuthorizedKeys parses a public key from an authorized_keys
// file used in OpenSSH according to the sshd(8) manual page.
78
func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, ok bool) {
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
	for len(in) > 0 {
		end := bytes.IndexByte(in, '\n')
		if end != -1 {
			rest = in[end+1:]
			in = in[:end]
		} else {
			rest = nil
		}

		end = bytes.IndexByte(in, '\r')
		if end != -1 {
			in = in[:end]
		}

		in = bytes.TrimSpace(in)
		if len(in) == 0 || in[0] == '#' {
			in = rest
			continue
		}

		i := bytes.IndexAny(in, " \t")
		if i == -1 {
			in = rest
			continue
		}

105 106
		if out, comment, ok = parseAuthorizedKey(in[i:]); ok {
			return
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
		}

		// No key type recognised. Maybe there's an options field at
		// the beginning.
		var b byte
		inQuote := false
		var candidateOptions []string
		optionStart := 0
		for i, b = range in {
			isEnd := !inQuote && (b == ' ' || b == '\t')
			if (b == ',' && !inQuote) || isEnd {
				if i-optionStart > 0 {
					candidateOptions = append(candidateOptions, string(in[optionStart:i]))
				}
				optionStart = i + 1
			}
			if isEnd {
				break
			}
			if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
				inQuote = !inQuote
			}
		}
		for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
			i++
		}
		if i == len(in) {
			// Invalid line: unmatched quote
			in = rest
			continue
		}

		in = in[i:]
		i = bytes.IndexAny(in, " \t")
		if i == -1 {
			in = rest
			continue
		}

146 147 148
		if out, comment, ok = parseAuthorizedKey(in[i:]); ok {
			options = candidateOptions
			return
149 150 151 152 153 154 155 156 157 158
		}

		in = rest
		continue
	}

	return
}

// ParsePublicKey parses an SSH public key formatted for use in
159
// the SSH wire protocol according to RFC 4253, section 6.6.
160
func ParsePublicKey(in []byte) (out PublicKey, rest []byte, ok bool) {
161 162 163 164 165 166
	algo, in, ok := parseString(in)
	if !ok {
		return
	}

	return parsePubKey(in, string(algo))
167 168 169 170 171
}

// MarshalAuthorizedKey returns a byte stream suitable for inclusion
// in an OpenSSH authorized_keys file following the format specified
// in the sshd(8) manual page.
172
func MarshalAuthorizedKey(key PublicKey) []byte {
173
	b := &bytes.Buffer{}
174
	b.WriteString(key.PublicKeyAlgo())
175 176
	b.WriteByte(' ')
	e := base64.NewEncoder(base64.StdEncoding, b)
177
	e.Write(MarshalPublicKey(key))
178 179 180 181 182
	e.Close()
	b.WriteByte('\n')
	return b.Bytes()
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
// PublicKey is an abstraction of different types of public keys.
type PublicKey interface {
	// PrivateKeyAlgo returns the name of the encryption system.
	PrivateKeyAlgo() string

	// PublicKeyAlgo returns the algorithm for the public key,
	// which may be different from PrivateKeyAlgo for certificates.
	PublicKeyAlgo() string

	// Marshal returns the serialized key data in SSH wire format,
	// without the name prefix.  Callers should typically use
	// MarshalPublicKey().
	Marshal() []byte

	// Verify that sig is a signature on the given data using this
	// key. This function will hash the data appropriately first.
	Verify(data []byte, sigBlob []byte) bool
}

202 203 204 205 206 207 208 209 210
// A Signer is can create signatures that verify against a public key.
type Signer interface {
	// PublicKey returns an associated PublicKey instance.
	PublicKey() PublicKey

	// Sign returns raw signature for the given data. This method
	// will apply the hash specified for the keytype to the data.
	Sign(rand io.Reader, data []byte) ([]byte, error)
}
211 212 213 214 215 216 217 218

type rsaPublicKey rsa.PublicKey

func (r *rsaPublicKey) PrivateKeyAlgo() string {
	return "ssh-rsa"
}

func (r *rsaPublicKey) PublicKeyAlgo() string {
219
	return r.PrivateKeyAlgo()
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
}

// parseRSA parses an RSA key according to RFC 4253, section 6.6.
func parseRSA(in []byte) (out PublicKey, rest []byte, ok bool) {
	key := new(rsa.PublicKey)

	bigE, in, ok := parseInt(in)
	if !ok || bigE.BitLen() > 24 {
		return
	}
	e := bigE.Int64()
	if e < 3 || e&1 == 0 {
		ok = false
		return
	}
	key.E = int(e)

	if key.N, in, ok = parseInt(in); !ok {
		return
	}

	ok = true
242
	return (*rsaPublicKey)(key), in, ok
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
}

func (r *rsaPublicKey) Marshal() []byte {
	// See RFC 4253, section 6.6.
	e := new(big.Int).SetInt64(int64(r.E))
	length := intLength(e)
	length += intLength(r.N)

	ret := make([]byte, length)
	rest := marshalInt(ret, e)
	marshalInt(rest, r.N)

	return ret
}

func (r *rsaPublicKey) Verify(data []byte, sig []byte) bool {
	h := crypto.SHA1.New()
	h.Write(data)
	digest := h.Sum(nil)
	return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig) == nil
}

265 266 267 268 269 270 271 272 273 274 275 276 277
type rsaPrivateKey struct {
	*rsa.PrivateKey
}

func (r *rsaPrivateKey) PublicKey() PublicKey {
	return (*rsaPublicKey)(&r.PrivateKey.PublicKey)
}

func (r *rsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
	h := crypto.SHA1.New()
	h.Write(data)
	digest := h.Sum(nil)
	return rsa.SignPKCS1v15(rand, r.PrivateKey, crypto.SHA1, digest)
278 279 280 281 282 283 284
}

type dsaPublicKey dsa.PublicKey

func (r *dsaPublicKey) PrivateKeyAlgo() string {
	return "ssh-dss"
}
285

286
func (r *dsaPublicKey) PublicKeyAlgo() string {
287
	return r.PrivateKeyAlgo()
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
}

// parseDSA parses an DSA key according to RFC 4253, section 6.6.
func parseDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
	key := new(dsa.PublicKey)

	if key.P, in, ok = parseInt(in); !ok {
		return
	}

	if key.Q, in, ok = parseInt(in); !ok {
		return
	}

	if key.G, in, ok = parseInt(in); !ok {
		return
	}

	if key.Y, in, ok = parseInt(in); !ok {
		return
	}

	ok = true
311
	return (*dsaPublicKey)(key), in, ok
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
}

func (r *dsaPublicKey) Marshal() []byte {
	// See RFC 4253, section 6.6.
	length := intLength(r.P)
	length += intLength(r.Q)
	length += intLength(r.G)
	length += intLength(r.Y)

	ret := make([]byte, length)
	rest := marshalInt(ret, r.P)
	rest = marshalInt(rest, r.Q)
	rest = marshalInt(rest, r.G)
	marshalInt(rest, r.Y)

	return ret
}

func (k *dsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
	h := crypto.SHA1.New()
	h.Write(data)
	digest := h.Sum(nil)

	// Per RFC 4253, section 6.6,
	// The value for 'dss_signature_blob' is encoded as a string containing
	// r, followed by s (which are 160-bit integers, without lengths or
	// padding, unsigned, and in network byte order).
	// For DSS purposes, sig.Blob should be exactly 40 bytes in length.
	if len(sigBlob) != 40 {
		return false
	}
	r := new(big.Int).SetBytes(sigBlob[:20])
	s := new(big.Int).SetBytes(sigBlob[20:])
	return dsa.Verify((*dsa.PublicKey)(k), digest, r, s)
}

348 349
type dsaPrivateKey struct {
	*dsa.PrivateKey
350 351
}

352 353
func (k *dsaPrivateKey) PublicKey() PublicKey {
	return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
354
}
355 356 357 358 359 360 361 362 363 364 365 366 367 368

func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
	h := crypto.SHA1.New()
	h.Write(data)
	digest := h.Sum(nil)
	r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
	if err != nil {
		return nil, err
	}

	sig := make([]byte, 40)
	copy(sig[:20], r.Bytes())
	copy(sig[20:], s.Bytes())
	return sig, nil
369 370
}

371 372
type ecdsaPublicKey ecdsa.PublicKey

373
func (key *ecdsaPublicKey) PrivateKeyAlgo() string {
374
	return "ecdsa-sha2-" + key.nistID()
375 376 377 378 379 380 381 382 383 384 385 386 387 388
}

func (key *ecdsaPublicKey) nistID() string {
	switch key.Params().BitSize {
	case 256:
		return "nistp256"
	case 384:
		return "nistp384"
	case 521:
		return "nistp521"
	}
	panic("ssh: unsupported ecdsa key size")
}

389 390 391 392 393 394 395 396 397 398
func supportedEllipticCurve(curve elliptic.Curve) bool {
	return (curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521())
}

// ecHash returns the hash to match the given elliptic curve, see RFC
// 5656, section 6.2.1
func ecHash(curve elliptic.Curve) crypto.Hash {
	bitSize := curve.Params().BitSize
	switch {
	case bitSize <= 256:
399
		return crypto.SHA256
400
	case bitSize <= 384:
401 402
		return crypto.SHA384
	}
403
	return crypto.SHA512
404 405 406
}

func (key *ecdsaPublicKey) PublicKeyAlgo() string {
407
	return key.PrivateKeyAlgo()
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
}

// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
func parseECDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
	var identifier []byte
	if identifier, in, ok = parseString(in); !ok {
		return
	}

	key := new(ecdsa.PublicKey)

	switch string(identifier) {
	case "nistp256":
		key.Curve = elliptic.P256()
	case "nistp384":
		key.Curve = elliptic.P384()
	case "nistp521":
		key.Curve = elliptic.P521()
	default:
		ok = false
		return
	}

	var keyBytes []byte
	if keyBytes, in, ok = parseString(in); !ok {
		return
	}

	key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes)
	if key.X == nil || key.Y == nil {
		ok = false
		return
	}
441
	return (*ecdsaPublicKey)(key), in, ok
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
}

func (key *ecdsaPublicKey) Marshal() []byte {
	// See RFC 5656, section 3.1.
	keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)

	ID := key.nistID()
	length := stringLength(len(ID))
	length += stringLength(len(keyBytes))

	ret := make([]byte, length)
	r := marshalString(ret, []byte(ID))
	r = marshalString(r, keyBytes)
	return ret
}

func (key *ecdsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
459
	h := ecHash(key.Curve).New()
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	h.Write(data)
	digest := h.Sum(nil)

	// Per RFC 5656, section 3.1.2,
	// The ecdsa_signature_blob value has the following specific encoding:
	//    mpint    r
	//    mpint    s
	r, rest, ok := parseInt(sigBlob)
	if !ok {
		return false
	}
	s, rest, ok := parseInt(rest)
	if !ok || len(rest) > 0 {
		return false
	}
	return ecdsa.Verify((*ecdsa.PublicKey)(key), digest, r, s)
476
}
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

type ecdsaPrivateKey struct {
	*ecdsa.PrivateKey
}

func (k *ecdsaPrivateKey) PublicKey() PublicKey {
	return (*ecdsaPublicKey)(&k.PrivateKey.PublicKey)
}

func (k *ecdsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
	h := ecHash(k.PrivateKey.PublicKey.Curve).New()
	h.Write(data)
	digest := h.Sum(nil)
	r, s, err := ecdsa.Sign(rand, k.PrivateKey, digest)
	if err != nil {
		return nil, err
	}

	sig := make([]byte, intLength(r)+intLength(s))
	rest := marshalInt(sig, r)
	marshalInt(rest, s)
	return sig, nil
}

// NewPrivateKey takes a pointer to rsa, dsa or ecdsa PrivateKey
// returns a corresponding Signer instance. EC keys should use P256,
// P384 or P521.
func NewSignerFromKey(k interface{}) (Signer, error) {
	var sshKey Signer
	switch t := k.(type) {
	case *rsa.PrivateKey:
		sshKey = &rsaPrivateKey{t}
	case *dsa.PrivateKey:
		sshKey = &dsaPrivateKey{t}
	case *ecdsa.PrivateKey:
		if !supportedEllipticCurve(t.Curve) {
			return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
		}

		sshKey = &ecdsaPrivateKey{t}
	default:
		return nil, fmt.Errorf("ssh: unsupported key type %T", k)
	}
	return sshKey, nil
}

// NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey
// and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521.
func NewPublicKey(k interface{}) (PublicKey, error) {
	var sshKey PublicKey
	switch t := k.(type) {
	case *rsa.PublicKey:
		sshKey = (*rsaPublicKey)(t)
	case *ecdsa.PublicKey:
		if !supportedEllipticCurve(t.Curve) {
			return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
		}
		sshKey = (*ecdsaPublicKey)(t)
	case *dsa.PublicKey:
		sshKey = (*dsaPublicKey)(t)
	default:
		return nil, fmt.Errorf("ssh: unsupported key type %T", k)
	}
	return sshKey, nil
}

543 544
// ParsePublicKey parses a PEM encoded private key. It supports
// PKCS#1, RSA, DSA and ECDSA private keys.
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
func ParsePrivateKey(pemBytes []byte) (Signer, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("ssh: no key found")
	}

	var rawkey interface{}
	switch block.Type {
	case "RSA PRIVATE KEY":
		rsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = rsa
	case "EC PRIVATE KEY":
		ec, err := x509.ParseECPrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = ec
565 566 567 568 569 570
	case "DSA PRIVATE KEY":
		ec, err := parseDSAPrivate(block.Bytes)
		if err != nil {
			return nil, err
		}
		rawkey = ec
571 572 573 574 575 576
	default:
		return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
	}

	return NewSignerFromKey(rawkey)
}
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

// parseDSAPrivate parses a DSA key in ASN.1 DER encoding, as
// documented in the OpenSSL DSA manpage.
// TODO(hanwen): move this in to crypto/x509 after the Go 1.2 freeze.
func parseDSAPrivate(p []byte) (*dsa.PrivateKey, error) {
	k := struct {
		Version int
		P       *big.Int
		Q       *big.Int
		G       *big.Int
		Priv    *big.Int
		Pub     *big.Int
	}{}
	rest, err := asn1.Unmarshal(p, &k)
	if err != nil {
		return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
	}
	if len(rest) > 0 {
		return nil, errors.New("ssh: garbage after DSA key")
	}

	return &dsa.PrivateKey{
		PublicKey: dsa.PublicKey{
			Parameters: dsa.Parameters{
				P: k.P,
				Q: k.Q,
				G: k.G,
			},
			Y: k.Priv,
		},
		X: k.Pub,
	}, nil
}