60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package prosody
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha1"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os/exec"
|
|
"strconv"
|
|
|
|
"github.com/xdg-go/pbkdf2"
|
|
)
|
|
|
|
func (p *Prosody) ChangePassword(user string, currentPwd string, newPwd string) error {
|
|
acc, err := p.loadAccount(user)
|
|
if err != nil {
|
|
return fmt.Errorf("p.loadAccount %w", err)
|
|
}
|
|
|
|
iterationCount, err := strconv.Atoi(acc.IterationCount)
|
|
if err != nil {
|
|
return fmt.Errorf("strconv.Atoi %w", err)
|
|
}
|
|
|
|
storedKey, err := hashPassword(currentPwd, acc.Salt, iterationCount)
|
|
if err != nil {
|
|
return fmt.Errorf("hashPassword: %w", err)
|
|
}
|
|
|
|
// Compare the hashes
|
|
if storedKey != acc.StoredKey {
|
|
return errors.New("password is incorrect")
|
|
}
|
|
|
|
result, err := exec.Command("/usr/bin/prosodyctl", "-c", "passwd -s 12 -scny 1").Output()
|
|
if err != nil {
|
|
return fmt.Errorf("prosodcytl: %w", err)
|
|
}
|
|
|
|
log.Println("string(result)", string(result))
|
|
return nil
|
|
}
|
|
|
|
func hashPassword(password, salt string, iterationCount int) (string, error) {
|
|
// Hash the password using the SCRAM mechanism
|
|
saltedPassword := pbkdf2.Key([]byte(password), []byte(salt), iterationCount, 20, sha1.New)
|
|
clientKey := hmacSha1(saltedPassword, []byte("Client Key"))
|
|
storedKey := sha1.Sum(clientKey)
|
|
|
|
return hex.EncodeToString(storedKey[:]), nil
|
|
}
|
|
|
|
func hmacSha1(key, data []byte) []byte {
|
|
mac := hmac.New(sha1.New, key)
|
|
mac.Write(data)
|
|
return mac.Sum(nil)
|
|
}
|