// GenerateGoogleTOTP produces a new TOTP token with the defaults expected by
// Google Authenticator.
5511
func GenerateGoogleTOTP() *TOTP {
	key := make([]byte, sha1.Size)
	if _, err := io.ReadFull(PRNG, key); err != nil {
		return nil
	}
	return NewTOTP(key, 0, 30, 6, crypto.SHA1)
}
415674
func (c *Client) CreateUserWithOTP(token, password, otpToken string) (services.WebSession, error) {
	out, err := c.PostJSON(c.Endpoint("signuptokens", "users"), createUserWithTokenReq{
		Token:    token,
		Password: password,
		OTPToken: otpToken,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
648505
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) {
	// As noted in issue #10 and #17 this adds support for TOTP secrets that are
	// missing their padding.
	secret = strings.TrimSpace(secret)
	if n := len(secret) % 8; n != 0 {
		secret = secret + strings.Repeat("=", 8-n)
	}

	// As noted in issue #24 Google has started producing base32 in lower case,
	// but the StdEncoding (and the RFC), expect a dictionary of only upper case letters.
	secret = strings.ToUpper(secret)

	secretBytes, err := base32.StdEncoding.DecodeString(secret)
	if err != nil {
		return "", otp.ErrValidateSecretInvalidBase32
	}

	buf := make([]byte, 8)
	mac := hmac.New(opts.Algorithm.Hash, secretBytes)
	binary.BigEndian.PutUint64(buf, counter)
	if debug {
		fmt.Printf("counter=%v\n", counter)
		fmt.Printf("buf=%v\n", buf)
	}

	mac.Write(buf)
	sum := mac.Sum(nil)

	// "Dynamic truncation" in RFC 4226
	// http://tools.ietf.org/html/rfc4226#section-5.4
	offset := sum[len(sum)-1] & 0xf
	value := int64(((int(sum[offset]) & 0x7f) << 24) |
		((int(sum[offset+1] & 0xff)) << 16) |
		((int(sum[offset+2] & 0xff)) << 8) |
		(int(sum[offset+3]) & 0xff))

	l := opts.Digits.Length()
	mod := int32(value % int64(math.Pow10(l)))

	if debug {
		fmt.Printf("offset=%v\n", offset)
		fmt.Printf("value=%v\n", value)
		fmt.Printf("mod'ed=%v\n", mod)
	}

	return opts.Digits.Format(mod), nil
}
169875
func GenerateToken(claims map[string]interface{}, expiration time.Time) (s string, err error) {
	t := jwt.New(jwt.GetSigningMethod("RS256"))
	t.Header["typ"] = "JWT"
	t.Header["alg"] = "RS256"
	t.Header["kid"] = pubKeyId
	claims["exp"] = expiration.Unix()
	t.Claims = jwt.MapClaims(claims)
	privKey, err := jwt.ParseRSAPrivateKeyFromPEM(privKeyPEMEncoded)
	if err != nil {
		return "", err
	}
	return t.SignedString(privKey)
}
94441
func retryGoogleRPC(ctx context.Context, rpcName string, rpc func() error) error {
	return retry.Retry(ctx, transient.Only(retry.Default), func() error {
		err := rpc()
		if gerr, ok := err.(*googleapi.Error); ok && gerr.Code >= 500 {
			err = transient.Tag.Apply(err)
		}
		return err
	}, retry.LogCallback(ctx, rpcName))
}
224784
func NewGoogleClient(conf *cloudstorage.Config) (client GoogleOAuthClient, err error) {

	switch conf.AuthMethod {
	case AuthGCEDefaultOAuthToken:
		// This token method uses the default OAuth token with GCS created by tools like gsutils, gcloud, etc...
		// See github.com/lytics/lio/src/ext_svcs/google/google_transporter.go : BuildDefaultGoogleTransporter
		client, err = BuildDefaultGoogleTransporter("")
		if err != nil {
			return nil, err
		}
	case AuthGCEMetaKeySource:
		client, err = BuildGCEMetadatTransporter("")
		if err != nil {
			return nil, err
		}
	case AuthJWTKeySource:
		if conf.JwtConf == nil {
			return nil, fmt.Errorf("invalid config: missing jwt config struct")
		}
		// used if you are providing string of json
		client, err = BuildGoogleJWTTransporter(conf.JwtConf)
		if err != nil {
			return nil, err
		}
	case AuthGoogleJWTKeySource:
		switch conf.Scope {
		case "":
			// See the list here: https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/storage/storage.go#L58-L68
			return nil, fmt.Errorf("invalid config: missing devstorage scope")
		}
		client, err = BuildGoogleFileJWTTransporter(conf.JwtFile, conf.Scope)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("bad AuthMethod: %v", conf.AuthMethod)
	}

	return client, err
}
513109
func (c ProvisionUiClient) SwitchToGPGSignOK(ctx context.Context, __arg SwitchToGPGSignOKArg) (res bool, err error) {
	err = c.Cli.Call(ctx, "keybase.1.provisionUi.switchToGPGSignOK", []interface{}{__arg}, &res)
	return
}
655464
func GenerateCert(signer crypto.Signer, ca string, sn *big.Int, name string, days int, DNSNames []string, IPAddresses []net.IP, extKeyUsage []x509.ExtKeyUsage) (string, string, error) {
	parent, err := parseCert(ca)
	if err != nil {
		return "", "", err
	}

	signee, pk, err := GeneratePrivateKey()
	if err != nil {
		return "", "", err
	}

	id, err := keyID(signee.Public())
	if err != nil {
		return "", "", err
	}

	template := x509.Certificate{
		SerialNumber:          sn,
		Subject:               pkix.Name{CommonName: name},
		BasicConstraintsValid: true,
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		ExtKeyUsage:           extKeyUsage,
		IsCA:                  false,
		NotAfter:              time.Now().AddDate(0, 0, days),
		NotBefore:             time.Now(),
		SubjectKeyId:          id,
		DNSNames:              DNSNames,
		IPAddresses:           IPAddresses,
	}

	bs, err := x509.CreateCertificate(rand.Reader, &template, parent, signee.Public(), signer)
	if err != nil {
		return "", "", err
	}

	var buf bytes.Buffer
	err = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: bs})
	if err != nil {
		return "", "", fmt.Errorf("error encoding private key: %s", err)
	}

	return buf.String(), pk, nil
}
504979
func (g *Generator) generateHeader() {
	g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
	if g.file.GetOptions().GetDeprecated() {
		g.P("// ", g.file.Name, " is a deprecated file.")
	} else {
		g.P("// source: ", g.file.Name)
	}
	g.P()
	g.PrintComments(strconv.Itoa(packagePath))
	g.P()
	g.P("package ", g.file.packageName)
	g.P()
}
669659
func (i *TeleInstance) GenerateConfig(trustedSecrets []*InstanceSecrets, tconf *service.Config) (*service.Config, error) {
	var err error
	dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if tconf == nil {
		tconf = service.MakeDefaultConfig()
	}
	tconf.DataDir = dataDir
	tconf.UploadEventsC = i.UploadEventsC
	tconf.CachePolicy.Enabled = true
	tconf.Auth.ClusterName, err = services.NewClusterName(services.ClusterNameSpecV2{
		ClusterName: i.Secrets.SiteName,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	tconf.Auth.StaticTokens, err = services.NewStaticTokens(services.StaticTokensSpecV2{
		StaticTokens: []services.ProvisionTokenV1{
			{
				Roles: []teleport.Role{teleport.RoleNode, teleport.RoleProxy, teleport.RoleTrustedCluster},
				Token: "token",
			},
		},
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	tconf.Auth.Authorities = append(tconf.Auth.Authorities, i.Secrets.GetCAs()...)
	tconf.Identities = append(tconf.Identities, i.Secrets.GetIdentity())
	for _, trusted := range trustedSecrets {
		tconf.Auth.Authorities = append(tconf.Auth.Authorities, trusted.GetCAs()...)
		tconf.Auth.Roles = append(tconf.Auth.Roles, trusted.GetRoles()...)
		tconf.Identities = append(tconf.Identities, trusted.GetIdentity())
		if trusted.ListenAddr != "" {
			tconf.ReverseTunnels = []services.ReverseTunnel{
				services.NewReverseTunnel(trusted.SiteName, []string{trusted.ListenAddr}),
			}
		}
	}
	tconf.Proxy.ReverseTunnelListenAddr.Addr = i.Secrets.ListenAddr
	tconf.HostUUID = i.Secrets.GetIdentity().ID.HostUUID
	tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, i.GetPortSSH())
	tconf.SSH.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}
	tconf.Auth.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortAuth())
	tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortProxy())
	tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortWeb())
	tconf.Proxy.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        i.Hostname,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}
	tconf.AuthServers = append(tconf.AuthServers, tconf.Auth.SSHAddr)
	tconf.Auth.StorageConfig = backend.Config{
		Type:   lite.GetName(),
		Params: backend.Params{"path": dataDir + string(os.PathListSeparator) + defaults.BackendDir, "poll_stream_period": 50 * time.Millisecond},
	}

	tconf.Keygen = testauthority.New()
	i.Config = tconf
	return tconf, nil
}
279028
func (ga *GoogleAuth) doGoogleAuthCreateToken(rw http.ResponseWriter, code string) {
	resp, err := ga.client.PostForm(
		"https://www.googleapis.com/oauth2/v3/token",
		url.Values{
			"code":          []string{string(code)},
			"client_id":     []string{ga.config.ClientId},
			"client_secret": []string{ga.config.ClientSecret},
			"redirect_uri":  []string{"postmessage"},
			"grant_type":    []string{"authorization_code"},
		})
	if err != nil {
		http.Error(rw, fmt.Sprintf("Error talking to Google auth backend: %s", err), http.StatusServiceUnavailable)
		return
	}
	codeResp, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	glog.V(2).Infof("Code to token resp: %s", strings.Replace(string(codeResp), "\n", " ", -1))

	var c2t CodeToTokenResponse
	err = json.Unmarshal(codeResp, &c2t)
	if err != nil || c2t.Error != "" || c2t.ErrorDescription != "" {
		var et string
		if err != nil {
			et = err.Error()
		} else {
			et = fmt.Sprintf("%s: %s", c2t.Error, c2t.ErrorDescription)
		}
		http.Error(rw, fmt.Sprintf("Failed to get token: %s", et), http.StatusBadRequest)
		return
	}

	if c2t.RefreshToken == "" {
		http.Error(rw, "Google did not return refresh token, please sign out and sign in again.", http.StatusBadRequest)
		return
	}

	if c2t.ExpiresIn < 60 {
		http.Error(rw, "New token is too short-lived", http.StatusInternalServerError)
		return
	}

	ti, err := ga.getIDTokenInfo(c2t.IDToken)
	if err != nil {
		glog.Errorf("Newly-acquired token is invalid: %+v %s", c2t, err)
		http.Error(rw, "Newly-acquired token is invalid", http.StatusInternalServerError)
		return
	}
	user := ti.Email

	glog.Infof("New Google auth token for %s (exp %d)", user, c2t.ExpiresIn)

	v := &TokenDBValue{
		TokenType:    c2t.TokenType,
		AccessToken:  c2t.AccessToken,
		RefreshToken: c2t.RefreshToken,
		ValidUntil:   time.Now().Add(time.Duration(c2t.ExpiresIn-30) * time.Second),
	}
	dp, err := ga.db.StoreToken(user, v, true)
	if err != nil {
		glog.Errorf("Failed to record server token: %s", err)
		http.Error(rw, "Failed to record server token: %s", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(rw, `Server logged in; now run "docker login YOUR_REGISTRY_FQDN", use %s as login and %s as password.`, user, dp)
}
748018
func CreateGooglePubSubClient() (*pubsub.Client, error) {
	envValue := os.Getenv(NDGooglePubSubURL)
	if envValue != "" {
		googlePubSubURL = envValue
	}

	envValue = os.Getenv(NDGoogleProjectID)
	if envValue != "" {
		googleProjectID = envValue
	}

	ctx := cloud.NewContext(googleProjectID, http.DefaultClient)
	o := []cloud.ClientOption{
		cloud.WithBaseHTTP(http.DefaultClient),
		cloud.WithEndpoint(googleDatastoreURL),
	}
	client, _ := pubsub.NewClient(ctx, googleProjectID, o...)
	return client, nil
}
412922
func PgTsConfigByOid(db XODB, oid pgtypes.Oid) (*PgTsConfig, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, oid, ctid, cfgname, cfgnamespace, cfgowner, cfgparser ` +
		`FROM pg_catalog.pg_ts_config ` +
		`WHERE oid = $1`

	// run query
	XOLog(sqlstr, oid)
	ptc := PgTsConfig{}

	err = db.QueryRow(sqlstr, oid).Scan(&ptc.Tableoid, &ptc.Cmax, &ptc.Xmax, &ptc.Cmin, &ptc.Xmin, &ptc.Oid, &ptc.Ctid, &ptc.Cfgname, &ptc.Cfgnamespace, &ptc.Cfgowner, &ptc.Cfgparser)
	if err != nil {
		return nil, err
	}

	return &ptc, nil
}
766977
func authGooglePlus(url string) (string, string, common.Address, error) {
	// Ensure the user specified a meaningful URL, no fancy nonsense
	parts := strings.Split(url, "/")
	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
		return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
	}
	username := parts[len(parts)-3]

	// Google's API isn't really friendly with direct links. Still, we don't
	// want to do ask read permissions from users, so just load the public posts and
	// scrape it for the Ethereum address and profile URL.
	res, err := http.Get(url)
	if err != nil {
		return "", "", common.Address{}, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", "", common.Address{}, err
	}
	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
	if address == (common.Address{}) {
		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
	}
	var avatar string
	if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
		avatar = parts[1]
	}
	return username + "@google+", avatar, address, nil
}
495404
func GenerateCodeCustom(secret string, t time.Time, opts ValidateOpts) (passcode string, err error) {
	if opts.Period == 0 {
		opts.Period = 30
	}
	counter := uint64(math.Floor(float64(t.Unix()) / float64(opts.Period)))
	passcode, err = hotp.GenerateCodeCustom(secret, counter, hotp.ValidateOpts{
		Digits:    opts.Digits,
		Algorithm: opts.Algorithm,
	})
	if err != nil {
		return "", err
	}
	return passcode, nil
}
51818
func NewTgBot(token string) *TgBot {
	bot, err := NewWithError(token)
	if err != nil {
		panic(err)
	}
	return bot
}
503008
func NewGoogleProvider(client, secret, redirect string) *GoogleProvider {
	goog := GoogleProvider{}
	goog.AuthorizationURL = "https://accounts.google.com/o/oauth2/auth"
	goog.AccessTokenURL   = "https://accounts.google.com/o/oauth2/token"
	goog.RedirectURL      = redirect
	goog.ClientId         = client
	goog.ClientSecret     = secret
	return &goog
}