Golang : Verify Linux user password again before executing a program example

Tags : golang password authentication pamexec

One of my previous tutorial shows you how to restrict a program execution to root only and this can be restrictive for some as the root password needs to be shared around. Mr. Jake of the Philipines would like to know how to force a user to enter his or her username and password before allowing a program to execute. Instead of hard coding the password/username into the code, he needs know how his program can authenticate the username and password against the Linux's user/password database.

In Linux, we can use the PAM(Pluggable Authentication Module) to check if a username/password is valid before allowing further execution of the program.

The code example below uses the Linux PAM(Pluggable Authentication Module) to verify if a username and password are registered in the Linux's database. If yes, allow the user to proceed and if not, simply abort the program.

NOTE: In case the code did not compile due to a missing library. Install libpam0g-dev on your Linux machine. sudo yum install libpam0g-dev or sudo apt-get install libpam0g-dev should fix the issue.

NOTE: Do not use this program on none Linux OS.

Here you go!

 package main

 import (

 func authService() error {
  t, err := pam.StartFunc("", "", func(s pam.Style, msg string) (string, error) {
 switch s {
 case pam.PromptEchoOff:
 return speakeasy.Ask(msg)
 case pam.PromptEchoOn:
 fmt.Print(msg + " ")
 input, err := bufio.NewReader(os.Stdin).ReadString('\n')
 if err != nil {
 return "", err
 return input[:len(input)-1], nil
 case pam.ErrorMsg:
 return "", nil
 case pam.TextInfo:
 return "", nil
 return "", errors.New("Unrecognized message style")
  if err != nil {
 return err
  err = t.Authenticate(0)
  if err != nil {
 return err
  //fmt.Println("Authentication succeeded!")
  return nil


 func main() {
  if runtime.GOOS != "linux" { // also can be specified to FreeBSD
 fmt.Println("PAM(Pluggable Authentication Modules) only works with Linux!!")

  err := authService()

  if err != nil {
 fmt.Println("Unable to authenticate your password or username! Abort!")
  } else {
 fmt.Println("Credential accepted! Proceeding to .....")
 // this is where you want to execute your main function for authenticated users.

Execute the code and feed it with valid and none valid username/password combinations to see the differences.

Happy coding!




  See also : Golang : Get login name from environment and prompt for password

Tags : golang password authentication pamexec

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.