// RenewExistingCert loads a certificate file, uses the renew interface to renew it,
// and saves the resulting certificate and key over the old one.
979933
func RenewExistingCert(certsDir, baseName string, impl Interface) error {
	certificatePath, _ := pkiutil.PathsForCertAndKey(certsDir, baseName)
	certs, err := certutil.CertsFromFile(certificatePath)
	if err != nil {
		return errors.Wrapf(err, "failed to load existing certificate %s", baseName)
	}

	if len(certs) != 1 {
		return errors.Errorf("wanted exactly one certificate, got %d", len(certs))
	}

	cfg := certToConfig(certs[0])
	newCert, newKey, err := impl.Renew(cfg)
	if err != nil {
		return errors.Wrapf(err, "failed to renew certificate %s", baseName)
	}

	if err := pkiutil.WriteCertAndKey(certsDir, baseName, newCert, newKey); err != nil {
		return errors.Wrapf(err, "failed to write new certificate %s", baseName)
	}
	return nil
}
399767
func (cp *ConsulClient) renewService(keyName, ttl, sessionID string, jsonVal []byte, stopChan chan struct{}) {
	for {
		err := cp.client.Session().RenewPeriodic(ttl, sessionID, nil, stopChan)
		if err == nil {
			log.Infof("Stoping renew on %s", keyName)
			return
		}
		log.Infof("RenewPeriodic for session %s exited with error: %v. Retrying..", keyName, err)

		// session configuration
		sessCfg := api.SessionEntry{
			Name:      keyName,
			Behavior:  "delete",
			LockDelay: 10 * time.Millisecond,
			TTL:       ttl,
		}

		// Create consul session
		sessionID, _, err = cp.client.Session().CreateNoChecks(&sessCfg, nil)
		if err != nil {
			log.Errorf("Error Creating session for lock %s. Err: %v", keyName, err)
		}

		// Delete the old key if it exists..
		log.Infof("Deleting old service entry for key %s", keyName)
		_, err = cp.client.KV().Delete(keyName, nil)
		if err != nil {
			log.Errorf("Error deleting key %s. Err: %v", keyName, err)
		}

		// Set it via consul client
		succ, _, err := cp.client.KV().Acquire(&api.KVPair{Key: keyName, Value: jsonVal, Session: sessionID}, nil)
		if err != nil {
			log.Errorf("Error setting key %s, Err: %v", keyName, err)
		} else if !succ {
			log.Errorf("Failed to acquire key %s. Already acquired", keyName)
		}
	}
}
46061
func (s *DomainAssociation) SetCertificateVerificationDNSRecord(v string) *DomainAssociation {
	s.CertificateVerificationDNSRecord = &v
	return s
}
834923
func RenewTLSConfigNow(ctx context.Context, s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths) error {
	s.renewalMu.Lock()
	defer s.renewalMu.Unlock()

	ctx = log.WithModule(ctx, "tls")
	log := log.G(ctx).WithFields(logrus.Fields{
		"node.id":   s.ClientTLSCreds.NodeID(),
		"node.role": s.ClientTLSCreds.Role(),
	})

	// Let's request new certs. Renewals don't require a token.
	rootCA := s.RootCA()
	tlsKeyPair, issuerInfo, err := rootCA.RequestAndSaveNewCertificates(ctx,
		s.KeyWriter(),
		CertificateRequestConfig{
			ConnBroker:  connBroker,
			Credentials: s.ClientTLSCreds,
		})
	if wrappedError, ok := err.(x509UnknownAuthError); ok {
		var newErr error
		tlsKeyPair, issuerInfo, newErr = updateRootThenUpdateCert(ctx, s, connBroker, rootPaths, wrappedError.failedLeafCert)
		if newErr != nil {
			err = wrappedError.error
		} else {
			err = nil
		}
	}
	if err != nil {
		log.WithError(err).Errorf("failed to renew the certificate")
		return err
	}

	return s.UpdateTLSCredentials(tlsKeyPair, issuerInfo)
}
848225
func (kv *consulKV) renewSession(
	pair *api.KVPair,
	ttl uint64,
	noCreate bool,
) (string, error) {
	// Check if there is any previous session with an active TTL
	session, err := kv.getActiveSession(pair.Key)
	if err != nil {
		logrus.Infof("Failed to find session: %v", err)
		return "", err
	}

	if session != "" {
		if noCreate {
			// Do not create new session for the key
			return "", kvdb.ErrModified
		}
		// Destroy the existing session associated with the key
		kv.client.Destroy(session, nil)
	}

	durationTTL := time.Duration(int64(ttl)) * time.Second

	entry := &api.SessionEntry{
		Behavior:  api.SessionBehaviorDelete, // Delete the key when the session expires
		TTL:       durationTTL.String(),
		LockDelay: 0, // Virtually disable lock delay
	}

	// Create the key session
	session, _, err = kv.client.Create(entry, nil)

	// Session timer is started after a call to "Renew"
	kv.client.Renew(session, nil)

	return session, err
}
1161468
func (s *Session) Renew() error {
	if s.m == nil {
		return ErrNotPassMiddleware
	}
	return s.m.Renew(s)
}
643185
func (c *Client) Renew(acknowledgement dhcp4.Packet) (bool, dhcp4.Packet, error) {
	renewRequest := c.RenewalRequestPacket(&acknowledgement)
	renewRequest.PadToMinSize()

	err := c.SendPacket(renewRequest)
	if err != nil {
		return false, renewRequest, err
	}

	newAcknowledgement, err := c.GetAcknowledgement(&renewRequest)
	if err != nil {
		return false, newAcknowledgement, err
	}

	newAcknowledgementOptions := newAcknowledgement.ParseOptions()
	if dhcp4.MessageType(newAcknowledgementOptions[dhcp4.OptionDHCPMessageType][0]) != dhcp4.ACK {
		return false, newAcknowledgement, nil
	}

	return true, newAcknowledgement, nil
}
820450
func LoadCertFromFile(filename string) (*x509.Certificate, error) {
	certs, err := LoadCertBundleFromFile(filename)
	if err != nil {
		return nil, err
	}
	return certs[0], nil
}
1056449
func VerifyCertificate(cert *x509.Certificate) (revoked, ok bool) {
	revoked, ok, _ = VerifyCertificateError(cert)
	return revoked, ok
}
1144226
func NewCertificatesStorage(ctx *cli.Context) *CertificatesStorage {
	return &CertificatesStorage{
		rootPath:    filepath.Join(ctx.GlobalString("path"), baseCertificatesFolderName),
		archivePath: filepath.Join(ctx.GlobalString("path"), baseArchivesFolderName),
		pem:         ctx.GlobalBool("pem"),
		filename:    ctx.GlobalString("filename"),
	}
}
678293
func (self *CertificateStoreCtx) GetCurrentCert() *Certificate {
	x509 := C.X509_STORE_CTX_get_current_cert(self.ctx)
	if x509 == nil {
		return nil
	}
	// add a ref
	if 1 != C.X_X509_add_ref(x509) {
		return nil
	}
	cert := &Certificate{
		x: x509,
	}
	runtime.SetFinalizer(cert, func(cert *Certificate) {
		C.X509_free(cert.x)
	})
	return cert
}
39427
func (s *RegistrarService) RenewDomain(accountID string, domainName string, request *DomainRenewRequest) (*domainRenewalResponse, error) {
	path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/renewals", accountID, domainName))
	renewalResponse := &domainRenewalResponse{}

	resp, err := s.client.post(path, request, renewalResponse)
	if err != nil {
		return nil, err
	}

	renewalResponse.HttpResponse = resp
	return renewalResponse, nil
}
85530
func (m *ExpirationManager) RenewToken(ctx context.Context, req *logical.Request, te *logical.TokenEntry,
	increment time.Duration) (*logical.Response, error) {
	defer metrics.MeasureSince([]string{"expire", "renew-token"}, time.Now())

	tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core)
	if err != nil {
		return nil, err
	}
	if tokenNS == nil {
		return nil, namespace.ErrNoNamespace
	}

	ns, err := namespace.FromContext(ctx)
	if err != nil {
		return nil, err
	}
	if ns.ID != tokenNS.ID {
		return nil, errors.New("cannot renew a token across namespaces")
	}

	// Compute the Lease ID
	saltedID, err := m.tokenStore.SaltID(ctx, te.ID)
	if err != nil {
		return nil, err
	}

	leaseID := path.Join(te.Path, saltedID)

	if ns.ID != namespace.RootNamespaceID {
		leaseID = fmt.Sprintf("%s.%s", leaseID, ns.ID)
	}

	// Load the entry
	le, err := m.loadEntry(ctx, leaseID)
	if err != nil {
		return nil, err
	}
	if le == nil {
		return logical.ErrorResponse("invalid lease ID"), logical.ErrInvalidRequest
	}

	// Check if the lease is renewable. Note that this also checks for a nil
	// lease and errors in that case as well.
	if _, err := le.renewable(); err != nil {
		return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
	}

	// Attempt to renew the auth entry
	resp, err := m.renewAuthEntry(ctx, req, le, increment)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, nil
	}
	if resp.IsError() {
		return &logical.Response{
			Data: resp.Data,
		}, nil
	}
	if resp.Auth == nil {
		return nil, nil
	}

	sysViewCtx := namespace.ContextWithNamespace(ctx, le.namespace)
	sysView := m.router.MatchingSystemView(sysViewCtx, le.Path)
	if sysView == nil {
		return nil, fmt.Errorf("unable to retrieve system view from router")
	}

	ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Auth.TTL, resp.Auth.Period, resp.Auth.MaxTTL, resp.Auth.ExplicitMaxTTL, le.IssueTime)
	if err != nil {
		return nil, err
	}
	retResp := &logical.Response{}
	for _, warning := range warnings {
		retResp.AddWarning(warning)
	}
	resp.Auth.TTL = ttl

	// Attach the ClientToken
	resp.Auth.ClientToken = te.ID

	// Refresh groups
	if resp.Auth.EntityID != "" &&
		resp.Auth.GroupAliases != nil &&
		m.core.identityStore != nil {
		validAliases, err := m.core.identityStore.refreshExternalGroupMembershipsByEntityID(ctx, resp.Auth.EntityID, resp.Auth.GroupAliases)
		if err != nil {
			return nil, err
		}
		resp.Auth.GroupAliases = validAliases
	}

	// Update the lease entry
	le.Auth = resp.Auth
	le.ExpireTime = resp.Auth.ExpirationTime()
	le.LastRenewalTime = time.Now()

	{
		m.pendingLock.Lock()
		if err := m.persistEntry(ctx, le); err != nil {
			m.pendingLock.Unlock()
			return nil, err
		}

		// Update the expiration time
		m.updatePendingInternal(le, resp.Auth.LeaseTotal())
		m.pendingLock.Unlock()
	}

	retResp.Auth = resp.Auth
	return retResp, nil
}
108044
func (c *ACMEClient) Renew(name string) error {
	// Get access to ACME storage
	storage, err := c.config.StorageFor(c.config.CAUrl)
	if err != nil {
		return err
	}

	waiter, err := storage.TryLock(name)
	if err != nil {
		return err
	}
	if waiter != nil {
		log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name)
		waiter.Wait()
		return nil // we assume the process with the lock succeeded, rather than hammering this execution path again
	}
	defer func() {
		if err := storage.Unlock(name); err != nil {
			log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err)
		}
	}()

	// Prepare for renewal (load PEM cert, key, and meta)
	siteData, err := storage.LoadSite(name)
	if err != nil {
		return err
	}
	var certMeta acme.CertificateResource
	err = json.Unmarshal(siteData.Meta, &certMeta)
	certMeta.Certificate = siteData.Cert
	certMeta.PrivateKey = siteData.Key

	// Perform renewal and retry if necessary, but not too many times.
	var newCertMeta acme.CertificateResource
	var success bool
	for attempts := 0; attempts < 2; attempts++ {
		namesObtaining.Add([]string{name})
		acmeMu.Lock()
		newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple)
		acmeMu.Unlock()
		namesObtaining.Remove([]string{name})
		if err == nil {
			success = true
			break
		}

		// If the legal terms were updated and need to be
		// agreed to again, we can handle that.
		if _, ok := err.(acme.TOSError); ok {
			err := c.acmeClient.AgreeToTOS()
			if err != nil {
				return err
			}
			continue
		}

		// For any other kind of error, wait 10s and try again.
		wait := 10 * time.Second
		log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait)
		time.Sleep(wait)
	}

	if !success {
		return errors.New("too many renewal attempts; last error: " + err.Error())
	}

	return saveCertResource(storage, newCertMeta)
}
106681
func (s *RegisterCACertificateInput) SetVerificationCertificate(v string) *RegisterCACertificateInput {
	s.VerificationCertificate = &v
	return s
}
155800
func (r *Renewer) Renew() {
	var result error
	if r.secret.Auth != nil {
		result = r.renewAuth()
	} else {
		result = r.renewLease()
	}

	r.doneCh <- result
}
799916
func (i *macIdentity) Certificate() (*x509.Certificate, error) {
	certRef, err := i.getCertRef()
	if err != nil {
		return nil, err
	}

	crt, err := exportCertRef(certRef)
	if err != nil {
		return nil, err
	}

	i.crt = crt

	return i.crt, nil
}