Security [SOLVED]: Passing certificate and key as string to ListenAndServeTLS

Security [SOLVED]: Passing certificate and key as string to ListenAndServeTLS

Home Forums Security Security [SOLVED]: Passing certificate and key as string to ListenAndServeTLS

Tagged: ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36322

    Anonymous

    QuestionQuestion

    I am creating an app using Go and I am trying to start a https server using the ListenAndServeTLS function. Here is my code:

    func StartServer() {
        defer config.CapturePanic()
        c := config.GetInstance()
    
        serverAddress := fmt.Sprintf(":%s", c.GetConfig().ServerPort)
        server := http.Server{Addr: serverAddress}
    
        log.Info("Starting local server")
        http.HandleFunc("/", login.Handler)
        http.HandleFunc("/login", login.Handler)
        http.HandleFunc("/settings", settings.Handler)
    
        //cert, _ := data.Asset("my-cert.pem")
        //key, _ := data.Asset("my-key.pem")
        err := server.ListenAndServeTLS("my-cert.crt", "my-cert.key")
        if err != nil {
            log.WithError(err).Fatal("Error stopping local server")
        }
    }
    

    The thing is that I would like to embed my certificate and its key inside my executable file and then pass them to the the server.ListeAndServeTLS function as a string or a byte array. However this function does not take these types of arguments. Is there another way to do this?

    Note: I am aware that it is a bad practice to embed a private key inside a client application, however what I am trying to do here is just to create a config webpage that will be hosted as https://localhost:8080.

    #36323

    Anonymous

    Accepted AnswerAnswer

    You can build your own server object and still call ListenAndServeTLS. Since your tls config has certificates, it will ignore the passed-in filenames.
    I’m omitting the return on error for conciseness, please do not:

    // Generate a key pair from your pem-encoded cert and key ([]byte).
    cert, err := tls.X509KeyPair(<cert contents>, <key contents>)
    
    // Construct a tls.config
    tlsConfig := &tls.Config{
      Certificates: []tls.Certificate{cert}
      // Other options
    }
    
    // Build a server:
    server := http.Server{
        // Other options
        TLSConfig: tlsConfig,
    }
    
    // Finally: serve.
    err = server.ListenAndServeTLS("", "")
    

    Source: https://stackoverflow.com/questions/47857573/passing-certificate-and-key-as-string-to-listenandservetls
    Author: Marc
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.