Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a new internal hook to save ssh log #15787

Merged
merged 6 commits into from
May 21, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cmd/serv.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ func fail(userMessage, logMessage string, args ...interface{}) {
}
}

if len(logMessage) > 0 {
_ = private.SSHLog(true, fmt.Sprintf(logMessage+": ", args...))
}

os.Exit(1)
}

Expand Down
1 change: 1 addition & 0 deletions custom/conf/app.example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,7 @@ BUFFER_LEN = 10000
ROUTER_LOG_LEVEL = Info
ROUTER = console
ENABLE_ACCESS_LOG = false
ENABLE_SSH_LOG = false
ACCESS_LOG_TEMPLATE = {{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"
ACCESS = file
; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace"
Expand Down
1 change: 1 addition & 0 deletions docs/content/doc/advanced/config-cheat-sheet.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,7 @@ Default templates for project boards:
- `ROUTER`: **console**: The mode or name of the log the router should log to. (If you set this to `,` it will log to default gitea logger.)
NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take effect. Configure each mode in per mode log subsections `\[log.modename.router\]`.
- `ENABLE_ACCESS_LOG`: **false**: Creates an access.log in NCSA common log format, or as per the following template
- `ENABLE_SSH_LOG`: **false**: save ssh log to log file
- `ACCESS`: **file**: Logging mode for the access logger, use a comma to separate values. Configure each mode in per mode log subsections `\[log.modename.access\]`. By default the file mode will log to `$ROOT_PATH/access.log`. (If you set this to `,` it will log to the default gitea logger.)
- `ACCESS_LOG_TEMPLATE`: **`{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`**: Sets the template used to create the access log.
- The following variables are available:
Expand Down
31 changes: 31 additions & 0 deletions modules/private/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package private

import (
"encoding/json"
"fmt"
"net/http"
"net/url"
Expand Down Expand Up @@ -57,6 +58,12 @@ type HookOptions struct {
IsDeployKey bool
}

// SSHLogOption ssh log options
type SSHLogOption struct {
IsError bool
Message string
}

// HookPostReceiveResult represents an individual result from PostReceive
type HookPostReceiveResult struct {
Results []HookPostReceiveBranchResult
Expand Down Expand Up @@ -146,3 +153,27 @@ func SetDefaultBranch(ownerName, repoName, branch string) error {
}
return nil
}

// SSHLog send ssh error log to
techknowlogick marked this conversation as resolved.
Show resolved Hide resolved
func SSHLog(isErr bool, msg string) error {
reqURL := setting.LocalURL + "ssh_log"
req := newInternalRequest(reqURL, "POST")
req = req.Header("Content-Type", "application/json")

jsonBytes, _ := json.Marshal(&SSHLogOption{
IsError: isErr,
Message: msg,
})
req.Body(jsonBytes)

req.SetTimeout(60*time.Second, 60*time.Second)
resp, err := req.Response()
if err != nil {
return fmt.Errorf("unable to contact gitea: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Error returned from gitea: %v", decodeJSONError(resp).Err)
}
return nil
}
1 change: 1 addition & 0 deletions modules/setting/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ func newLogService() {

options := newDefaultLogOptions()
options.bufferLength = Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000)
EnableSSHLog = Cfg.Section("log").Key("ENABLE_SSH_LOG").MustBool(false)

description := LogDescription{
Name: log.DEFAULT,
Expand Down
1 change: 1 addition & 0 deletions modules/setting/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ var (
DisableRouterLog bool
RouterLogLevel log.Level
EnableAccessLog bool
EnableSSHLog bool
AccessLogTemplate string
EnableXORMLog bool

Expand Down
1 change: 1 addition & 0 deletions routers/private/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func Routes() *web.Route {

r.Post("/ssh/authorized_keys", AuthorizedPublicKeyByContent)
r.Post("/ssh/{id}/update/{repoid}", UpdatePublicKeyInRepo)
r.Post("/ssh_log", bind(private.SSHLogOption{}), SSHLog)
a1012112796 marked this conversation as resolved.
Show resolved Hide resolved
r.Post("/hook/pre-receive/{owner}/{repo}", bind(private.HookOptions{}), HookPreReceive)
r.Post("/hook/post-receive/{owner}/{repo}", bind(private.HookOptions{}), HookPostReceive)
r.Post("/hook/set-default-branch/{owner}/{repo}/{branch}", SetDefaultBranch)
Expand Down
34 changes: 34 additions & 0 deletions routers/private/ssh_log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package private

import (
"net/http"

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/web"
)

// SSHLog hook to response ssh log
func SSHLog(ctx *context.PrivateContext) {
if !setting.EnableSSHLog {
ctx.Status(http.StatusOK)
return
}

opts := web.GetForm(ctx).(*private.SSHLogOption)

if opts.IsError {
log.Error("ssh: %v", opts.Message)
ctx.Status(http.StatusOK)
return
}

log.Debug("ssh: %v", opts.Message)
ctx.Status(http.StatusOK)
}