0

I have to connect with https url and I am provided with .crt, .key and .csr file. I am trying using code:

caCert, err := ioutil.ReadFile("file1.crt")
    if err != nil {
        fmt.Println("error in read crt")
        fmt.Println(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    cer, err := tls.LoadX509KeyPair("file1.crt", "file2.key")
    if err != nil {
        fmt.Println("cert load error")
        fmt.Println(err.Error())
    }

    proxyUrl, _ := url.Parse("http://xxx.xxx.xxx.xx:yy")

    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                ServerName:   "abc.com",
                RootCAs:      caCertPool,
                Certificates: []tls.Certificate{cer},
            },
            Proxy: http.ProxyURL(proxyUrl),
        }}
    req, err := http.NewRequest("POST", url, nil)

    if err != nil {
        fmt.Println(err)
    }
    req.Header.Set("id", id)
    resp, err := client.Do(req)

I am behind proxy and corporate firewall. When I try to connect using above code I am getting error:

x509: certificate signed by unknown authority

Why I am getting this error. Is code correct or I am doing something wrong.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
anujprashar
  • 6,263
  • 7
  • 52
  • 86
  • 3
    If the site you are trying to reach has a certificate signed by a public CA, don't set `RootCAs`, it will use the system root certificate pool. If it was signed by a private CA certificate, you need to add that CA certificate to the pool. The way you are doing it right now, the only server certificate allowed is `file1.crt` which is probably your client certificate (if it isn't a client certificate, you have another problem). – Marc Aug 19 '20 at 11:07
  • Thanks for reply, so to make it work I need server .crt file if it is signed by private CA and add it to pool. And if it is signed by public ca than I dont need RootCA in config of http client and it will work. – anujprashar Aug 19 '20 at 11:14
  • If it is signed by a public CA, don't set `RootCAs`, it should be in your system pool. If it is signed by a private CA (not in the system pool), you need the **CA certificate** in `RootCAs`. If it is a self-signed server certificate, then you need the **server certificate** in `RootCAs`. – Marc Aug 19 '20 at 11:19
  • @Marc There was also firewall blocking connection. So after getting permission from firewall and removing RootCA from httpclient config I am able to make connection. Thanks for your help, if you can post it as answer so that I am able to accept it. – anujprashar Aug 20 '20 at 10:08

0 Answers0