Search code examples
mongodbazuregomgo

How to connect to mongoDB via ssl using .crt file in Go


I am trying to connect to a mongo database hosted in azure using the .crt file.

I am successfully able to connect from my linux machine terminal using command:

mongo mongodb://username:[email protected]:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/ --tls --tlsCAFile rootca.crt --tlsAllowInvalidCertificates

I am also able to connect from mongo UI client like robo3T by setting "Use SSL protocol" and using Auth Mechanism as "SCRAM-SHA-256". [If I set Auth Mechanism to any other value, results in Authentication Failure]

But I am not able to connect to that database in Go lang code.

Here is a sample of code I am using:

package main

import (
    "crypto/tls"
    "crypto/x509"
    "io/ioutil"
    "log"
    "net"

    "github.com/globalsign/mgo"
)

func InitMongo() error {

    rootCerts := x509.NewCertPool()
    ca, err := ioutil.ReadFile("./rootca.crt")
    if err != nil {
        log.Fatalf("failed to read file : %s", err.Error())
        return err
    }

    success := rootCerts.AppendCertsFromPEM(ca)
    if !success {
        log.Printf("rootcert failed")
    }

    connStr := "mongodb://username:[email protected]:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/?ssl=true"

    dbDialInfo, err := mgo.ParseURL(connStr)
    if err != nil {
        log.Fatal("unable to parse url - " + err.Error())
    }

    dbDialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
        return tls.Dial("tcp", addr.String(), &tls.Config{
            RootCAs:            rootCerts,
            InsecureSkipVerify: true,
        })
    }

    // dbDialInfo.Mechanism = "SCRAM-SHA-256"

    _session, err := mgo.DialWithInfo(dbDialInfo)
    if err != nil {
        log.Fatalf("failed to creating db session : %s", err.Error())
        return err
    }

    log.Printf("Created session - %v", _session)

    return nil
}

When I run this code, I get error: failed to creating db session : "server returned error on SASL authentication step: Authentication failed."

If I set [dbDialInfo.Mechanism = "SCRAM-SHA-256"] before creating session, I get error: failed to creating db session : "SASL support not enabled during build (-tags sasl)"

Please let me know what is causing this issue, how can I connect to the database. Currently I am using "github.com/globalsign/mgo", if it required to use any other library, that's totally fine for me. I just want to get connected to the db.

rootca.crt file looks something like:

-----BEGIN CERTIFICATE-----
MIIGLjCCBBagAwIBAgIUbxINX1qe6W+7kolWGp+MX8NbYj8wDQYJKoZIhvcNAQEL
<blah> <blah> <blah> <blah> <blah> <blah> <blah> <blah> <blah> 
jCZAGGHmbrR3zeIsOY8yKau0IXqRp5Wy6NQ0poOTcma9BfwNUVc4/ixsCkEVYbgW
eMs=
-----END CERTIFICATE-----

Thank you.


Solution

  • After researching a lot, I was not able to find a way to connect to mongodb using .crt file using globalsign library.

    However I was successfully able to do this using mongo-driver library. here connection string can be of format:

    mongodb://user:[email protected]:27017,replicaset-1.com:27017,replicaset-2.com:27017/?ssl=true&tlsCAFile=./ca.crt&tlsCertificateKeyFile=./ca.pem&authSource=admin&replicaSet=replicaset
    

    Sample code:

    import (
        "context"
        "log"
        "os"
    
        // "github.com/globalsign/mgo"
        mgo "go.mongodb.org/mongo-driver/mongo"
    
        mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
    )
    func InitMongo() (error) {
        
        connStr := os.Getenv("MONGODB_CONN_STR")
        dbName := os.Getenv("MONGODB_DATABASE")
    
        clientOpts := mongoOptions.Client().ApplyURI(connStr)
        if err := clientOpts.Validate(); err != nil {
            log.Print("unable to parse url")
            log.Fatal(err)
        }
        client, err := mgo.Connect(context.TODO(), clientOpts)
        if err != nil {
            log.Print("unable to connect into database")
            log.Fatal(err)
        }
        if err := client.Ping(context.TODO(), nil); err != nil {
            log.Print("database ping failed")
            log.Fatal(err)
        }
    
        //client.Database(dbName)
    
        return nil
    }