How to enter passive mode for FTP using Golang? - go

I am new to golang and am trying to connect to a server via ftp server using golang. But as the server requires me to enter in passive mode for me to connect with it. Could anyone please tell me how I can do that?

If you are using goftp library, set activetranfers to false
config := goftp.Config{}
config.User = userLL
config.Password = passwordLL
config.ActiveTransfers = false
client, err := goftp.DialConfig(config, hostLL)
if err != nil {
fmt.Println(err)
}

Related

GO GCP SDK auth code to connect gcp project

Im using the following code which works as expected, I use from the cli gcloud auth application-default login and enter my credentials and I was able to run the code successfully from my macbook.
Now I need to run this code in my CI and we need to use different approach , what should be the approach to get the client_secret
and client_id or service account / some ENV variable, what is the way for doing it via GO code?
import "google.golang.org/api/compute/v1"
project := "my-project"
region := "my-region"
ctx := context.Background()
c, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
if err != nil {
log.Fatal(err)
}
computeService, err := compute.New(c)
if err != nil {
log.Fatal(err)
}
req := computeService.Routers.List(project, region)
if err := req.Pages(ctx, func(page *compute.RouterList) error {
for _, router := range page.Items {
// process each `router` resource:
fmt.Printf("%#v\n", router)
// NAT Gateways are found in router.nats
}
return nil
}); err != nil {
log.Fatal(err)
}
Since you're using Jenkins you probably want to start with how to create a service account. It guides you on creating a service account and exporting a key to be set as a var in another CI/CD system.
Then refer to the docs from the client library on how to create a new client with source credential.
e.g.
client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json"))
If you provided no source, it would attempt to read the credentials locally and act as the service account running the operation (not applicable in your use case).
Many CIs support the export of specific env vars. Or your script / conf can do it too.
But if you want to run in a CI why you need such configuration? Integration tests?
Some services can be used locally for unit/smoke testing. Like pubsub, there is a way to run a fake/local pubsub to perform some tests.
Or perhaps I did not understand your question, in this case can you provide an example?

How to connect Go API to Cassandra DB

I'm using a Go API and I need to connect it to my Cassandra DB on a Google Cloud server.
This is my Go connection code:
func SetupDBConnection() {
cluster := gocql.NewCluster("XX.XXX.XXX.XXX")
cluster.Keyspace = "afterstr"
cluster.Consistency = gocql.Quorum
s, err := cluster.CreateSession()
if err != nil {
fmt.Println(err)
}
}
But, when I run this code, I have this error:
gocql: unable to create session: control: unable to connect to initial hosts: dial tcp xx.xxx.xxx.xxx:9042: i/o timeout
This is my Google Cloud configuration:
I also modified the cassandra.yaml file in my server to change the listen address and the RPC address to put my IP with the port I use to run my Go program that I opened.
(It is opened 3 times because I was just testing something)
Try:
cluster.Authenticator = gocql.PasswordAuthenticator{Username: username, Password: password}

How to confirm gRPC traffic from Go client is TLS encrypted

I wrote a sample gRPC client a server in Go, both configured for server-authenticated TLS.
The client gRPC call succeeds, giving me the impression the TLS is configured properly, otherwise if the TLS handshake had failed, I would expect the client to fail and not make the gRPC request (i.e. not default to plaintext).
Yet I am puzzled by a result I obtain when I attach Wireshark to that network to sniff TCP packets. I do not see any packet with TLS, for e.g. I do not see the TLS CLIENT HELLO packet.
So is this because I'm misinterpreting what I see in Wireshark, or is my gRPC client actually doing plaintext gRPC?
The client code looks like this, note the grpc.withTransportCredentials which I think means it will use TLS or fail, but never plaintext:
// block the dial until connection is successful or 3 sec timeout
dialOptions := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithTimeout(3 * time.Second),
}
// Load TLS Configuration
tlsCredentials, err := LoadTLSCredentials()
if err != nil {
log.Fatalf("Failed to load TLS credentials: %v", err)
}
dialOptions = append(dialOptions, grpc.WithTransportCredentials(tlsCredentials))
// Dial the gRPC server
log.Printf("Dialing %v", *address)
conn, err := grpc.Dial(*address, dialOptions...)
if err != nil {
log.Fatalf("Failed to connect to the server: %v", err)
}
defer conn.Close()
// then this application sets up a gRPC request, and logs the response to stdout,
// in my testing stdout shows the expected gRPC response, so I'd assume TLS is working.
func LoadTLSCredentials() (credentials.TransportCredentials, error) {
rootCA, err := ioutil.ReadFile("ca.cert")
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(rootCA) {
return nil, fmt.Errorf("Failed to add rootCA to x509 certificate pool")
}
config := &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: certPool,
}
return credentials.NewTLS(config), nil
}
And here's a screenshot of Wireshark showing no TLS packet
whereas I would expect something similar to the following which clearly shows some TLS activity (not my app, image is from the web for illustration purposes)
I'm running Wireshark v2.6.10 on Ubuntu 16.04. The source and destination IPs match my gRPC client and server IPs (both are docker containers on the same docker network).
Not that it really matters, but as can be seen in my client code, I'm sharing a root CA certificate on the client (self signed). I can do this because I deploy both the client and the server.
As #steffanUllrich explained in the comments, this was a case of Wireshark can be better configured to show TLS. I confirmed the gRPC exchange is indeed TLS protected.
You should right click the packet list, and select 'decode as..' menu item, then select 'tls' to force wireshark dissect traffic in this tcp port as TLS.

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.

LDAP authendication using goLang

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.

Resources