// Creates a cross-signed intermediate and new api.RootRotation object.
// This function assumes that the root cert and key and the external CAs have already been validated.
325990
func newRootRotationObject(ctx context.Context, securityConfig *ca.SecurityConfig, apiRootCA *api.RootCA, newCARootCA ca.RootCA, extCAs []*api.ExternalCA, version uint64) (*api.RootCA, error) {
	var (
		rootCert, rootKey, crossSignedCert []byte
		newRootHasSigner                   bool
		err                                error
	)

	rootCert = newCARootCA.Certs
	if s, err := newCARootCA.Signer(); err == nil {
		rootCert, rootKey = s.Cert, s.Key
		newRootHasSigner = true
	}

	// we have to sign with the original signer, not whatever is in the SecurityConfig's RootCA (which may have an intermediate signer, if
	// a root rotation is already in progress)
	switch {
	case hasSigningKey(apiRootCA):
		var oldRootCA ca.RootCA
		oldRootCA, err = ca.NewRootCA(apiRootCA.CACert, apiRootCA.CACert, apiRootCA.CAKey, ca.DefaultNodeCertExpiration, nil)
		if err == nil {
			crossSignedCert, err = oldRootCA.CrossSignCACertificate(rootCert)
		}
	case !newRootHasSigner: // the original CA and the new CA both require external CAs
		return nil, status.Errorf(codes.InvalidArgument, "rotating from one external CA to a different external CA is not supported")
	default:
		// We need the same credentials but to connect to the original URLs (in case we are in the middle of a root rotation already)
		var urls []string
		for _, c := range extCAs {
			if c.Protocol == api.ExternalCA_CAProtocolCFSSL {
				urls = append(urls, c.URL)
			}
		}
		if len(urls) == 0 {
			return nil, status.Errorf(codes.InvalidArgument,
				"must provide an external CA for the current external root CA to generate a cross-signed certificate")
		}
		rootPool := x509.NewCertPool()
		rootPool.AppendCertsFromPEM(apiRootCA.CACert)

		externalCAConfig := ca.NewExternalCATLSConfig(securityConfig.ClientTLSCreds.Config().Certificates, rootPool)
		externalCA := ca.NewExternalCA(nil, externalCAConfig, urls...)
		crossSignedCert, err = externalCA.CrossSignRootCA(ctx, newCARootCA)
	}

	if err != nil {
		log.G(ctx).WithError(err).Error("unable to generate a cross-signed certificate for root rotation")
		return nil, status.Errorf(codes.Internal, "unable to generate a cross-signed certificate for root rotation")
	}

	copied := apiRootCA.Copy()
	copied.RootRotation = &api.RootRotation{
		CACert:            rootCert,
		CAKey:             rootKey,
		CrossSignedCACert: ca.NormalizePEMs(crossSignedCert),
	}
	copied.LastForcedRotation = version
	return copied, nil
}
943574
func (c *Client) AddRootCA(caCert string) error {
	if c.httpClient == nil {
		return errors.New("Client has not been initialized yet!")
	}

	certBytes, err := ioutil.ReadFile(caCert)
	if err != nil {
		return err
	}

	tr, ok := c.httpClient.Transport.(*http.Transport)

	if !ok {
		panic("AddRootCA(): Transport type assert should not fail")
	}

	if tr.TLSClientConfig.RootCAs == nil {
		caCertPool := x509.NewCertPool()
		ok = caCertPool.AppendCertsFromPEM(certBytes)
		if ok {
			tr.TLSClientConfig.RootCAs = caCertPool
		}
		tr.TLSClientConfig.InsecureSkipVerify = false
	} else {
		ok = tr.TLSClientConfig.RootCAs.AppendCertsFromPEM(certBytes)
	}

	if !ok {
		err = errors.New("Unable to load caCert")
	}

	c.Config.CaCertFile = append(c.Config.CaCertFile, caCert)
	return err
}
542716
func (r *repository) pubKeyListForRotation(role data.RoleName, serverManaged bool, newKeys []string) (pubKeyList data.KeyList, err error) {
	var pubKey data.PublicKey

	// If server manages the key being rotated, request a rotation and return the new key
	if serverManaged {
		remote := r.getRemoteStore()
		pubKey, err = rotateRemoteKey(role, remote)
		pubKeyList = make(data.KeyList, 0, 1)
		pubKeyList = append(pubKeyList, pubKey)
		if err != nil {
			return nil, fmt.Errorf("unable to rotate remote key: %s", err)
		}
		return pubKeyList, nil
	}

	// If no new keys are passed in, we generate one
	if len(newKeys) == 0 {
		pubKeyList = make(data.KeyList, 0, 1)
		pubKey, err = r.GetCryptoService().Create(role, r.gun, data.ECDSAKey)
		pubKeyList = append(pubKeyList, pubKey)
	}
	if err != nil {
		return nil, fmt.Errorf("unable to generate key: %s", err)
	}

	// If a list of keys to rotate to are provided, we add those
	if len(newKeys) > 0 {
		pubKeyList = make(data.KeyList, 0, len(newKeys))
		for _, keyID := range newKeys {
			pubKey = r.GetCryptoService().GetKey(keyID)
			if pubKey == nil {
				return nil, fmt.Errorf("unable to find key: %s", keyID)
			}
			pubKeyList = append(pubKeyList, pubKey)
		}
	}

	// Convert to certs (for root keys)
	if pubKeyList, err = r.pubKeysToCerts(role, pubKeyList); err != nil {
		return nil, err
	}

	return pubKeyList, nil
}
1057066
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error {
	if ca == nil {
		return trace.BadParameter("missing certificate authority")
	}
	clusterName, err := a.GetClusterName()
	if err != nil {
		return trace.Wrap(err)
	}

	// this is just an extra precaution against local admins,
	// because this is additionally enforced by RBAC as well
	if ca.GetClusterName() == clusterName.GetClusterName() {
		return trace.BadParameter("can not rotate local certificate authority")
	}

	existing, err := a.Trust.GetCertAuthority(services.CertAuthID{
		Type:       ca.GetType(),
		DomainName: ca.GetClusterName(),
	}, false)
	if err != nil {
		return trace.Wrap(err)
	}

	updated := existing.Clone()
	updated.SetCheckingKeys(ca.GetCheckingKeys())
	updated.SetTLSKeyPairs(ca.GetTLSKeyPairs())
	updated.SetRotation(ca.GetRotation())

	// use compare and swap to protect from concurrent updates
	// by trusted cluster API
	if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil {
		return trace.Wrap(err)
	}

	return nil
}
1348964
func NewBaseRotatingHandler(
	filepath string, mode, bufferSize int) (*BaseRotatingHandler, error) {

	fileHandler, err := NewFileHandler(filepath, mode, bufferSize)
	if err != nil {
		return nil, err
	}
	object := &BaseRotatingHandler{
		FileHandler: fileHandler,
	}
	Closer.RemoveHandler(object.FileHandler)
	Closer.AddHandler(object)
	return object, nil
}
1340639
func (req *IdpAuthnRequest) MakeAssertionEl() error {
	keyPair := tls.Certificate{
		Certificate: [][]byte{req.IDP.Certificate.Raw},
		PrivateKey:  req.IDP.Key,
		Leaf:        req.IDP.Certificate,
	}
	for _, cert := range req.IDP.Intermediates {
		keyPair.Certificate = append(keyPair.Certificate, cert.Raw)
	}
	keyStore := dsig.TLSCertKeyStore(keyPair)

	signatureMethod := req.IDP.SignatureMethod
	if signatureMethod == "" {
		signatureMethod = dsig.RSASHA1SignatureMethod
	}

	signingContext := dsig.NewDefaultSigningContext(keyStore)
	signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList)
	if err := signingContext.SetSignatureMethod(signatureMethod); err != nil {
		return err
	}

	assertionEl := req.Assertion.Element()

	signedAssertionEl, err := signingContext.SignEnveloped(assertionEl)
	if err != nil {
		return err
	}

	sigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1]
	req.Assertion.Signature = sigEl.(*etree.Element)
	signedAssertionEl = req.Assertion.Element()

	certBuf, err := req.getSPEncryptionCert()
	if err == os.ErrNotExist {
		req.AssertionEl = signedAssertionEl
		return nil
	} else if err != nil {
		return err
	}

	var signedAssertionBuf []byte
	{
		doc := etree.NewDocument()
		doc.SetRoot(signedAssertionEl)
		signedAssertionBuf, err = doc.WriteToBytes()
		if err != nil {
			return err
		}
	}

	encryptor := xmlenc.OAEP()
	encryptor.BlockCipher = xmlenc.AES128CBC
	encryptor.DigestMethod = &xmlenc.SHA1
	encryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf)
	if err != nil {
		return err
	}
	encryptedDataEl.CreateAttr("Type", "http://www.w3.org/2001/04/xmlenc#Element")

	encryptedAssertionEl := etree.NewElement("saml:EncryptedAssertion")
	encryptedAssertionEl.AddChild(encryptedDataEl)
	req.AssertionEl = encryptedAssertionEl

	return nil
}
654722
func (s *AuthorizationService) CreateAuthorization(ctx context.Context, authorization *platform.Authorization) error {
	return s.CreateAuthorizationFn(ctx, authorization)
}
819052
func (i *Influxdb) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) {
	// Grab the lock
	i.Lock()
	defer i.Unlock()

	cli, err := i.getConnection(ctx)
	if err != nil {
		return nil, err
	}

	rotateIFQL := statements
	if len(rotateIFQL) == 0 {
		rotateIFQL = []string{defaultRootCredentialRotationIFQL}
	}

	password, err := i.GeneratePassword()
	if err != nil {
		return nil, err
	}

	var result *multierror.Error
	for _, stmt := range rotateIFQL {
		for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
			query = strings.TrimSpace(query)
			if len(query) == 0 {
				continue
			}
			q := influx.NewQuery(dbutil.QueryHelper(query, map[string]string{
				"username": i.Username,
				"password": password,
			}), "", "")
			response, err := cli.Query(q)
			result = multierror.Append(result, err)
			result = multierror.Append(result, response.Error())
		}
	}

	err = result.ErrorOrNil()
	if err != nil {
		return nil, err
	}

	i.rawConfig["password"] = password
	return i.rawConfig, nil
}
633753
func pivotRoot(rootfs string) error {
	// While the documentation may claim otherwise, pivot_root(".", ".") is
	// actually valid. What this results in is / being the new root but
	// /proc/self/cwd being the old root. Since we can play around with the cwd
	// with pivot_root this allows us to pivot without creating directories in
	// the rootfs. Shout-outs to the LXC developers for giving us this idea.

	oldroot, err := unix.Open("/", unix.O_DIRECTORY|unix.O_RDONLY, 0)
	if err != nil {
		return err
	}
	defer unix.Close(oldroot)

	newroot, err := unix.Open(rootfs, unix.O_DIRECTORY|unix.O_RDONLY, 0)
	if err != nil {
		return err
	}
	defer unix.Close(newroot)

	// Change to the new root so that the pivot_root actually acts on it.
	if err := unix.Fchdir(newroot); err != nil {
		return err
	}

	if err := unix.PivotRoot(".", "."); err != nil {
		return fmt.Errorf("pivot_root %s", err)
	}

	// Currently our "." is oldroot (according to the current kernel code).
	// However, purely for safety, we will fchdir(oldroot) since there isn't
	// really any guarantee from the kernel what /proc/self/cwd will be after a
	// pivot_root(2).

	if err := unix.Fchdir(oldroot); err != nil {
		return err
	}

	// Make oldroot rslave to make sure our unmounts don't propagate to the
	// host (and thus bork the machine). We don't use rprivate because this is
	// known to cause issues due to races where we still have a reference to a
	// mount while a process in the host namespace are trying to operate on
	// something they think has no mounts (devicemapper in particular).
	if err := unix.Mount("", ".", "", unix.MS_SLAVE|unix.MS_REC, ""); err != nil {
		return err
	}
	// Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd.
	if err := unix.Unmount(".", unix.MNT_DETACH); err != nil {
		return err
	}

	// Switch back to our shiny new root.
	if err := unix.Chdir("/"); err != nil {
		return fmt.Errorf("chdir / %s", err)
	}
	return nil
}
238457
func (c *CertAuthorityV2) GetRotation() Rotation {
	if c.Spec.Rotation == nil {
		return Rotation{}
	}
	return *c.Spec.Rotation
}
604954
func (m *manager) nextRotationDeadline() time.Time {
	// forceRotation is not protected by locks
	if m.forceRotation {
		m.forceRotation = false
		return time.Now()
	}

	m.certAccessLock.RLock()
	defer m.certAccessLock.RUnlock()

	if !m.certSatisfiesTemplateLocked() {
		return time.Now()
	}

	notAfter := m.cert.Leaf.NotAfter
	totalDuration := float64(notAfter.Sub(m.cert.Leaf.NotBefore))
	deadline := m.cert.Leaf.NotBefore.Add(jitteryDuration(totalDuration))

	klog.V(2).Infof("Certificate expiration is %v, rotation deadline is %v", notAfter, deadline)
	if m.certificateExpiration != nil {
		m.certificateExpiration.Set(float64(notAfter.Unix()))
	}
	return deadline
}
851145
func NewRootCA(rootCertBytes, signCertBytes, signKeyBytes []byte, certExpiry time.Duration, intermediates []byte) (RootCA, error) {
	// Parse all the certificates in the cert bundle
	parsedCerts, err := helpers.ParseCertificatesPEM(rootCertBytes)
	if err != nil {
		return RootCA{}, errors.Wrap(err, "invalid root certificates")
	}
	// Check to see if we have at least one valid cert
	if len(parsedCerts) < 1 {
		return RootCA{}, errors.New("no valid root CA certificates found")
	}

	// Create a Pool with all of the certificates found
	pool := x509.NewCertPool()
	for _, cert := range parsedCerts {
		if err := validateSignatureAlgorithm(cert); err != nil {
			return RootCA{}, err
		}
		// Check to see if all of the certificates are valid, self-signed root CA certs
		selfpool := x509.NewCertPool()
		selfpool.AddCert(cert)
		if _, err := cert.Verify(x509.VerifyOptions{Roots: selfpool}); err != nil {
			return RootCA{}, errors.Wrap(err, "error while validating Root CA Certificate")
		}
		pool.AddCert(cert)
	}

	// Calculate the digest for our Root CA bundle
	digest := digest.FromBytes(rootCertBytes)

	// The intermediates supplied must be able to chain up to the root certificates, so that when they are appended to
	// a leaf certificate, the leaf certificate can be validated through the intermediates to the root certificates.
	var intermediatePool *x509.CertPool
	var parsedIntermediates []*x509.Certificate
	if len(intermediates) > 0 {
		parsedIntermediates, _, err = ValidateCertChain(pool, intermediates, false)
		if err != nil {
			return RootCA{}, errors.Wrap(err, "invalid intermediate chain")
		}
		intermediatePool = x509.NewCertPool()
		for _, cert := range parsedIntermediates {
			intermediatePool.AddCert(cert)
		}
	}

	var localSigner *LocalSigner
	if len(signKeyBytes) != 0 || len(signCertBytes) != 0 {
		localSigner, err = newLocalSigner(signKeyBytes, signCertBytes, certExpiry, pool, intermediatePool)
		if err != nil {
			return RootCA{}, err
		}

		// If a signer is provided and there are intermediates, then either the first intermediate would be the signer CA
		// certificate (in which case it'd have the same subject and public key), or it would be a cross-signed
		// intermediate with the same subject and public key as our signing CA certificate (which could be either an
		// intermediate cert or a self-signed root cert).
		if len(parsedIntermediates) > 0 && (!bytes.Equal(parsedIntermediates[0].RawSubject, localSigner.parsedCert.RawSubject) ||
			!bytes.Equal(parsedIntermediates[0].RawSubjectPublicKeyInfo, localSigner.parsedCert.RawSubjectPublicKeyInfo)) {
			return RootCA{}, errors.New(
				"invalid intermediate chain - the first intermediate must have the same subject and public key as the signing cert")
		}
	}

	return RootCA{signer: localSigner, Intermediates: intermediates, Digest: digest, Certs: rootCertBytes, Pool: pool}, nil
}
292975
func (c *FakeRoleBindings) Create(roleBinding *rbacv1.RoleBinding) (result *rbacv1.RoleBinding, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(rolebindingsResource, c.ns, roleBinding), &rbacv1.RoleBinding{})

	if obj == nil {
		return nil, err
	}
	return obj.(*rbacv1.RoleBinding), err
}
229027
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error {
	rootRoles := make(map[data.RoleName]*data.RootRole)
	rootKeys := make(map[string]data.PublicKey)

	for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} {
		rootRoles[r.Name] = &data.RootRole{
			Threshold: r.Threshold,
			KeyIDs:    r.ListKeyIDs(),
		}
		for kid, k := range r.Keys {
			rootKeys[kid] = k
		}
	}
	r, err := data.NewRoot(rootKeys, rootRoles, consistent)
	if err != nil {
		return err
	}
	tr.Root = r
	tr.originalRootRole = root
	return nil
}
619302
func LoadRoot(cfg map[string]string) (*Root, error) {
	var root Root
	var err error
	spec, ok := cfg["private"]
	if !ok {
		return nil, ErrMissingPrivateKey
	}

	certPath, ok := cfg["certificate"]
	if !ok {
		return nil, ErrMissingCertificatePath
	}

	configPath, ok := cfg["config"]
	if !ok {
		return nil, ErrMissingConfigPath
	}

	root.PrivateKey, err = parsePrivateKeySpec(spec, cfg)
	if err != nil {
		return nil, err
	}

	in, err := ioutil.ReadFile(certPath)
	if err != nil {
		return nil, err
	}

	root.Certificate, err = helpers.ParseCertificatePEM(in)
	if err != nil {
		return nil, err
	}

	conf, err := config.LoadFile(configPath)
	if err != nil {
		return nil, err
	}
	root.Config = conf.Signing

	nets := cfg["nets"]
	if nets != "" {
		root.ACL, err = parseACL(nets)
		if err != nil {
			return nil, err
		}
	}

	dbConfig := cfg["dbconfig"]
	if dbConfig != "" {
		db, err := dbconf.DBFromConfig(dbConfig)
		if err != nil {
			return nil, err
		}
		root.DB = db
	}

	return &root, nil
}
922494
func NamespaceKeyRootFunc(ctx context.Context, prefix string) string {
	key := prefix
	ns, ok := genericapirequest.NamespaceFrom(ctx)
	if ok && len(ns) > 0 {
		key = key + "/" + ns
	}
	return key
}
97754
func (c *Core) GenerateRootInit(otp, pgpKey string, strategy GenerateRootStrategy) error {
	var fingerprint string
	switch {
	case len(otp) > 0:
		if len(otp) != TokenLength+2 {
			return fmt.Errorf("OTP string is wrong length")
		}

	case len(pgpKey) > 0:
		fingerprints, err := pgpkeys.GetFingerprints([]string{pgpKey}, nil)
		if err != nil {
			return errwrap.Wrapf("error parsing PGP key: {{err}}", err)
		}
		if len(fingerprints) != 1 || fingerprints[0] == "" {
			return fmt.Errorf("could not acquire PGP key entity")
		}
		fingerprint = fingerprints[0]

	default:
		return fmt.Errorf("otp or pgp_key parameter must be provided")
	}

	c.stateLock.RLock()
	defer c.stateLock.RUnlock()
	if c.Sealed() {
		return consts.ErrSealed
	}
	if c.standby {
		return consts.ErrStandby
	}

	c.generateRootLock.Lock()
	defer c.generateRootLock.Unlock()

	// Prevent multiple concurrent root generations
	if c.generateRootConfig != nil {
		return fmt.Errorf("root generation already in progress")
	}

	// Copy the configuration
	generationNonce, err := uuid.GenerateUUID()
	if err != nil {
		return err
	}

	c.generateRootConfig = &GenerateRootConfig{
		Nonce:          generationNonce,
		OTP:            otp,
		PGPKey:         pgpKey,
		PGPFingerprint: fingerprint,
		Strategy:       strategy,
	}

	if c.logger.IsInfo() {
		switch strategy.(type) {
		case generateStandardRootToken:
			c.logger.Info("root generation initialized", "nonce", c.generateRootConfig.Nonce)
		default:
			c.logger.Info("dr operation token generation initialized", "nonce", c.generateRootConfig.Nonce)
		}
	}

	return nil
}