LDAP authendication using goLang - go

I am trying to authenticate with LDAP server using goLang also trying to search the user.
I am new to goLang and LDAP so I pulled GitHub code.
While trying with below code, I am getting error in authentication
func ExampleLDAPClient_Authenticate() {
client := &ldap.LDAPClient{
Base: "cn=admin,dc=testing,dc=io",
Host: "52.51.245.219",
Port: 389,
UseSSL: false,
BindDN: "cn=admin,dc=testing,dc=io",
BindPassword: "test123",
UserFilter: "(uid='*api*')",
// GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
username := "cn=admin,dc=testing,dc=io"
password := "test123"
ok, user, err := client.Authenticate(username, password)
if err != nil {
log.Fatalf("Error authenticating user %s: %+v", "*cn=admin,dc=testing,dc=io*", err)
}
if !ok {
log.Fatalf("Authenticating failed for user %s", "*cn=admin,dc=testing,dc=io*")
}
log.Printf("User: %+v", user)
}
go run example.go
2016/10/06 23:52:25 Error authenticating user *cn=admin,dc=testing,dc=io*: LDAP Result Code 201 "": ldap: finished compiling filter with extra at end: %!(EXTRA string=bmui)
Note: LDAP server working with http connection
Could anyone help me to fix this...

What library is this?
I have used http://gopkg.in/ldap.v2 and in my case it was working well (with OpenLDAP server at least). It may be worth trying it - it seems to be the most used library.

Related

Go connecting to ssh results in handshake failed

currently I am trying to connect to ssh with golang.
I enabled the PasswordAuthentication on the server and testet it by conecting via terminal this
worked like a charm no problems at all. The final goal ist to connect to a MySQL DB via ssh tunnel.
sshConfig := &ssh.ClientConfig{
User: os.Getenv("SSH_USER"),
Auth: []ssh.AuthMethod{
ssh.Password(""),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", "", sshConfig)
if err != nil {
return nil, err
}
The credentials were loaded via env vars and they also worked.
But the ssh.Dial funtion threw allways follwing error:
ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain
I checked /etc/ssh/sshd_config
I tried to use the same authentication method via the terminal and it worked
I checked the credentials
Am I missing something ?
Thanks in advance.

When deploying GCP cloud function with go client I receive: "Error 400: Precondition check failed., failedPrecondition"

I'm trying to deploy a Google Cloud Function using the go client package by google.
(https://pkg.go.dev/google.golang.org/api/cloudfunctions/v1?tab=doc#pkg-overview)
I have broken it down into the snippet I think is most relevant:
import (
"context"
log "github.com/sirupsen/logrus"
functions "google.golang.org/api/cloudfunctions/v1"
)
func main() {
ctx := context.Background()
CloudFunctionService, err := functions.NewService(ctx)
if err != nil {
log.Printf("Error at functions.NewService(ctx): \"%v\"\n", err)
}
FunctionSpec := functions.CloudFunction{
EntryPoint: "DeployThisFunctionEntryPoint",
EventTrigger: &functions.EventTrigger{
EventType: "google.pubsub.topic.publish",
Resource: "projects/mytestproject/topics/cloud-builds",
},
Name: "DeployThisFunction",
Runtime: "go111",
SourceRepository: &functions.SourceRepository{Url: "https://source.developers.google.com/projects/mytestproject/repos/deploythisfunction/moveable-aliases/master/paths//"},
}
CloudFunctionDeploymentService := functions.NewProjectsLocationsFunctionsService(CloudFunctionService)
createCall := CloudFunctionDeploymentService.Create("projects/mytestproject/locations/us-central1", &FunctionSpec)
resp, err := createCall.Context(ctx).Do()
if err != nil {
log.Printf("Error at createCall.Context(ctx).Do(): \"%v\"\n", err)
}
log.Printf("response createCall.Context(ctx).Do(): \"%v\"\n", resp)
}
However, no matter how I format it or try. I always get the following message:
googleapi: Error 400: Precondition check failed., failedPrecondition
Through the google api explorer I ran the request with their authentication and json scheme and I received the same error.
https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions/create
Response:
{
"error": {
"code": 400,
"message": "Precondition check failed.",
"status": "FAILED_PRECONDITION"
}
}
I cannot figure out what is going wrong. I have started my own project and am the administrator. When running another part of the go client with GCP for instance creating storage, IAM user, serviceaccounts, database I can make it work and create these resources.
If anyone has encountered this problem I would appreciate some help.
The eventType should match pattern : providers/*/eventTypes/*.*. .
For exmple:providers/cloud.pubsub/eventTypes/topic.publish
Also SourceRepository url should be https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/
and you have https://source.developers.google.com/projects/mytestproject/repos/deploythisfunction/moveable-aliases/master/paths//
The error message says that is an issue with the way you configure FunctionSpec, I suspect EventTrigger or SourceRepository fields.
Edit
The code: 400 is a bad request, client error, in this case formatting issue, and the first thing to check is each cloud function fileds

Getting Unimplemented desc = unknown service error gRPC

In one of my services that happens to be my loadbalancer, I am getting the following error when calling the server method in one of my deployed services:
rpc error: code = Unimplemented desc = unknown service
fooService.FooService
I have a few other services set up with gRPC and they work fine. It just seems to be this one and I am wondering if that is because it is the loadbalancer?
func GetResult(w http.ResponseWriter, r *http.Request) {
conn, errOne := grpc.Dial("redis-gateway:10006", grpc.WithInsecure())
defer conn.Close()
rClient := rs.NewRedisGatewayClient(conn)
result , errTwo := rClient.GetData(context.Background(), &rs.KeyRequest{Key: "trump", Value: "trumpVal"}, grpc.WithInsecure())
fmt.Fprintf(w, "print result: %s \n", result) //prints nil
fmt.Fprintf(w, "print error one: %v \n", errOne) // prints nil
fmt.Fprintf(w, "print error two: %s \n", errTwo) // prints error
}
The error says there is no service called fooService.FooService which is true because the dns name for the service I am calling is called foo-service. However it is the exact same setup for my other services that use gRPC and work fine. Also my proto files are correctly configured so that is not an issue.
server I am calling:
func main() {
lis, err := net.Listen("tcp", ":10006")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
newServer := &RedisGatewayServer{}
rs.RegisterRedisGatewayServer(grpcServer, newServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
The function I am trying to access from client:
func (s *RedisGatewayServer) GetData(ctx context.Context, in *rs.KeyRequest)(*rs.KeyRequest, error) {
return in, nil
}
My docker and yaml files are all correct also with the right naming and ports.
I had this exact problem, and it was because of a very simple mistake: I had put the call to the service registration after the server start. The code looked like this:
err = s.Serve(listener)
if err != nil {
log.Fatalf("[x] serve: %v", err)
}
primepb.RegisterPrimeServiceServer(s, &server{})
Obviously, the registration should have been called before the server was ran:
primepb.RegisterPrimeServiceServer(s, &server{})
err = s.Serve(listener)
if err != nil {
log.Fatalf("[x] serve: %v", err)
}
thanks #dolan's for the comment, it solved the problem.
Basically we have to make sure, the method value should be same in both server and client (you can even copy the method name from the pb.go file generated from server side)
func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error {
this invoke function will be there inside all the methods which you have implemented in gRPC service.
for me, my client was connecting to the wrong server port.
My server listens to localhost:50052
My client connects to localhost:50051
and hence I see this error.
I had the same problem - I was able to perform rpc call from Postman to the service whereas apigateway was able to connect to the service but on method call It gave error code 12 unknown service and the reason was in my proto files client was under package X whereas server was under package Y.
Quite silly but yeah making the package for both proto under apigateway and service solved my problem.
There are many scenarios in which this can happen. The underlying issue seems to be the same - the GRPC server is reachable but cannot service client requests.
The two scenarios I faced that are not documented in previous answers are:
1. Client and server are not running the same contract version
A breaking change introduced in the contract can cause this error.
In my case, the server was running the older version of the contract while the client was running the latest one.
A breaking change meant that the server could not resolve the service my client was asking for thus returning the unimplemented error.
2. The client is connecting to the wrong GRPC server
The client reached the incorrect server that doesn't implement the contract.
Consider this scenario if you're running multiple different GRPC services. You might be mistakingly dialing the wrong one.

SSH in Go: unable to authenticate, attempted methods [none], no supported methods remain

I tried to connect to one of my virtual machines using SSH and Go.
It works perfectly fine via command line if i do it like so:
ssh root#my_host
I type in the password and it works all good.
I tried to do it in Go, here is my code:
package main
import (
"golang.org/x/crypto/ssh"
"fmt"
)
func connectViaSsh(user, host string, password string) (*ssh.Client, *ssh.Session) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, config)
fmt.Println(err)
session, err := client.NewSession()
fmt.Println(err)
return client, session
}
func main() {
client, _ := connectViaSsh("root", "host:22", "password")
client.Close()
}
If i run it it returns an error:
ssh: handshake failed: ssh: unable to authenticate, attempted methods [none], no supported methods remain
Does anyone have any idea what might cause such an error. It works just fine using paramiko in Python, and in shell but fails in Go. Is there something i'm missing?
As pointed by #JimB and #putu my server doesn't have Password Authentication enabled.
To verify that i ran ssh with verbose option and it gave me back all supported authentication methods.
In my case it turned out to be following:
debug1 : Authentications that can continue: publickey,keyboard-interactive,hostbased
So i had 2 options to go with, either enable password authentication on the server or use other method to authenticate.
To enable password authentication connect to your server and open sshd config file like so:
vi /etc/ssh/sshd_config
Find line saying: PasswordAuthentication no
Change it to yes, save changes and restart sshd service: service ssh restart
After that password authentication method starts to work as expected.
Alternatively other methods can be used, i decided to try keyboard-interactive, the one user usually has when connects over the terminal using ssh.
Here is the code snippet that does just that, sends password after password question is asked by remote server:
package main
import (
"bytes"
"golang.org/x/crypto/ssh"
"fmt"
)
func connectViaSsh(user, host string, password string) (*ssh.Client, *ssh.Session) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.KeyboardInteractive(SshInteractive),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, config)
fmt.Println(err)
session, err := client.NewSession()
fmt.Println(err)
return client, session
}
func SshInteractive(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
answers = make([]string, len(questions))
// The second parameter is unused
for n, _ := range questions {
answers[n] = "your_password"
}
return answers, nil
}
func main() {
var b bytes.Buffer
client, session := connectViaSsh("root", "host:22", "password")
session.Stdout = &b
session.Run("ls")
fmt.Println(b.String())
client.Close()
}
In my case server asks only one question which is password, if your server asks more than that you would need to build an entire chain of answers to feed back in.

Couchbase GoLang client can't find bucket

I have a TCP server that tries to connect to a Couchbase database using the go-couchbase client library but I get an error saying that the bucket that I'm trying to access, named "events", doesn't exist.
When I use the official Couchbase client library for Go everything works fine.
The difference that I noticed between these two clients is the concept of "pool". I have set this pool to be "default".
What could lead to this Go client not seeing my bucket?
cb, err := couchbase.Connect("http://address:port")
if err != nil {
log.Fatalf("Error connecting: %v", err)
}
cbPool, err := cb.GetPool("default")
if err != nil {
log.Fatalf("Error getting pool: %v", err)
}
cbBucket, err := cbPool.GetBucketWithAuth("events", "username", "password")
if err != nil {
log.Fatalf("Error getting bucket: %v", err)
}
I'm assuming you're getting some kind of an authentication error. The API is a little bit confusing. GetBucketWithAuth should be called like this:
GetBucketWithAuth("events", "events", "password")
The reason is that the client wants the bucket user name and the bucket password. The bucket username is the same as the bucket name.
With that said I would highly recommend that you use gocb and not go-couchbase. gocb is the official Couchbase go client and go-couchbase is only used internally inside Couchbase. In fact many of the components that use go-couchbase will start using gocb instead since this library is much easier to use and is better organized.
https://github.com/couchbase/gocb

Resources