apkovl-cli/cmd/passwd.go

107 lines
2.8 KiB
Go
Raw Normal View History

/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/GehirnInc/crypt"
_ "github.com/GehirnInc/crypt/sha512_crypt"
log "github.com/s00500/env_logger"
"github.com/spf13/cobra"
)
// passwdCmd represents the passwd command
var passwdCmd = &cobra.Command{
Use: "passwd",
Short: "Change a user password by editing /etc/shadow",
Long: `Change a user password by editing /etc/shadow, first argument is user (defaults to root), second is password, can also be enteres via promt if not specified`,
Run: func(cmd *cobra.Command, args []string) {
log.Println("passwd called")
// promt for a user
user := "root"
if len(args) > 0 {
user = args[0]
}
// promt for a password
newPassword := ""
if len(args) > 1 {
newPassword = args[1]
} else {
newPassword = promtPassword("New Password")
}
if newPassword == "" {
log.Fatal("No password specified")
}
prepareWorkdir()
// Modify /etc/shadow
pwHash := encryptPassword(newPassword)
shadowDat, err := os.ReadFile(workdir + "/etc/shadow")
log.MustFatal(err)
newShadow := ""
scanner := bufio.NewScanner(strings.NewReader(string(shadowDat)))
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), user+":") {
parts := strings.Split(scanner.Text(), ":")
//log.Info(scanner.Text())
parts[1] = pwHash
//log.Info(strings.Join(parts, ":") + "\n")
newShadow += strings.Join(parts, ":") + "\n"
continue
}
newShadow += scanner.Text() + "\n"
}
err = os.WriteFile(workdir+"/etc/shadow", []byte(newShadow), 0600)
log.MustFatal(err)
createOutput()
},
}
func init() {
rootCmd.AddCommand(passwdCmd)
}
func encryptPassword(userPassword string) string {
// Generate a random string for use in the salt
const charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
s := make([]byte, 8)
for i := range s {
s[i] = charset[seededRand.Intn(len(charset))]
}
salt := []byte(fmt.Sprintf("$6$%s", s))
// use salt to hash user-supplied password
crypt := crypt.SHA512.New()
hash, err := crypt.Generate([]byte(userPassword), salt)
if err != nil {
log.Fatalf("error hashing user's supplied password: %s\n", err)
}
return string(hash)
}