SSHSecure/config/func.go

82 lines
2.0 KiB
Go

/*
SSHSecure - a program to harden OpenSSH from defaults
Copyright (C) 2020 Brent Saner
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package config
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"github.com/pkg/errors"
"r00t2.io/sysutils/exec_extra"
"r00t2.io/sysutils/paths"
)
func TestConfig(config *[]byte) (bool, error) {
var sysPaths []string
var binPath string
var tmpConf *os.File
var err error
var stdout, stderr bytes.Buffer
// sshd *requires* to be invoked with an absolute path.
sysPaths, err = paths.GetPathEnv()
if err != nil {
return false, err
}
for _, p := range sysPaths {
fpath := path.Join(p, "sshd")
if exists, err := paths.RealPathExists(&fpath); err != nil {
return false, err
} else if !exists {
continue
}
binPath = fpath
break
}
tmpConf, err = ioutil.TempFile("/tmp", ".test.sshconf.")
if err != nil {
return false, err
}
defer os.Remove(tmpConf.Name())
if err = tmpConf.Chmod(0600); err != nil {
return false, err
}
if _, err = tmpConf.Write(*config); err != nil {
return false, err
}
cmd := exec.Command(binPath,
"-T", fmt.Sprintf("-f %v",
tmpConf.Name()))
cmd.Stdout = &stdout
cmd.Stderr = &stderr
exitStatus, err := exec_extra.ExecCmdReturn(cmd)
if err != nil {
return false, err
}
if exitStatus != 0 {
// TODO: also handle non-empty stderr?
e := fmt.Sprintf("returned status/exit code %d", exitStatus)
return false, errors.New(e)
}
return true, nil
}