2021-08-19 13:31:12 +00:00
|
|
|
package openvpn
|
2020-02-06 20:42:46 -05:00
|
|
|
|
|
|
|
|
import (
|
2022-08-15 19:54:58 -04:00
|
|
|
"fmt"
|
2020-12-29 00:55:31 +00:00
|
|
|
"os"
|
2020-07-12 14:55:03 +00:00
|
|
|
"strings"
|
2020-02-06 20:42:46 -05:00
|
|
|
)
|
|
|
|
|
|
2020-10-20 02:45:28 +00:00
|
|
|
// WriteAuthFile writes the OpenVPN auth file to disk with the right permissions.
|
2021-08-18 20:28:42 +00:00
|
|
|
func (c *Configurator) WriteAuthFile(user, password string) error {
|
2022-08-15 19:54:58 -04:00
|
|
|
content := strings.Join([]string{user, password}, "\n")
|
|
|
|
|
return writeIfDifferent(c.authFilePath, content, c.puid, c.pgid)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WriteAskPassFile writes the OpenVPN askpass file to disk with the right permissions.
|
|
|
|
|
func (c *Configurator) WriteAskPassFile(passphrase string) error {
|
|
|
|
|
return writeIfDifferent(c.askPassPath, passphrase, c.puid, c.pgid)
|
|
|
|
|
}
|
2020-12-29 00:55:31 +00:00
|
|
|
|
2022-08-15 19:54:58 -04:00
|
|
|
func writeIfDifferent(path, content string, puid, pgid int) (err error) {
|
|
|
|
|
fileStat, err := os.Stat(path)
|
2020-12-29 00:55:31 +00:00
|
|
|
if err != nil && !os.IsNotExist(err) {
|
2022-08-15 19:54:58 -04:00
|
|
|
return fmt.Errorf("obtaining file information: %w", err)
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
|
|
|
|
|
2022-08-15 19:54:58 -04:00
|
|
|
const perm = os.FileMode(0400)
|
|
|
|
|
var writeData, setChown bool
|
2020-12-29 00:55:31 +00:00
|
|
|
if os.IsNotExist(err) {
|
2022-08-15 19:54:58 -04:00
|
|
|
writeData = true
|
|
|
|
|
setChown = true
|
|
|
|
|
} else {
|
|
|
|
|
data, err := os.ReadFile(path)
|
2020-12-29 00:55:31 +00:00
|
|
|
if err != nil {
|
2022-08-15 19:54:58 -04:00
|
|
|
return fmt.Errorf("reading file: %w", err)
|
2020-07-12 14:55:03 +00:00
|
|
|
}
|
2022-08-15 19:54:58 -04:00
|
|
|
writeData = string(data) != content
|
|
|
|
|
setChown = fileStat.Mode().Perm() != perm
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
|
|
|
|
|
2022-08-15 19:54:58 -04:00
|
|
|
if writeData {
|
2022-08-24 19:39:55 +00:00
|
|
|
err = os.WriteFile(path, []byte(content), perm)
|
2022-08-15 19:54:58 -04:00
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("writing file: %w", err)
|
|
|
|
|
}
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
|
|
|
|
|
2022-08-15 19:54:58 -04:00
|
|
|
if setChown {
|
|
|
|
|
err = os.Chown(path, puid, pgid)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("setting file permissions: %w", err)
|
|
|
|
|
}
|
2020-12-29 00:55:31 +00:00
|
|
|
}
|
|
|
|
|
|
2022-08-15 19:54:58 -04:00
|
|
|
return nil
|
2020-02-06 20:42:46 -05:00
|
|
|
}
|