// Use this to initialize remote HTTPStores from the config settings
344716
func getRemoteStore(baseURL string, gun data.GUN, rt http.RoundTripper) (store.RemoteStore, error) {
	s, err := store.NewHTTPStore(
		baseURL+"/v2/"+gun.String()+"/_trust/tuf/",
		"",
		"json",
		"key",
		rt,
	)
	if err != nil {
		return store.OfflineStore{}, err
	}
	return s, nil
}
1145572
func New(rootDefs []*core.Root) (*TrustStore, error) {
	var err error

	var store = &TrustStore{}
	var roots []*x509.Certificate

	if len(rootDefs) == 0 {
		roots, err = system.New(nil)
		if err != nil {
			return nil, err
		}

		store.addCerts(roots)
		return store, nil
	}

	err = errors.New("transport: no supported root providers found")
	for _, root := range rootDefs {
		pfn, ok := Providers[root.Type]
		if ok {
			roots, err = pfn(root.Metadata)
			if err != nil {
				break
			}

			store.addCerts(roots)
		}
	}

	if err != nil {
		store = nil
	}
	return store, err
}
1171843
func (ctx *CertContext) initServerCert(host string) (err error) {
	if ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil {
		if os.IsNotExist(err) {
			fmt.Printf("Creating new PK at: %s\n", ctx.PKFile)
			if ctx.PK, err = keyman.GeneratePK(2048); err != nil {
				return
			}
			if err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {
				return fmt.Errorf("Unable to save private key: %s\n", err)
			}
		} else {
			return fmt.Errorf("Unable to read private key, even though it exists: %s\n", err)
		}
	}

	fmt.Printf("Creating new server cert at: %s\n", ctx.ServerCertFile)
	ctx.ServerCert, err = ctx.PK.TLSCertificateFor(tenYearsFromToday, true, nil, "Lantern", host)
	if err != nil {
		return
	}
	err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)
	if err != nil {
		return
	}
	return nil
}
1142360
func init() {
	tabletmanager.RegisterQueryServices = append(tabletmanager.RegisterQueryServices, func(agent *tabletmanager.ActionAgent) {
		if servenv.GRPCCheckServiceMap("tabletmanager") {
			tabletmanagerservicepb.RegisterTabletManagerServer(servenv.GRPCServer, &server{agent})
		}
	})
}
1173349
func tlsConfig(certFile, keyFile string) (*tls.Config, error) {
	if certFile == "" {
		certFile = defaultCertFile
	}
	if keyFile == "" {
		keyFile = defaultKeyFile
	}
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return nil, err
	}
	return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
}
200039
func (s *Store) Init(ctx context.Context, path string, ids ...string) error {
	if s.Initialized(ctx) {
		return errors.Errorf(`Found already initialized store at %s.
You can add secondary stores with gopass init --path <path to secondary store> --store <mount name>`, path)
	}

	// initialize recipient list
	recipients := make([]string, 0, len(ids))

	for _, id := range ids {
		if id == "" {
			continue
		}
		kl, err := s.crypto.FindPublicKeys(ctx, id)
		if err != nil {
			out.Error(ctx, "Failed to fetch public key for '%s': %s", id, err)
			continue
		}
		if len(kl) < 1 {
			out.Error(ctx, "No useable keys for '%s'", id)
			continue
		}
		recipients = append(recipients, kl[0])
	}

	if len(recipients) < 1 {
		return errors.Errorf("failed to initialize store: no valid recipients given in %+v", ids)
	}

	kl, err := s.crypto.FindPrivateKeys(ctx, recipients...)
	if err != nil {
		return errors.Errorf("Failed to get available private keys: %s", err)
	}

	if len(kl) < 1 {
		return errors.Errorf("None of the recipients has a secret key. You will not be able to decrypt the secrets you add")
	}

	if err := s.saveRecipients(ctx, recipients, "Initialized Store for "+strings.Join(recipients, ", "), true); err != nil {
		return errors.Wrapf(err, "failed to initialize store: %s", err)
	}

	return nil
}
236741
func (ec *Envcfg) TLS() *tls.Config {
	ec.once.Do(func() {
		// build cert provider
		certProvider := ec.buildCertProvider()
		if certProvider == nil {
			return
		}

		// set tls config
		ec.tls = &tls.Config{
			NextProtos:     []string{"h2", "http/1.1"},
			ServerName:     ec.Host(),
			GetCertificate: certProvider.GetCertificate,

			// qualys A+ settings
			MinVersion:               tls.VersionTLS12,
			CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
			PreferServerCipherSuites: true,
			CipherSuites: []uint16{
				tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
			},
		}
	})
	return ec.tls
}
435453
func (s *Action) initLocal(ctx context.Context, c *cli.Context) error {
	ctx = out.AddPrefix(ctx, "[local] ")

	path := ""
	if s.Store != nil {
		path = s.Store.URL()
	}

	out.Print(ctx, "Initializing your local store ...")
	if err := s.init(out.WithHidden(ctx, true), "", path); err != nil {
		return errors.Wrapf(err, "failed to init local store")
	}
	out.Green(ctx, " -> OK")

	out.Print(ctx, "Configuring your local store ...")

	if want, err := termio.AskForBool(ctx, out.Prefix(ctx)+"Do you want to add a git remote?", false); err == nil && want {
		out.Print(ctx, "Configuring the git remote ...")
		if err := s.initSetupGitRemote(ctx, "", ""); err != nil {
			return errors.Wrapf(err, "failed to setup git remote")
		}
		// autosync
		if want, err := termio.AskForBool(ctx, out.Prefix(ctx)+"Do you want to automatically push any changes to the git remote (if any)?", true); err == nil {
			s.cfg.Root.AutoSync = want
		}
	} else {
		s.cfg.Root.AutoSync = false
	}

	// noconfirm
	if want, err := termio.AskForBool(ctx, out.Prefix(ctx)+"Do you want to always confirm recipients when encrypting?", false); err == nil {
		s.cfg.Root.NoConfirm = !want
	}

	// save config
	if err := s.cfg.Save(); err != nil {
		return errors.Wrapf(err, "failed to save config")
	}

	out.Green(ctx, " -> OK")
	return nil
}
910542
func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) {
	var ret types.AuthConfig

	creds, err := client.Get(c.programFunc, serverAddress)
	if err != nil {
		if credentials.IsErrCredentialsNotFound(err) {
			// do not return an error if the credentials are not
			// in the keychain. Let docker ask for new credentials.
			return ret, nil
		}
		return ret, err
	}

	if creds.Username == tokenUsername {
		ret.IdentityToken = creds.Secret
	} else {
		ret.Password = creds.Secret
		ret.Username = creds.Username
	}

	ret.ServerAddress = serverAddress
	return ret, nil
}
1123560
func init() {
	r := http.Request{
		URL: &url.URL{
			Scheme: "http",
			Opaque: "//opaque",
		},
	}
	b := &bytes.Buffer{}
	r.Write(b)
	has4860Fix = bytes.HasPrefix(b.Bytes(), []byte("GET http"))
}
654721
func NewCallerStore(c session.Caller, storeID string) content.Store {
	client := api.NewContentClient(c.Conn())
	return &callerContentStore{
		store:   proxy.NewContentStore(client),
		storeID: storeID,
	}
}
295215
func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s secrets, err error) {
	h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
	authMsg, err := h.makeAuthMsg(prv)
	if err != nil {
		return s, err
	}
	authPacket, err := sealEIP8(authMsg, h)
	if err != nil {
		return s, err
	}
	if _, err = conn.Write(authPacket); err != nil {
		return s, err
	}

	authRespMsg := new(authRespV4)
	authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
	if err != nil {
		return s, err
	}
	if err := h.handleAuthResp(authRespMsg); err != nil {
		return s, err
	}
	return h.secrets(authPacket, authRespPacket)
}
299201
func init() {
	ps := endpoints.ProdService{}

	r := router.New()

	// Standard HTTP endpoints.
	standard.InstallHandlers(r)

	// Register all of the handlers that we want to show up in RPC explorer (via
	// pRPC discovery).
	//
	// Note that most of these services have dedicated service handlers, and any
	// RPCs sent to this module will automatically be routed to them via
	// "dispatch.yaml".
	svr := &prpc.Server{
		UnaryServerInterceptor: grpcmon.NewUnaryServerInterceptor(nil),
	}
	logsPb.RegisterLogsServer(svr, dummyLogsService)
	registrationPb.RegisterRegistrationServer(svr, dummyRegistrationService)
	servicesPb.RegisterServicesServer(svr, dummyServicesService)
	adminPb.RegisterAdminServer(svr, admin.New())
	discovery.Enable(svr)

	base := standard.Base().Extend(ps.Base)
	svr.InstallHandlers(r, base)

	r.POST("/admin/cron/stats/:stat/:namespace", base, cronStatsNSHandler)
	r.GET("/admin/cron/stats", base, cronStatsHandler)

	// Redirect "/" to "/app/".
	r.GET("/", router.MiddlewareChain{}, func(c *router.Context) {
		http.Redirect(c.Writer, c.Request, "/app/", http.StatusFound)
	})
	// Redirect "/v/?s=..." to "/logs/..."
	r.GET("/v/", router.MiddlewareChain{}, func(c *router.Context) {
		path := "/logs/" + c.Request.URL.Query().Get("s")
		http.Redirect(c.Writer, c.Request, path, http.StatusFound)
	})

	http.Handle("/", r)
}
607863
func (m *Module) Init(c *service.Config) {
	c.Setup = func() error {
		m.CookieName = "session"
		m.RevocationStore = NewInMemoryRevocationStore(defaultRevocationFlush)
		return nil
	}

	c.Start = func() {
		if m.KeyStore == nil {
			m.KeyStore = &keystore.KeyStore{}
		}
		if m.KeyFile == "" {
			m.KeyFile = defaultKeyFile
		}
		var err error
		m.encrypter, m.decryptionKey, err = loadKeys(m.KeyFile, m.KeyStore)
		if err != nil {
			panic(err)
		}
		m.revocationTrackDuration = m.SessionValidityDuration
		s, ok := m.RevocationStore.(*InMemoryRevocationStore)
		if ok {
			go s.Start()
		}
	}
}
509852
func (r *repository) getRemoteStore() store.RemoteStore {
	if r.remoteStore != nil {
		return r.remoteStore
	}

	r.remoteStore = &store.OfflineStore{}

	return r.remoteStore
}
1066039
func configureTLS(caCertificatePath string) (*http.Transport, error) {
	tr := &http.Transport{}
	// if user provided CA cert we must use it, otherwise use InsecureSkipVerify: true for all HTTPS requests.
	if caCertificatePath != "" {
		caPool, err := loadCAPool(caCertificatePath)
		if err != nil {
			return tr, err
		}

		tr.TLSClientConfig = &tls.Config{
			RootCAs: caPool,
		}
	} else {
		tr.TLSClientConfig = &tls.Config{
			InsecureSkipVerify: true,
		}
	}
	return tr, nil
}
1163457
func (p *Provider) Init() error {

	ctx := log.With(context.Background(), log.Str(log.ProviderName, "acme"))
	logger := log.FromContext(ctx)

	if p.ACMELogging {
		legolog.Logger = fmtlog.New(logger.WriterLevel(logrus.InfoLevel), "legolog: ", 0)
	} else {
		legolog.Logger = fmtlog.New(ioutil.Discard, "", 0)
	}

	if len(p.Configuration.Storage) == 0 {
		return errors.New("unable to initialize ACME provider with no storage location for the certificates")
	}
	p.Store = NewLocalStore(p.Configuration.Storage)

	var err error
	p.account, err = p.Store.GetAccount()
	if err != nil {
		return fmt.Errorf("unable to get ACME account : %v", err)
	}

	// Reset Account if caServer changed, thus registration URI can be updated
	if p.account != nil && p.account.Registration != nil && !isAccountMatchingCaServer(ctx, p.account.Registration.URI, p.CAServer) {
		logger.Info("Account URI does not match the current CAServer. The account will be reset.")
		p.account = nil
	}

	p.certificates, err = p.Store.GetCertificates()
	if err != nil {
		return fmt.Errorf("unable to get ACME certificates : %v", err)
	}

	// Init the currently resolved domain map
	p.resolvingDomains = make(map[string]struct{})

	return nil
}