x509.go 20.8 KB
Newer Older
Adam Langley's avatar
Adam Langley committed
1 2 3 4 5 6 7 8
// Copyright 2009 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.

// This package parses X.509-encoded keys and certificates.
package x509

import (
9 10 11 12 13 14
	"asn1"
	"big"
	"container/vector"
	"crypto/rsa"
	"crypto/sha1"
	"hash"
15
	"io"
16 17 18
	"os"
	"strings"
	"time"
Adam Langley's avatar
Adam Langley committed
19 20 21 22
)

// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
type pkcs1PrivateKey struct {
23 24 25 26 27 28
	Version int
	N       asn1.RawValue
	E       int
	D       asn1.RawValue
	P       asn1.RawValue
	Q       asn1.RawValue
Adam Langley's avatar
Adam Langley committed
29 30 31 32
}

// rawValueIsInteger returns true iff the given ASN.1 RawValue is an INTEGER type.
func rawValueIsInteger(raw *asn1.RawValue) bool {
33
	return raw.Class == 0 && raw.Tag == 2 && raw.IsCompound == false
Adam Langley's avatar
Adam Langley committed
34 35 36 37
}

// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
38
	var priv pkcs1PrivateKey
39
	rest, err := asn1.Unmarshal(der, &priv)
40
	if len(rest) > 0 {
41 42
		err = asn1.SyntaxError{"trailing data"}
		return
43
	}
Adam Langley's avatar
Adam Langley committed
44
	if err != nil {
45
		return
Adam Langley's avatar
Adam Langley committed
46 47 48 49 50 51
	}

	if !rawValueIsInteger(&priv.N) ||
		!rawValueIsInteger(&priv.D) ||
		!rawValueIsInteger(&priv.P) ||
		!rawValueIsInteger(&priv.Q) {
52 53
		err = asn1.StructuralError{"tags don't match"}
		return
Adam Langley's avatar
Adam Langley committed
54 55 56 57 58 59 60 61 62 63
	}

	key = &rsa.PrivateKey{
		PublicKey: rsa.PublicKey{
			E: priv.E,
			N: new(big.Int).SetBytes(priv.N.Bytes),
		},
		D: new(big.Int).SetBytes(priv.D.Bytes),
		P: new(big.Int).SetBytes(priv.P.Bytes),
		Q: new(big.Int).SetBytes(priv.Q.Bytes),
64
	}
Adam Langley's avatar
Adam Langley committed
65

66
	err = key.Validate()
Adam Langley's avatar
Adam Langley committed
67
	if err != nil {
68
		return nil, err
Adam Langley's avatar
Adam Langley committed
69
	}
70
	return
Adam Langley's avatar
Adam Langley committed
71
}
72

73 74 75 76
// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
	priv := pkcs1PrivateKey{
		Version: 1,
77 78 79 80 81
		N:       asn1.RawValue{Tag: 2, Bytes: key.PublicKey.N.Bytes()},
		E:       key.PublicKey.E,
		D:       asn1.RawValue{Tag: 2, Bytes: key.D.Bytes()},
		P:       asn1.RawValue{Tag: 2, Bytes: key.P.Bytes()},
		Q:       asn1.RawValue{Tag: 2, Bytes: key.Q.Bytes()},
82 83
	}

84
	b, _ := asn1.Marshal(priv)
85 86 87
	return b
}

88 89 90
// These structures reflect the ASN.1 structure of X.509 certificates.:

type certificate struct {
91 92 93
	TBSCertificate     tbsCertificate
	SignatureAlgorithm algorithmIdentifier
	SignatureValue     asn1.BitString
94 95 96
}

type tbsCertificate struct {
97 98 99 100 101 102 103 104
	Raw                asn1.RawContent
	Version            int "optional,explicit,default:1,tag:0"
	SerialNumber       asn1.RawValue
	SignatureAlgorithm algorithmIdentifier
	Issuer             rdnSequence
	Validity           validity
	Subject            rdnSequence
	PublicKey          publicKeyInfo
105 106
	UniqueId           asn1.BitString "optional,tag:1"
	SubjectUniqueId    asn1.BitString "optional,tag:2"
107
	Extensions         []extension    "optional,explicit,tag:3"
108 109 110
}

type algorithmIdentifier struct {
111
	Algorithm asn1.ObjectIdentifier
112 113
}

114
type rdnSequence []relativeDistinguishedNameSET
115

116
type relativeDistinguishedNameSET []attributeTypeAndValue
117 118

type attributeTypeAndValue struct {
119 120
	Type  asn1.ObjectIdentifier
	Value interface{}
121 122 123
}

type validity struct {
124
	NotBefore, NotAfter *time.Time
125 126 127
}

type publicKeyInfo struct {
128 129
	Algorithm algorithmIdentifier
	PublicKey asn1.BitString
130 131 132
}

type extension struct {
133 134 135
	Id       asn1.ObjectIdentifier
	Critical bool "optional"
	Value    []byte
136 137 138 139
}

// RFC 5280,  4.2.1.1
type authKeyId struct {
140
	Id []byte "optional,tag:0"
141 142 143 144 145
}

type SignatureAlgorithm int

const (
146 147 148 149 150 151 152
	UnknownSignatureAlgorithm SignatureAlgorithm = iota
	MD2WithRSA
	MD5WithRSA
	SHA1WithRSA
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
153 154 155 156 157
)

type PublicKeyAlgorithm int

const (
158 159
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
160 161 162 163 164
)

// Name represents an X.509 distinguished name. This only includes the common
// elements of a DN.  Additional elements in the name are ignored.
type Name struct {
165 166 167 168
	Country, Organization, OrganizationalUnit []string
	Locality, Province                        []string
	StreetAddress, PostalCode                 []string
	SerialNumber, CommonName                  string
169 170 171 172 173 174 175
}

func (n *Name) fillFromRDNSequence(rdns *rdnSequence) {
	for _, rdn := range *rdns {
		if len(rdn) == 0 {
			continue
		}
176 177
		atv := rdn[0]
		value, ok := atv.Value.(string)
178 179 180 181
		if !ok {
			continue
		}

182
		t := atv.Type
183 184 185 186 187 188 189
		if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
			switch t[3] {
			case 3:
				n.CommonName = value
			case 5:
				n.SerialNumber = value
			case 6:
190
				n.Country = appendString(n.Country, value)
191
			case 7:
192
				n.Locality = appendString(n.Locality, value)
193
			case 8:
194
				n.Province = appendString(n.Province, value)
195
			case 9:
196
				n.StreetAddress = appendString(n.StreetAddress, value)
197
			case 10:
198
				n.Organization = appendString(n.Organization, value)
199
			case 11:
200
				n.OrganizationalUnit = appendString(n.OrganizationalUnit, value)
201
			case 17:
202
				n.PostalCode = appendString(n.PostalCode, value)
203 204 205 206 207
			}
		}
	}
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
var (
	oidCountry            = []int{2, 5, 4, 6}
	oidOrganization       = []int{2, 5, 4, 10}
	oidOrganizationalUnit = []int{2, 5, 4, 11}
	oidCommonName         = []int{2, 5, 4, 3}
	oidSerialNumber       = []int{2, 5, 4, 5}
	oidLocatity           = []int{2, 5, 4, 7}
	oidProvince           = []int{2, 5, 4, 8}
	oidStreetAddress      = []int{2, 5, 4, 9}
	oidPostalCode         = []int{2, 5, 4, 17}
)

func (n Name) toRDNSequence() (ret rdnSequence) {
	ret = make([]relativeDistinguishedNameSET, 9 /* maximum number of elements */ )
	i := 0
	if len(n.Country) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
224
		ret[i] = []attributeTypeAndValue{{oidCountry, n.Country}}
225 226 227
		i++
	}
	if len(n.Organization) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
228
		ret[i] = []attributeTypeAndValue{{oidOrganization, n.Organization}}
229 230 231
		i++
	}
	if len(n.OrganizationalUnit) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
232
		ret[i] = []attributeTypeAndValue{{oidOrganizationalUnit, n.OrganizationalUnit}}
233 234 235
		i++
	}
	if len(n.CommonName) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
236
		ret[i] = []attributeTypeAndValue{{oidCommonName, n.CommonName}}
237 238 239
		i++
	}
	if len(n.SerialNumber) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
240
		ret[i] = []attributeTypeAndValue{{oidSerialNumber, n.SerialNumber}}
241 242 243
		i++
	}
	if len(n.Locality) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
244
		ret[i] = []attributeTypeAndValue{{oidLocatity, n.Locality}}
245 246 247
		i++
	}
	if len(n.Province) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
248
		ret[i] = []attributeTypeAndValue{{oidProvince, n.Province}}
249 250 251
		i++
	}
	if len(n.StreetAddress) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
252
		ret[i] = []attributeTypeAndValue{{oidStreetAddress, n.StreetAddress}}
253 254 255
		i++
	}
	if len(n.PostalCode) > 0 {
Robert Griesemer's avatar
Robert Griesemer committed
256
		ret[i] = []attributeTypeAndValue{{oidPostalCode, n.PostalCode}}
257 258 259 260 261 262 263 264 265
		i++
	}

	// Adding another RDN here? Remember to update the maximum number of
	// elements in the make() at the top of the function.

	return ret[0:i]
}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
func getSignatureAlgorithmFromOID(oid []int) SignatureAlgorithm {
	if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
		oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
		switch oid[6] {
		case 2:
			return MD2WithRSA
		case 4:
			return MD5WithRSA
		case 5:
			return SHA1WithRSA
		case 11:
			return SHA256WithRSA
		case 12:
			return SHA384WithRSA
		case 13:
			return SHA512WithRSA
		}
	}

285
	return UnknownSignatureAlgorithm
286 287 288 289 290 291 292 293 294 295 296
}

func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
	if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
		oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
		switch oid[6] {
		case 1:
			return RSA
		}
	}

297
	return UnknownPublicKeyAlgorithm
298 299 300 301 302 303 304
}

// KeyUsage represents the set of actions that are valid for a given key. It's
// a bitmap of the KeyUsage* constants.
type KeyUsage int

const (
305 306 307 308 309 310 311 312 313
	KeyUsageDigitalSignature KeyUsage = 1 << iota
	KeyUsageContentCommitment
	KeyUsageKeyEncipherment
	KeyUsageDataEncipherment
	KeyUsageKeyAgreement
	KeyUsageCertSign
	KeyUsageCRLSign
	KeyUsageEncipherOnly
	KeyUsageDecipherOnly
314 315 316 317
)

// A Certificate represents an X.509 certificate.
type Certificate struct {
318 319 320
	Raw                []byte // Raw ASN.1 DER contents.
	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm
321

322 323
	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          interface{}
324

325 326 327 328 329 330
	Version             int
	SerialNumber        []byte
	Issuer              Name
	Subject             Name
	NotBefore, NotAfter *time.Time // Validity bounds.
	KeyUsage            KeyUsage
331

332 333 334
	BasicConstraintsValid bool // if true then the next two fields are valid.
	IsCA                  bool
	MaxPathLen            int
335

336 337
	SubjectKeyId   []byte
	AuthorityKeyId []byte
338 339

	// Subject Alternate Name values
340 341
	DNSNames       []string
	EmailAddresses []string
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
}

// UnsupportedAlgorithmError results from attempting to perform an operation
// that involves algorithms that are not currently implemented.
type UnsupportedAlgorithmError struct{}

func (UnsupportedAlgorithmError) String() string {
	return "cannot verify signature: algorithm unimplemented"
}

// ConstraintViolationError results when a requested usage is not permitted by
// a certificate. For example: checking a signature when the public key isn't a
// certificate signing key.
type ConstraintViolationError struct{}

func (ConstraintViolationError) String() string {
	return "invalid signature: parent certificate cannot sign this kind of certificate"
}

// CheckSignatureFrom verifies that the signature on c is a valid signature
// from parent.
func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) {
	// RFC 5280, 4.2.1.9:
	// "If the basic constraints extension is not present in a version 3
	// certificate, or the extension is present but the cA boolean is not
	// asserted, then the certified public key MUST NOT be used to verify
	// certificate signatures."
	if parent.Version == 3 && !parent.BasicConstraintsValid ||
		parent.BasicConstraintsValid && !parent.IsCA {
		return ConstraintViolationError{}
	}

	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
		return ConstraintViolationError{}
	}

	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
		return UnsupportedAlgorithmError{}
	}

	// TODO(agl): don't ignore the path length constraint.

384 385
	var h hash.Hash
	var hashType rsa.PKCS1v15Hash
386 387 388

	switch c.SignatureAlgorithm {
	case SHA1WithRSA:
389 390
		h = sha1.New()
		hashType = rsa.HashSHA1
391 392 393 394
	default:
		return UnsupportedAlgorithmError{}
	}

395
	pub, ok := parent.PublicKey.(*rsa.PublicKey)
396 397 398 399
	if !ok {
		return UnsupportedAlgorithmError{}
	}

400 401
	h.Write(c.Raw)
	digest := h.Sum()
402

403
	return rsa.VerifyPKCS1v15(pub, hashType, digest, c.Signature)
404 405 406 407 408 409 410
}

func matchHostnames(pattern, host string) bool {
	if len(pattern) == 0 || len(host) == 0 {
		return false
	}

411 412
	patternParts := strings.Split(pattern, ".", -1)
	hostParts := strings.Split(host, ".", -1)
413 414 415 416 417 418 419 420 421 422 423 424 425 426

	if len(patternParts) != len(hostParts) {
		return false
	}

	for i, patternPart := range patternParts {
		if patternPart == "*" {
			continue
		}
		if patternPart != hostParts[i] {
			return false
		}
	}

427
	return true
428 429
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
type HostnameError struct {
	Certificate *Certificate
	Host        string
}

func (h *HostnameError) String() string {
	var valid string
	c := h.Certificate
	if len(c.DNSNames) > 0 {
		valid = strings.Join(c.DNSNames, ", ")
	} else {
		valid = c.Subject.CommonName
	}
	return "certificate is valid for " + valid + ", not " + h.Host
}

// VerifyHostname returns nil if c is a valid certificate for the named host.
// Otherwise it returns an os.Error describing the mismatch.
func (c *Certificate) VerifyHostname(h string) os.Error {
449 450 451
	if len(c.DNSNames) > 0 {
		for _, match := range c.DNSNames {
			if matchHostnames(match, h) {
452
				return nil
453 454 455
			}
		}
		// If Subject Alt Name is given, we ignore the common name.
456 457
	} else if matchHostnames(c.Subject.CommonName, h) {
		return nil
458 459
	}

460
	return &HostnameError{c, h}
461 462 463 464 465 466 467 468 469
}

type UnhandledCriticalExtension struct{}

func (h UnhandledCriticalExtension) String() string {
	return "unhandled critical extension"
}

type basicConstraints struct {
470 471
	IsCA       bool "optional"
	MaxPathLen int  "optional"
472 473 474
}

type rsaPublicKey struct {
475 476
	N asn1.RawValue
	E int
477 478 479 480 481
}

func parsePublicKey(algo PublicKeyAlgorithm, asn1Data []byte) (interface{}, os.Error) {
	switch algo {
	case RSA:
482
		p := new(rsaPublicKey)
483
		_, err := asn1.Unmarshal(asn1Data, p)
484 485 486 487 488 489 490 491 492 493 494
		if err != nil {
			return nil, err
		}

		if !rawValueIsInteger(&p.N) {
			return nil, asn1.StructuralError{"tags don't match"}
		}

		pub := &rsa.PublicKey{
			E: p.E,
			N: new(big.Int).SetBytes(p.N.Bytes),
495 496
		}
		return pub, nil
497 498 499 500
	default:
		return nil, nil
	}

501
	panic("unreachable")
502 503 504 505
}

func appendString(in []string, v string) (out []string) {
	if cap(in)-len(in) < 1 {
506
		out = make([]string, len(in)+1, len(in)*2+1)
Russ Cox's avatar
Russ Cox committed
507
		copy(out, in)
508 509 510
	} else {
		out = in[0 : len(in)+1]
	}
511 512
	out[len(in)] = v
	return out
513 514 515
}

func parseCertificate(in *certificate) (*Certificate, os.Error) {
516 517
	out := new(Certificate)
	out.Raw = in.TBSCertificate.Raw
518

519
	out.Signature = in.SignatureValue.RightAlign()
520
	out.SignatureAlgorithm =
521
		getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
522 523

	out.PublicKeyAlgorithm =
524 525 526
		getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
	var err os.Error
	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, in.TBSCertificate.PublicKey.PublicKey.RightAlign())
527 528 529 530
	if err != nil {
		return nil, err
	}

531 532 533 534 535 536
	out.Version = in.TBSCertificate.Version
	out.SerialNumber = in.TBSCertificate.SerialNumber.Bytes
	out.Issuer.fillFromRDNSequence(&in.TBSCertificate.Issuer)
	out.Subject.fillFromRDNSequence(&in.TBSCertificate.Subject)
	out.NotBefore = in.TBSCertificate.Validity.NotBefore
	out.NotAfter = in.TBSCertificate.Validity.NotAfter
537 538 539 540 541 542

	for _, e := range in.TBSCertificate.Extensions {
		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
			switch e.Id[3] {
			case 15:
				// RFC 5280, 4.2.1.3
543
				var usageBits asn1.BitString
544
				_, err := asn1.Unmarshal(e.Value, &usageBits)
545 546

				if err == nil {
547
					var usage int
548 549 550 551 552
					for i := 0; i < 9; i++ {
						if usageBits.At(i) != 0 {
							usage |= 1 << uint(i)
						}
					}
553 554
					out.KeyUsage = KeyUsage(usage)
					continue
555 556 557
				}
			case 19:
				// RFC 5280, 4.2.1.9
558
				var constriants basicConstraints
559
				_, err := asn1.Unmarshal(e.Value, &constriants)
560 561

				if err == nil {
562 563 564 565
					out.BasicConstraintsValid = true
					out.IsCA = constriants.IsCA
					out.MaxPathLen = constriants.MaxPathLen
					continue
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
				}
			case 17:
				// RFC 5280, 4.2.1.6

				// SubjectAltName ::= GeneralNames
				//
				// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
				//
				// GeneralName ::= CHOICE {
				//      otherName                       [0]     OtherName,
				//      rfc822Name                      [1]     IA5String,
				//      dNSName                         [2]     IA5String,
				//      x400Address                     [3]     ORAddress,
				//      directoryName                   [4]     Name,
				//      ediPartyName                    [5]     EDIPartyName,
				//      uniformResourceIdentifier       [6]     IA5String,
				//      iPAddress                       [7]     OCTET STRING,
				//      registeredID                    [8]     OBJECT IDENTIFIER }
584
				var seq asn1.RawValue
585
				_, err := asn1.Unmarshal(e.Value, &seq)
586 587 588 589 590 591 592
				if err != nil {
					return nil, err
				}
				if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
					return nil, asn1.StructuralError{"bad SAN sequence"}
				}

593
				parsedName := false
594

595
				rest := seq.Bytes
596
				for len(rest) > 0 {
597
					var v asn1.RawValue
598
					rest, err = asn1.Unmarshal(rest, &v)
599 600 601 602 603
					if err != nil {
						return nil, err
					}
					switch v.Tag {
					case 1:
604 605
						out.EmailAddresses = appendString(out.EmailAddresses, string(v.Bytes))
						parsedName = true
606
					case 2:
607 608
						out.DNSNames = appendString(out.DNSNames, string(v.Bytes))
						parsedName = true
609 610 611 612 613 614 615 616 617 618 619
					}
				}

				if parsedName {
					continue
				}
				// If we didn't parse any of the names then we
				// fall through to the critical check below.

			case 35:
				// RFC 5280, 4.2.1.1
620
				var a authKeyId
621
				_, err = asn1.Unmarshal(e.Value, &a)
622 623 624
				if err != nil {
					return nil, err
				}
625 626
				out.AuthorityKeyId = a.Id
				continue
627 628 629

			case 14:
				// RFC 5280, 4.2.1.2
630
				var keyid []byte
631
				_, err = asn1.Unmarshal(e.Value, &keyid)
632 633 634 635
				if err != nil {
					return nil, err
				}
				out.SubjectKeyId = keyid
636
				continue
637 638 639 640 641 642 643 644
			}
		}

		if e.Critical {
			return out, UnhandledCriticalExtension{}
		}
	}

645
	return out, nil
646 647 648 649
}

// ParseCertificate parses a single certificate from the given ASN.1 DER data.
func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
650
	var cert certificate
651
	rest, err := asn1.Unmarshal(asn1Data, &cert)
652 653 654 655 656 657 658
	if err != nil {
		return nil, err
	}
	if len(rest) > 0 {
		return nil, asn1.SyntaxError{"trailing data"}
	}

659
	return parseCertificate(&cert)
660 661 662 663 664
}

// ParseCertificates parses one or more certificates from the given ASN.1 DER
// data. The certificates must be concatenated with no intermediate padding.
func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) {
665
	v := new(vector.Vector)
666 667

	for len(asn1Data) > 0 {
668 669
		cert := new(certificate)
		var err os.Error
670
		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
671 672 673
		if err != nil {
			return nil, err
		}
674
		v.Push(cert)
675 676
	}

677
	ret := make([]*Certificate, v.Len())
678
	for i := 0; i < v.Len(); i++ {
679
		cert, err := parseCertificate(v.At(i).(*certificate))
680 681 682
		if err != nil {
			return nil, err
		}
683
		ret[i] = cert
684 685
	}

686
	return ret, nil
687
}
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

func reverseBitsInAByte(in byte) byte {
	b1 := in>>4 | in<<4
	b2 := b1>>2&0x33 | b1<<2&0xcc
	b3 := b2>>1&0x55 | b2<<1&0xaa
	return b3
}

var (
	oidExtensionSubjectKeyId     = []int{2, 5, 29, 14}
	oidExtensionKeyUsage         = []int{2, 5, 29, 15}
	oidExtensionAuthorityKeyId   = []int{2, 5, 29, 35}
	oidExtensionBasicConstraints = []int{2, 5, 29, 19}
	oidExtensionSubjectAltName   = []int{2, 5, 29, 17}
)

func buildExtensions(template *Certificate) (ret []extension, err os.Error) {
	ret = make([]extension, 5 /* maximum number of elements. */ )
	n := 0

	if template.KeyUsage != 0 {
		ret[n].Id = oidExtensionKeyUsage
		ret[n].Critical = true

		var a [2]byte
		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))

		l := 1
		if a[1] != 0 {
			l = 2
		}

721
		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
722 723 724 725 726 727 728 729
		if err != nil {
			return
		}
		n++
	}

	if template.BasicConstraintsValid {
		ret[n].Id = oidExtensionBasicConstraints
730
		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
731 732 733 734 735 736 737 738 739
		ret[n].Critical = true
		if err != nil {
			return
		}
		n++
	}

	if len(template.SubjectKeyId) > 0 {
		ret[n].Id = oidExtensionSubjectKeyId
740
		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
741 742 743 744 745 746 747 748
		if err != nil {
			return
		}
		n++
	}

	if len(template.AuthorityKeyId) > 0 {
		ret[n].Id = oidExtensionAuthorityKeyId
749
		ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
750 751 752 753 754 755 756 757 758 759
		if err != nil {
			return
		}
		n++
	}

	if len(template.DNSNames) > 0 {
		ret[n].Id = oidExtensionSubjectAltName
		rawValues := make([]asn1.RawValue, len(template.DNSNames))
		for i, name := range template.DNSNames {
Russ Cox's avatar
Russ Cox committed
760
			rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
761
		}
762
		ret[n].Value, err = asn1.Marshal(rawValues)
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
		if err != nil {
			return
		}
		n++
	}

	// Adding another extension here? Remember to update the maximum number
	// of elements in the make() at the top of the function.

	return ret[0:n], nil
}

var (
	oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
	oidRSA         = []int{1, 2, 840, 113549, 1, 1, 1}
)

// CreateSelfSignedCertificate creates a new certificate based on
// a template. The following members of template are used: SerialNumber,
// Subject, NotBefore, NotAfter, KeyUsage, BasicConstraintsValid, IsCA,
// MaxPathLen, SubjectKeyId, DNSNames.
//
// The certificate is signed by parent. If parent is equal to template then the
Adam Langley's avatar
Adam Langley committed
786 787
// certificate is self-signed. The parameter pub is the public key of the
// signee and priv is the private key of the signer.
788 789
//
// The returned slice is the certificate in DER encoding.
790
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub *rsa.PublicKey, priv *rsa.PrivateKey) (cert []byte, err os.Error) {
791
	asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
792 793
		N: asn1.RawValue{Tag: 2, Bytes: pub.N.Bytes()},
		E: pub.E,
794 795 796 797 798
	})
	if err != nil {
		return
	}

799
	if len(parent.SubjectKeyId) > 0 {
800 801 802 803 804 805 806 807 808 809
		template.AuthorityKeyId = parent.SubjectKeyId
	}

	extensions, err := buildExtensions(template)
	if err != nil {
		return
	}

	encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
	c := tbsCertificate{
810 811
		Version:            3,
		SerialNumber:       asn1.RawValue{Bytes: template.SerialNumber, Tag: 2},
812
		SignatureAlgorithm: algorithmIdentifier{oidSHA1WithRSA},
813 814 815
		Issuer:             parent.Subject.toRDNSequence(),
		Validity:           validity{template.NotBefore, template.NotAfter},
		Subject:            template.Subject.toRDNSequence(),
816 817
		PublicKey:          publicKeyInfo{algorithmIdentifier{oidRSA}, encodedPublicKey},
		Extensions:         extensions,
818 819
	}

820
	tbsCertContents, err := asn1.Marshal(c)
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
	if err != nil {
		return
	}

	c.Raw = tbsCertContents

	h := sha1.New()
	h.Write(tbsCertContents)
	digest := h.Sum()

	signature, err := rsa.SignPKCS1v15(rand, priv, rsa.HashSHA1, digest)
	if err != nil {
		return
	}

836
	cert, err = asn1.Marshal(certificate{
837 838 839 840 841 842
		c,
		algorithmIdentifier{oidSHA1WithRSA},
		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
	})
	return
}