Just use the log package's default logger as the error log.

This commit is contained in:
Solderpunk 2023-02-19 15:04:34 +01:00
parent 072669a167
commit 7a89b307a1
10 changed files with 115 additions and 126 deletions

View File

@ -10,24 +10,24 @@ import (
"time" "time"
) )
func enforceCertificateValidity(clientCerts []*x509.Certificate, conn net.Conn, log *LogEntry) { func enforceCertificateValidity(clientCerts []*x509.Certificate, conn net.Conn, logEntry *LogEntry) {
// This will fail if any of multiple certs are invalid // This will fail if any of multiple certs are invalid
// Maybe we should just require one valid? // Maybe we should just require one valid?
now := time.Now() now := time.Now()
for _, cert := range clientCerts { for _, cert := range clientCerts {
if now.Before(cert.NotBefore) { if now.Before(cert.NotBefore) {
conn.Write([]byte("64 Client certificate not yet valid!\r\n")) conn.Write([]byte("64 Client certificate not yet valid!\r\n"))
log.Status = 64 logEntry.Status = 64
return return
} else if now.After(cert.NotAfter) { } else if now.After(cert.NotAfter) {
conn.Write([]byte("65 Client certificate has expired!\r\n")) conn.Write([]byte("65 Client certificate has expired!\r\n"))
log.Status = 65 logEntry.Status = 65
return return
} }
} }
} }
func handleCertificateZones(URL *url.URL, clientCerts []*x509.Certificate, config Config, conn net.Conn, log *LogEntry) { func handleCertificateZones(URL *url.URL, clientCerts []*x509.Certificate, config Config, conn net.Conn, logEntry *LogEntry) {
authorised := true authorised := true
for zone, allowedFingerprints := range config.CertificateZones { for zone, allowedFingerprints := range config.CertificateZones {
matched, err := regexp.Match(zone, []byte(URL.Path)) matched, err := regexp.Match(zone, []byte(URL.Path))
@ -47,10 +47,10 @@ func handleCertificateZones(URL *url.URL, clientCerts []*x509.Certificate, confi
if !authorised { if !authorised {
if len(clientCerts) > 0 { if len(clientCerts) > 0 {
conn.Write([]byte("61 Provided certificate not authorised for this resource\r\n")) conn.Write([]byte("61 Provided certificate not authorised for this resource\r\n"))
log.Status = 61 logEntry.Status = 61
} else { } else {
conn.Write([]byte("60 A pre-authorised certificate is required to access this resource\r\n")) conn.Write([]byte("60 A pre-authorised certificate is required to access this resource\r\n"))
log.Status = 60 logEntry.Status = 60
} }
return return
} }

View File

@ -164,7 +164,7 @@ func getConfig(filename string) (Config, error) {
return config, nil return config, nil
} }
func parseMollyFiles(path string, config *Config, errorLog *log.Logger) { func parseMollyFiles(path string, config *Config) {
// Replace config variables which use pointers with new ones, // Replace config variables which use pointers with new ones,
// so that changes made here aren't reflected everywhere. // so that changes made here aren't reflected everywhere.
newTempRedirects := make(map[string]string) newTempRedirects := make(map[string]string)
@ -224,7 +224,7 @@ func parseMollyFiles(path string, config *Config, errorLog *log.Logger) {
// If the file exists and we can read it, try to parse it // If the file exists and we can read it, try to parse it
_, err = toml.DecodeFile(mollyPath, &mollyFile) _, err = toml.DecodeFile(mollyPath, &mollyFile)
if err != nil { if err != nil {
errorLog.Println("Error parsing .molly file " + mollyPath + ": " + err.Error()) log.Println("Error parsing .molly file " + mollyPath + ": " + err.Error())
continue continue
} }
// Overwrite main Config using MollyFile // Overwrite main Config using MollyFile
@ -237,14 +237,14 @@ func parseMollyFiles(path string, config *Config, errorLog *log.Logger) {
config.DirectoryTitles = mollyFile.DirectoryTitles config.DirectoryTitles = mollyFile.DirectoryTitles
for key, value := range mollyFile.TempRedirects { for key, value := range mollyFile.TempRedirects {
if strings.Contains(value, "://") && !strings.HasPrefix(value, "gemini://") { if strings.Contains(value, "://") && !strings.HasPrefix(value, "gemini://") {
errorLog.Println("Ignoring cross-protocol redirect to " + value + " in .molly file " + mollyPath) log.Println("Ignoring cross-protocol redirect to " + value + " in .molly file " + mollyPath)
continue continue
} }
config.TempRedirects[key] = value config.TempRedirects[key] = value
} }
for key, value := range mollyFile.PermRedirects { for key, value := range mollyFile.PermRedirects {
if strings.Contains(value, "://") && !strings.HasPrefix(value, "gemini://") { if strings.Contains(value, "://") && !strings.HasPrefix(value, "gemini://") {
errorLog.Println("Ignoring cross-protocol redirect to " + value + " in .molly file " + mollyPath) log.Println("Ignoring cross-protocol redirect to " + value + " in .molly file " + mollyPath)
continue continue
} }
config.PermRedirects[key] = value config.PermRedirects[key] = value

View File

@ -15,7 +15,7 @@ import (
"time" "time"
) )
func handleCGI(config Config, path string, cgiPath string, URL *url.URL, log *LogEntry, errorLog *log.Logger, conn net.Conn) { func handleCGI(config Config, path string, cgiPath string, URL *url.URL, logEntry *LogEntry, conn net.Conn) {
// Find the shortest leading part of path which maps to an executable file. // Find the shortest leading part of path which maps to an executable file.
// Call this part scriptPath, and everything after it pathInfo. // Call this part scriptPath, and everything after it pathInfo.
components := strings.Split(path, "/") components := strings.Split(path, "/")
@ -58,42 +58,42 @@ func handleCGI(config Config, path string, cgiPath string, URL *url.URL, log *Lo
response, err := cmd.Output() response, err := cmd.Output()
if ctx.Err() == context.DeadlineExceeded { if ctx.Err() == context.DeadlineExceeded {
errorLog.Println("Terminating CGI process " + path + " due to exceeding 10 second runtime limit.") log.Println("Terminating CGI process " + path + " due to exceeding 10 second runtime limit.")
conn.Write([]byte("42 CGI process timed out!\r\n")) conn.Write([]byte("42 CGI process timed out!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} }
if err != nil { if err != nil {
errorLog.Println("Error running CGI program " + path + ": " + err.Error()) log.Println("Error running CGI program " + path + ": " + err.Error())
if err, ok := err.(*exec.ExitError); ok { if err, ok := err.(*exec.ExitError); ok {
errorLog.Println("↳ stderr output: " + string(err.Stderr)) log.Println("↳ stderr output: " + string(err.Stderr))
} }
conn.Write([]byte("42 CGI error!\r\n")) conn.Write([]byte("42 CGI error!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} }
// Extract response header // Extract response header
header, _, err := bufio.NewReader(strings.NewReader(string(response))).ReadLine() header, _, err := bufio.NewReader(strings.NewReader(string(response))).ReadLine()
status, err2 := strconv.Atoi(strings.Fields(string(header))[0]) status, err2 := strconv.Atoi(strings.Fields(string(header))[0])
if err != nil || err2 != nil { if err != nil || err2 != nil {
errorLog.Println("Unable to parse first line of output from CGI process " + path + " as valid Gemini response header. Line was: " + string(header)) log.Println("Unable to parse first line of output from CGI process " + path + " as valid Gemini response header. Line was: " + string(header))
conn.Write([]byte("42 CGI error!\r\n")) conn.Write([]byte("42 CGI error!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} }
log.Status = status logEntry.Status = status
// Write response // Write response
conn.Write(response) conn.Write(response)
} }
func handleSCGI(URL *url.URL, scgiPath string, scgiSocket string, config Config, log *LogEntry, errorLog *log.Logger, conn net.Conn) { func handleSCGI(URL *url.URL, scgiPath string, scgiSocket string, config Config, logEntry *LogEntry, conn net.Conn) {
// Connect to socket // Connect to socket
socket, err := net.Dial("unix", scgiSocket) socket, err := net.Dial("unix", scgiSocket)
if err != nil { if err != nil {
errorLog.Println("Error connecting to SCGI socket " + scgiSocket + ": " + err.Error()) log.Println("Error connecting to SCGI socket " + scgiSocket + ": " + err.Error())
conn.Write([]byte("42 Error connecting to SCGI service!\r\n")) conn.Write([]byte("42 Error connecting to SCGI service!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} }
defer socket.Close() defer socket.Close()
@ -123,9 +123,9 @@ func handleSCGI(URL *url.URL, scgiPath string, scgiSocket string, config Config,
break break
} else if !first { } else if !first {
// Err // Err
errorLog.Println("Error reading from SCGI socket " + scgiSocket + ": " + err.Error()) log.Println("Error reading from SCGI socket " + scgiSocket + ": " + err.Error())
conn.Write([]byte("42 Error reading from SCGI service!\r\n")) conn.Write([]byte("42 Error reading from SCGI service!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} else { } else {
break break
@ -138,10 +138,10 @@ func handleSCGI(URL *url.URL, scgiPath string, scgiSocket string, config Config,
status, err := strconv.Atoi(strings.Fields(lines[0])[0]) status, err := strconv.Atoi(strings.Fields(lines[0])[0])
if err != nil { if err != nil {
conn.Write([]byte("42 CGI error!\r\n")) conn.Write([]byte("42 CGI error!\r\n"))
log.Status = 42 logEntry.Status = 42
return return
} }
log.Status = status logEntry.Status = status
} }
// Send to client // Send to client
conn.Write(buffer[:n]) conn.Write(buffer[:n])

View File

@ -35,36 +35,36 @@ func isSubdir(subdir, superdir string) (bool, error) {
return false, nil return false, nil
} }
func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan LogEntry, errorLog *log.Logger, wg *sync.WaitGroup) { func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan LogEntry, wg *sync.WaitGroup) {
defer conn.Close() defer conn.Close()
defer wg.Done() defer wg.Done()
var tlsConn (*tls.Conn) = conn.(*tls.Conn) var tlsConn (*tls.Conn) = conn.(*tls.Conn)
var log LogEntry var logEntry LogEntry
log.Time = time.Now() logEntry.Time = time.Now()
log.RemoteAddr = conn.RemoteAddr() logEntry.RemoteAddr = conn.RemoteAddr()
log.RequestURL = "-" logEntry.RequestURL = "-"
log.Status = 0 logEntry.Status = 0
if accessLogEntries != nil { if accessLogEntries != nil {
defer func() { accessLogEntries <- log }() defer func() { accessLogEntries <- logEntry }()
} }
// Read request // Read request
URL, err := readRequest(conn, &log, errorLog) URL, err := readRequest(conn, &logEntry)
if err != nil { if err != nil {
return return
} }
// Enforce client certificate validity // Enforce client certificate validity
clientCerts := tlsConn.ConnectionState().PeerCertificates clientCerts := tlsConn.ConnectionState().PeerCertificates
enforceCertificateValidity(clientCerts, conn, &log) enforceCertificateValidity(clientCerts, conn, &logEntry)
if log.Status != 0 { if logEntry.Status != 0 {
return return
} }
// Reject non-gemini schemes // Reject non-gemini schemes
if URL.Scheme != "gemini" { if URL.Scheme != "gemini" {
conn.Write([]byte("53 No proxying to non-Gemini content!\r\n")) conn.Write([]byte("53 No proxying to non-Gemini content!\r\n"))
log.Status = 53 logEntry.Status = 53
return return
} }
@ -76,14 +76,14 @@ func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan Log
} }
if requestedHost != config.Hostname || (URL.Port() != "" && URL.Port() != strconv.Itoa(config.Port)) { if requestedHost != config.Hostname || (URL.Port() != "" && URL.Port() != strconv.Itoa(config.Port)) {
conn.Write([]byte("53 No proxying to other hosts or ports!\r\n")) conn.Write([]byte("53 No proxying to other hosts or ports!\r\n"))
log.Status = 53 logEntry.Status = 53
return return
} }
// Fail if there are dots in the path // Fail if there are dots in the path
if strings.Contains(URL.Path, "..") { if strings.Contains(URL.Path, "..") {
conn.Write([]byte("50 Your directory traversal technique has been defeated!\r\n")) conn.Write([]byte("50 Your directory traversal technique has been defeated!\r\n"))
log.Status = 50 logEntry.Status = 50
return return
} }
@ -91,23 +91,23 @@ func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan Log
raw_path := resolvePath(URL.Path, config) raw_path := resolvePath(URL.Path, config)
path, err := filepath.EvalSymlinks(raw_path) path, err := filepath.EvalSymlinks(raw_path)
if err!= nil { if err!= nil {
errorLog.Println("Error evaluating path " + raw_path + " for symlinks: " + err.Error()) log.Println("Error evaluating path " + raw_path + " for symlinks: " + err.Error())
conn.Write([]byte("51 Not found!\r\n")) conn.Write([]byte("51 Not found!\r\n"))
log.Status = 51 logEntry.Status = 51
} }
// If symbolic links have been used to escape the intended document directory, // If symbolic links have been used to escape the intended document directory,
// deny all knowledge // deny all knowledge
isSub, err := isSubdir(path, config.DocBase) isSub, err := isSubdir(path, config.DocBase)
if err != nil { if err != nil {
errorLog.Println("Error testing whether path " + path + " is below DocBase: " + err.Error()) log.Println("Error testing whether path " + path + " is below DocBase: " + err.Error())
} }
if !isSub { if !isSub {
errorLog.Println("Refusing to follow simlink from " + raw_path + " outside of DocBase!") log.Println("Refusing to follow simlink from " + raw_path + " outside of DocBase!")
} }
if err != nil || !isSub { if err != nil || !isSub {
conn.Write([]byte("51 Not found!\r\n")) conn.Write([]byte("51 Not found!\r\n"))
log.Status = 51 logEntry.Status = 51
return return
} }
@ -115,31 +115,31 @@ func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan Log
// Fail ASAP if the URL has mapped to a sensitive file // Fail ASAP if the URL has mapped to a sensitive file
if path == config.CertPath || path == config.KeyPath || path == config.AccessLog || path == config.ErrorLog || filepath.Base(path) == ".molly" { if path == config.CertPath || path == config.KeyPath || path == config.AccessLog || path == config.ErrorLog || filepath.Base(path) == ".molly" {
conn.Write([]byte("51 Not found!\r\n")) conn.Write([]byte("51 Not found!\r\n"))
log.Status = 51 logEntry.Status = 51
return return
} }
// Read Molly files // Read Molly files
if config.ReadMollyFiles { if config.ReadMollyFiles {
parseMollyFiles(path, &config, errorLog) parseMollyFiles(path, &config)
} }
// Check whether this URL is in a certificate zone // Check whether this URL is in a certificate zone
handleCertificateZones(URL, clientCerts, config, conn, &log) handleCertificateZones(URL, clientCerts, config, conn, &logEntry)
if log.Status != 0 { if logEntry.Status != 0 {
return return
} }
// Check for redirects // Check for redirects
handleRedirects(URL, config, conn, &log, errorLog) handleRedirects(URL, config, conn, &logEntry)
if log.Status != 0 { if logEntry.Status != 0 {
return return
} }
// Check whether this URL is mapped to an SCGI app // Check whether this URL is mapped to an SCGI app
for scgiPath, scgiSocket := range config.SCGIPaths { for scgiPath, scgiSocket := range config.SCGIPaths {
if strings.HasPrefix(URL.Path, scgiPath) { if strings.HasPrefix(URL.Path, scgiPath) {
handleSCGI(URL, scgiPath, scgiSocket, config, &log, errorLog, conn) handleSCGI(URL, scgiPath, scgiSocket, config, &logEntry, conn)
return return
} }
} }
@ -147,8 +147,8 @@ func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan Log
// Check whether this URL is in a configured CGI path // Check whether this URL is in a configured CGI path
for _, cgiPath := range config.CGIPaths { for _, cgiPath := range config.CGIPaths {
if strings.HasPrefix(path, cgiPath) { if strings.HasPrefix(path, cgiPath) {
handleCGI(config, path, cgiPath, URL, &log, errorLog, conn) handleCGI(config, path, cgiPath, URL, &logEntry, conn)
if log.Status != 0 { if logEntry.Status != 0 {
return return
} }
} }
@ -158,50 +158,50 @@ func handleGeminiRequest(conn net.Conn, config Config, accessLogEntries chan Log
info, err := os.Stat(path) info, err := os.Stat(path)
if os.IsNotExist(err) || os.IsPermission(err) { if os.IsNotExist(err) || os.IsPermission(err) {
conn.Write([]byte("51 Not found!\r\n")) conn.Write([]byte("51 Not found!\r\n"))
log.Status = 51 logEntry.Status = 51
return return
} else if err != nil { } else if err != nil {
errorLog.Println("Error getting info for file " + path + ": " + err.Error()) log.Println("Error getting info for file " + path + ": " + err.Error())
conn.Write([]byte("40 Temporary failure!\r\n")) conn.Write([]byte("40 Temporary failure!\r\n"))
log.Status = 40 logEntry.Status = 40
return return
} else if uint64(info.Mode().Perm())&0444 != 0444 { } else if uint64(info.Mode().Perm())&0444 != 0444 {
conn.Write([]byte("51 Not found!\r\n")) conn.Write([]byte("51 Not found!\r\n"))
log.Status = 51 logEntry.Status = 51
return return
} }
// Finally, serve the file or directory // Finally, serve the file or directory
if info.IsDir() { if info.IsDir() {
serveDirectory(URL, path, &log, conn, config, errorLog) serveDirectory(URL, path, &logEntry, conn, config)
} else { } else {
serveFile(path, &log, conn, config, errorLog) serveFile(path, &logEntry, conn, config)
} }
} }
func readRequest(conn net.Conn, log *LogEntry, errorLog *log.Logger) (*url.URL, error) { func readRequest(conn net.Conn, logEntry *LogEntry) (*url.URL, error) {
reader := bufio.NewReaderSize(conn, 1024) reader := bufio.NewReaderSize(conn, 1024)
request, overflow, err := reader.ReadLine() request, overflow, err := reader.ReadLine()
if overflow { if overflow {
conn.Write([]byte("59 Request too long!\r\n")) conn.Write([]byte("59 Request too long!\r\n"))
log.Status = 59 logEntry.Status = 59
return nil, errors.New("Request too long") return nil, errors.New("Request too long")
} else if err != nil { } else if err != nil {
errorLog.Println("Error reading request from " + conn.RemoteAddr().String() + ": " + err.Error()) log.Println("Error reading request from " + conn.RemoteAddr().String() + ": " + err.Error())
conn.Write([]byte("40 Unknown error reading request!\r\n")) conn.Write([]byte("40 Unknown error reading request!\r\n"))
log.Status = 40 logEntry.Status = 40
return nil, errors.New("Error reading request") return nil, errors.New("Error reading request")
} }
// Parse request as URL // Parse request as URL
URL, err := url.Parse(string(request)) URL, err := url.Parse(string(request))
if err != nil { if err != nil {
errorLog.Println("Error parsing request URL " + string(request) + ": " + err.Error()) log.Println("Error parsing request URL " + string(request) + ": " + err.Error())
conn.Write([]byte("59 Error parsing URL!\r\n")) conn.Write([]byte("59 Error parsing URL!\r\n"))
log.Status = 59 logEntry.Status = 59
return nil, errors.New("Bad URL in request") return nil, errors.New("Bad URL in request")
} }
log.RequestURL = URL.String() logEntry.RequestURL = URL.String()
// Set implicit scheme // Set implicit scheme
if URL.Scheme == "" { if URL.Scheme == "" {
@ -225,17 +225,17 @@ func resolvePath(path string, config Config) string {
return path return path
} }
func handleRedirects(URL *url.URL, config Config, conn net.Conn, log *LogEntry, errorLog *log.Logger) { func handleRedirects(URL *url.URL, config Config, conn net.Conn, logEntry *LogEntry) {
handleRedirectsInner(URL, config.TempRedirects, 30, conn, log, errorLog) handleRedirectsInner(URL, config.TempRedirects, 30, conn, logEntry)
handleRedirectsInner(URL, config.PermRedirects, 31, conn, log, errorLog) handleRedirectsInner(URL, config.PermRedirects, 31, conn, logEntry)
} }
func handleRedirectsInner(URL *url.URL, redirects map[string]string, status int, conn net.Conn, log *LogEntry, errorLog *log.Logger) { func handleRedirectsInner(URL *url.URL, redirects map[string]string, status int, conn net.Conn, logEntry *LogEntry) {
strStatus := strconv.Itoa(status) strStatus := strconv.Itoa(status)
for src, dst := range redirects { for src, dst := range redirects {
compiled, err := regexp.Compile(src) compiled, err := regexp.Compile(src)
if err != nil { if err != nil {
errorLog.Println("Error compiling redirect regexp " + src + ": " + err.Error()) log.Println("Error compiling redirect regexp " + src + ": " + err.Error())
continue continue
} }
if compiled.MatchString(URL.Path) { if compiled.MatchString(URL.Path) {
@ -245,42 +245,42 @@ func handleRedirectsInner(URL *url.URL, redirects map[string]string, status int,
new_target = URL.String() new_target = URL.String()
} }
conn.Write([]byte(strStatus + " " + new_target + "\r\n")) conn.Write([]byte(strStatus + " " + new_target + "\r\n"))
log.Status = status logEntry.Status = status
return return
} }
} }
} }
func serveDirectory(URL *url.URL, path string, log *LogEntry, conn net.Conn, config Config, errorLog *log.Logger) { func serveDirectory(URL *url.URL, path string, logEntry *LogEntry, conn net.Conn, config Config) {
// Redirect to add trailing slash if missing // Redirect to add trailing slash if missing
// (otherwise relative links don't work properly) // (otherwise relative links don't work properly)
if !strings.HasSuffix(URL.Path, "/") { if !strings.HasSuffix(URL.Path, "/") {
URL.Path += "/" URL.Path += "/"
conn.Write([]byte(fmt.Sprintf("31 %s\r\n", URL.String()))) conn.Write([]byte(fmt.Sprintf("31 %s\r\n", URL.String())))
log.Status = 31 logEntry.Status = 31
return return
} }
// Check for index.gmi if path is a directory // Check for index.gmi if path is a directory
index_path := filepath.Join(path, "index."+config.GeminiExt) index_path := filepath.Join(path, "index."+config.GeminiExt)
index_info, err := os.Stat(index_path) index_info, err := os.Stat(index_path)
if err == nil && uint64(index_info.Mode().Perm())&0444 == 0444 { if err == nil && uint64(index_info.Mode().Perm())&0444 == 0444 {
serveFile(index_path, log, conn, config, errorLog) serveFile(index_path, logEntry, conn, config)
// Serve a generated listing // Serve a generated listing
} else { } else {
listing, err := generateDirectoryListing(URL, path, config) listing, err := generateDirectoryListing(URL, path, config)
if err != nil { if err != nil {
errorLog.Println("Error generating listing for directory " + path + ": " + err.Error()) log.Println("Error generating listing for directory " + path + ": " + err.Error())
conn.Write([]byte("40 Server error!\r\n")) conn.Write([]byte("40 Server error!\r\n"))
log.Status = 40 logEntry.Status = 40
return return
} }
conn.Write([]byte("20 text/gemini\r\n")) conn.Write([]byte("20 text/gemini\r\n"))
log.Status = 20 logEntry.Status = 20
conn.Write([]byte(listing)) conn.Write([]byte(listing))
} }
} }
func serveFile(path string, log *LogEntry, conn net.Conn, config Config, errorLog *log.Logger) { func serveFile(path string, logEntry *LogEntry, conn net.Conn, config Config) {
// Get MIME type of files // Get MIME type of files
ext := filepath.Ext(path) ext := filepath.Ext(path)
var mimeType string var mimeType string
@ -311,14 +311,14 @@ func serveFile(path string, log *LogEntry, conn net.Conn, config Config, errorLo
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
errorLog.Println("Error reading file " + path + ": " + err.Error()) log.Println("Error reading file " + path + ": " + err.Error())
conn.Write([]byte("50 Error!\r\n")) conn.Write([]byte("50 Error!\r\n"))
log.Status = 50 logEntry.Status = 50
return return
} }
defer f.Close() defer f.Close()
conn.Write([]byte(fmt.Sprintf("20 %s\r\n", mimeType))) conn.Write([]byte(fmt.Sprintf("20 %s\r\n", mimeType)))
io.Copy(conn, f) io.Copy(conn, f)
log.Status = 20 logEntry.Status = 20
} }

39
main.go
View File

@ -51,7 +51,7 @@ func do_main(config Config) int {
// chroot() possibly stops seeing /etc/passwd // chroot() possibly stops seeing /etc/passwd
privInfo, err := getUserInfo(config) privInfo, err := getUserInfo(config)
if err != nil { if err != nil {
errorLog.Println("Exiting due to failure to apply security restrictions.") log.Println("Exiting due to failure to apply security restrictions.")
return 1 return 1
} }
@ -65,18 +65,16 @@ func do_main(config Config) int {
} }
// Open log files // Open log files
var errorLogFile *os.File if config.ErrorLog != "" {
if config.ErrorLog == "" { errorLogFile, err := os.OpenFile(config.ErrorLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
errorLogFile = os.Stderr
} else {
errorLogFile, err = os.OpenFile(config.ErrorLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
log.Println(err) log.Println("Error opening error log file: " + err.Error())
return 1 return 1
} }
defer errorLogFile.Close() defer errorLogFile.Close()
log.SetOutput(errorLogFile)
} }
errorLog := log.New(errorLogFile, "", log.Ldate|log.Ltime) log.SetFlags(log.Ldate|log.Ltime)
var accessLogFile *os.File var accessLogFile *os.File
if config.AccessLog == "-" { if config.AccessLog == "-" {
@ -84,8 +82,7 @@ func do_main(config Config) int {
} else if config.AccessLog != "" { } else if config.AccessLog != "" {
accessLogFile, err = os.OpenFile(config.AccessLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) accessLogFile, err = os.OpenFile(config.AccessLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
errorLog.Println("Error opening access log file: " + err.Error()) log.Println("Error opening access log file: " + err.Error())
log.Println(err)
return 1 return 1
} }
defer accessLogFile.Close() defer accessLogFile.Close()
@ -95,16 +92,16 @@ func do_main(config Config) int {
// Check key file permissions first // Check key file permissions first
info, err := os.Stat(config.KeyPath) info, err := os.Stat(config.KeyPath)
if err != nil { if err != nil {
errorLog.Println("Error opening TLS key file: " + err.Error()) log.Println("Error opening TLS key file: " + err.Error())
return 1 return 1
} }
if uint64(info.Mode().Perm())&0444 == 0444 { if uint64(info.Mode().Perm())&0444 == 0444 {
errorLog.Println("Refusing to use world-readable TLS key file " + config.KeyPath) log.Println("Refusing to use world-readable TLS key file " + config.KeyPath)
return 1 return 1
} }
cert, err := tls.LoadX509KeyPair(config.CertPath, config.KeyPath) cert, err := tls.LoadX509KeyPair(config.CertPath, config.KeyPath)
if err != nil { if err != nil {
errorLog.Println("Error loading TLS keypair: " + err.Error()) log.Println("Error loading TLS keypair: " + err.Error())
return 1 return 1
} }
tlscfg := &tls.Config{ tlscfg := &tls.Config{
@ -117,20 +114,20 @@ func do_main(config Config) int {
// But if we can't for some reason it's no big deal // But if we can't for some reason it's no big deal
err = os.Chdir("/") err = os.Chdir("/")
if err != nil { if err != nil {
errorLog.Println("Could not change working directory to /: " + err.Error()) log.Println("Could not change working directory to /: " + err.Error())
} }
// Apply security restrictions // Apply security restrictions
err = enableSecurityRestrictions(config, privInfo, errorLog) err = enableSecurityRestrictions(config, privInfo)
if err != nil { if err != nil {
errorLog.Println("Exiting due to failure to apply security restrictions.") log.Println("Exiting due to failure to apply security restrictions.")
return 1 return 1
} }
// Create TLS listener // Create TLS listener
listener, err := tls.Listen("tcp", ":"+strconv.Itoa(config.Port), tlscfg) listener, err := tls.Listen("tcp", ":"+strconv.Itoa(config.Port), tlscfg)
if err != nil { if err != nil {
errorLog.Println("Error creating TLS listener: " + err.Error()) log.Println("Error creating TLS listener: " + err.Error())
return 1 return 1
} }
defer listener.Close() defer listener.Close()
@ -155,7 +152,7 @@ func do_main(config Config) int {
signal.Notify(sigterm, syscall.SIGTERM) signal.Notify(sigterm, syscall.SIGTERM)
go func() { go func() {
<-sigterm <-sigterm
errorLog.Println("Caught SIGTERM. Waiting for handlers to finish...") log.Println("Caught SIGTERM. Waiting for handlers to finish...")
close(shutdown) close(shutdown)
listener.Close() listener.Close()
}() }()
@ -167,19 +164,19 @@ func do_main(config Config) int {
conn, err := listener.Accept() conn, err := listener.Accept()
if err == nil { if err == nil {
wg.Add(1) wg.Add(1)
go handleGeminiRequest(conn, config, accessLogEntries, errorLog, &wg) go handleGeminiRequest(conn, config, accessLogEntries, &wg)
} else { } else {
select { select {
case <-shutdown: case <-shutdown:
running = false running = false
default: default:
errorLog.Println("Error accepting connection: " + err.Error()) log.Println("Error accepting connection: " + err.Error())
} }
} }
} }
// Wait for still-running handler Go routines to finish // Wait for still-running handler Go routines to finish
wg.Wait() wg.Wait()
errorLog.Println("Exiting.") log.Println("Exiting.")
// Exit successfully // Exit successfully
return 0 return 0

View File

@ -2,13 +2,9 @@
package main package main
import (
"log"
)
// Restrict access to the files specified in config in an OS-dependent way. // Restrict access to the files specified in config in an OS-dependent way.
// This is intended to be called immediately prior to accepting client // This is intended to be called immediately prior to accepting client
// connections and may be used to establish a security "jail" for the molly // connections and may be used to establish a security "jail" for the molly
// brown executable. // brown executable.
func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger) error { func enableSecurityRestrictions(config Config, ui userInfo) error {
} }

View File

@ -69,7 +69,7 @@ func getUserInfo(config Config) (userInfo, error) {
return ui, nil return ui, nil
} }
func DropPrivs(ui userInfo, errorLog *log.Logger) error { func DropPrivs(ui userInfo) error {
// If we're already unprivileged, all good // If we're already unprivileged, all good
if !ui.need_drop { if !ui.need_drop {
@ -80,7 +80,7 @@ func DropPrivs(ui userInfo, errorLog *log.Logger) error {
if ui.root_supp_group { if ui.root_supp_group {
err := syscall.Setgroups([]int{}) err := syscall.Setgroups([]int{})
if err != nil { if err != nil {
errorLog.Println("Could not unset supplementary groups: " + err.Error()) log.Println("Could not unset supplementary groups: " + err.Error())
return err return err
} }
} }
@ -89,7 +89,7 @@ func DropPrivs(ui userInfo, errorLog *log.Logger) error {
if ui.root_prim_group { if ui.root_prim_group {
err := syscall.Setgid(ui.unpriv_gid) err := syscall.Setgid(ui.unpriv_gid)
if err != nil { if err != nil {
errorLog.Println("Could not setgid to " + strconv.Itoa(ui.unpriv_gid) + ": " + err.Error()) log.Println("Could not setgid to " + strconv.Itoa(ui.unpriv_gid) + ": " + err.Error())
return err return err
} }
} }
@ -98,7 +98,7 @@ func DropPrivs(ui userInfo, errorLog *log.Logger) error {
if ui.root_user { if ui.root_user {
err := syscall.Setuid(ui.unpriv_uid) err := syscall.Setuid(ui.unpriv_uid)
if err != nil { if err != nil {
errorLog.Println("Could not setuid to " + strconv.Itoa(ui.unpriv_uid) + ": " + err.Error()) log.Println("Could not setuid to " + strconv.Itoa(ui.unpriv_uid) + ": " + err.Error())
return err return err
} }
} }

View File

@ -7,7 +7,7 @@ import (
"os" "os"
) )
func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger) error { func enableSecurityRestrictions(config Config, ui userInfo) error {
// Prior to Go 1.6, setuid did not work reliably on Linux // Prior to Go 1.6, setuid did not work reliably on Linux
// So, absolutely refuse to run as root // So, absolutely refuse to run as root
@ -15,7 +15,7 @@ func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger
euid := os.Geteuid() euid := os.Geteuid()
if uid == 0 || euid == 0 { if uid == 0 || euid == 0 {
setuid_err := "Refusing to run with root privileges when setuid() will not work!" setuid_err := "Refusing to run with root privileges when setuid() will not work!"
errorLog.Println(setuid_err) log.Println(setuid_err)
return error.New(setuid_err) return error.New(setuid_err)
} }

View File

@ -11,10 +11,10 @@ import (
// operations available to the molly brown executable. Please note that (S)CGI // operations available to the molly brown executable. Please note that (S)CGI
// processes that molly brown spawns or communicates with are unrestricted // processes that molly brown spawns or communicates with are unrestricted
// and should pledge their own restrictions and unveil their own files. // and should pledge their own restrictions and unveil their own files.
func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger) error { func enableSecurityRestrictions(config Config, ui userInfo) error {
// Setuid to an unprivileged user // Setuid to an unprivileged user
err := DropPrivs(ui, errorLog) err := DropPrivs(ui)
if err != nil { if err != nil {
return err return err
} }
@ -23,7 +23,7 @@ func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger
log.Println("Unveiling \"" + config.DocBase + "\" as readable.") log.Println("Unveiling \"" + config.DocBase + "\" as readable.")
err := unix.Unveil(config.DocBase, "r") err := unix.Unveil(config.DocBase, "r")
if err != nil { if err != nil {
errorLog.Println("Could not unveil DocBase: " + err.Error()) log.Println("Could not unveil DocBase: " + err.Error())
return err return err
} }
@ -34,7 +34,7 @@ func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger
log.Println("Unveiling \"" + cgiGlobbedPath + "\" as executable.") log.Println("Unveiling \"" + cgiGlobbedPath + "\" as executable.")
err = unix.Unveil(cgiGlobbedPath, "rx") err = unix.Unveil(cgiGlobbedPath, "rx")
if err != nil { if err != nil {
errorLog.Println("Could not unveil CGIPaths: " + err.Error()) log.Println("Could not unveil CGIPaths: " + err.Error())
return err return err
} }
} }
@ -53,7 +53,7 @@ func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger
// Any files not whitelisted above won't be accessible to molly brown. // Any files not whitelisted above won't be accessible to molly brown.
err = unix.UnveilBlock() err = unix.UnveilBlock()
if err != nil { if err != nil {
errorLog.Println("Could not block unveil: " + err.Error()) log.Println("Could not block unveil: " + err.Error())
return err return err
} }
@ -69,7 +69,7 @@ func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger
} }
err = unix.PledgePromises(promises) err = unix.PledgePromises(promises)
if err != nil { if err != nil {
errorLog.Println("Could not pledge: " + err.Error()) log.Println("Could not pledge: " + err.Error())
return err return err
} }
} }

View File

@ -2,13 +2,9 @@
package main package main
import ( func enableSecurityRestrictions(config Config, ui userInfo) error {
"log"
)
func enableSecurityRestrictions(config Config, ui userInfo, errorLog *log.Logger) error {
// Setuid to an unprivileged user // Setuid to an unprivileged user
return DropPrivs(ui, errorLog) return DropPrivs(ui)
} }