Search code examples
goauthenticode

Is there any way to sign the windows executables generated by the Go compiler?


I am trying to find out if there is a possibility to sign executables produced by the Go compiler. I cannot see this in the build/compile options. Is this even possible?


Solution

  • Signing an executable is not the responsibility of the compiler, but it is part of the build process. Change your build script to run signtool.exe after the Go compiler has generated your EXE or DLL file. Provide the path and password to the private key file (if using a .pfx file) and it will sign it for you. This is the same process that Visual Studio uses.

    https://learn.microsoft.com/en-us/windows/desktop/seccrypto/signtool


    Apparently Go's go build command is surprisingly spartan: you cannot add additional build steps nor custom commands to go build, nor is there any "hooks" feature for the go command either (other than go generate, but that's a pre-build step when we want a post-build step).

    ...which means you'll need a makefile.

    Here's a quick-and-dirty makefile (for GNU make on Windows) for a single-file project main.go, which should (it's untested) automatically runs signtool after a build:

    # golang makefile based on https://golangdocs.com/makefiles-golang
    BINARY_NAME=mygoproject.exe
     
    build:
        go build -o ${BINARY_NAME} main.go
    
        # This runs signtool with a cert in your profile store instead of a *.pfx file, to avoid needing to store a password in the makefile or environment variable: https://stackoverflow.com/questions/26998439/signtool-with-certificate-stored-in-local-computer
        signtool sign /sm /s My /n <certificateSubjectName> /t http://timestamp.digicert.com ${BINARY_NAME}
     
    run:
        go build -o ${BINARY_NAME} main.go
        ./${BINARY_NAME}
     
    clean:
        go clean
        rm ${BINARY_NAME}
    

    Just run make build from your terminal and it should just work (I hope!)