2019-02-07 12:43:12 +05:30
// Copyright 2017 The Gitea Authors. All rights reserved.
2022-11-27 23:50:29 +05:30
// SPDX-License-Identifier: MIT
2014-07-26 09:54:27 +05:30
package ssh
import (
2020-10-11 06:08:09 +05:30
"bytes"
2021-07-14 20:13:13 +05:30
"context"
2019-02-07 12:43:12 +05:30
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
2022-07-29 01:26:55 +05:30
"errors"
2019-07-07 06:58:09 +05:30
"fmt"
2015-11-09 03:29:56 +05:30
"io"
2021-06-28 22:35:27 +05:30
"net"
2014-07-26 09:54:27 +05:30
"os"
"os/exec"
2015-11-09 03:29:56 +05:30
"path/filepath"
2023-08-10 07:35:37 +05:30
"reflect"
2021-11-06 11:53:32 +05:30
"strconv"
2014-07-26 09:54:27 +05:30
"strings"
2019-07-07 06:58:09 +05:30
"sync"
"syscall"
2014-07-26 09:54:27 +05:30
2021-12-10 13:44:24 +05:30
asymkey_model "code.gitea.io/gitea/models/asymkey"
2022-03-31 22:31:43 +05:30
"code.gitea.io/gitea/modules/graceful"
2016-11-10 21:54:48 +05:30
"code.gitea.io/gitea/modules/log"
2022-03-31 22:31:43 +05:30
"code.gitea.io/gitea/modules/process"
2016-11-10 21:54:48 +05:30
"code.gitea.io/gitea/modules/setting"
2020-11-28 08:12:08 +05:30
"code.gitea.io/gitea/modules/util"
2019-07-07 06:58:09 +05:30
"github.com/gliderlabs/ssh"
gossh "golang.org/x/crypto/ssh"
2014-07-26 09:54:27 +05:30
)
2019-07-07 06:58:09 +05:30
type contextKey string
const giteaKeyID = contextKey ( "gitea-key-id" )
func getExitStatusFromError ( err error ) int {
if err == nil {
return 0
2015-11-09 03:29:56 +05:30
}
2019-07-07 06:58:09 +05:30
exitErr , ok := err . ( * exec . ExitError )
if ! ok {
return 1
}
2015-11-09 03:29:56 +05:30
2019-07-07 06:58:09 +05:30
waitStatus , ok := exitErr . Sys ( ) . ( syscall . WaitStatus )
if ! ok {
// This is a fallback and should at least let us return something useful
// when running on Windows, even if it isn't completely accurate.
if exitErr . Success ( ) {
return 0
2014-07-26 09:54:27 +05:30
}
2019-07-07 06:58:09 +05:30
return 1
2014-07-26 09:54:27 +05:30
}
2019-07-07 06:58:09 +05:30
return waitStatus . ExitStatus ( )
2014-07-26 09:54:27 +05:30
}
2019-07-07 06:58:09 +05:30
func sessionHandler ( session ssh . Session ) {
2020-12-25 15:29:32 +05:30
keyID := fmt . Sprintf ( "%d" , session . Context ( ) . Value ( giteaKeyID ) . ( int64 ) )
2019-07-07 06:58:09 +05:30
command := session . RawCommand ( )
log . Trace ( "SSH: Payload: %v" , command )
Refactor path & config system (#25330)
# The problem
There were many "path tricks":
* By default, Gitea uses its program directory as its work path
* Gitea tries to use the "work path" to guess its "custom path" and
"custom conf (app.ini)"
* Users might want to use other directories as work path
* The non-default work path should be passed to Gitea by GITEA_WORK_DIR
or "--work-path"
* But some Gitea processes are started without these values
* The "serv" process started by OpenSSH server
* The CLI sub-commands started by site admin
* The paths are guessed by SetCustomPathAndConf again and again
* The default values of "work path / custom path / custom conf" can be
changed when compiling
# The solution
* Use `InitWorkPathAndCommonConfig` to handle these path tricks, and use
test code to cover its behaviors.
* When Gitea's web server runs, write the WORK_PATH to "app.ini", this
value must be the most correct one, because if this value is not right,
users would find that the web UI doesn't work and then they should be
able to fix it.
* Then all other sub-commands can use the WORK_PATH in app.ini to
initialize their paths.
* By the way, when Gitea starts for git protocol, it shouldn't output
any log, otherwise the git protocol gets broken and client blocks
forever.
The "work path" priority is: WORK_PATH in app.ini > cmd arg --work-path
> env var GITEA_WORK_DIR > builtin default
The "app.ini" searching order is: cmd arg --config > cmd arg "work path
/ custom path" > env var "work path / custom path" > builtin default
## ⚠️ BREAKING
If your instance's "work path / custom path / custom conf" doesn't meet
the requirements (eg: work path must be absolute), Gitea will report a
fatal error and exit. You need to set these values according to the
error log.
----
Close #24818
Close #24222
Close #21606
Close #21498
Close #25107
Close #24981
Maybe close #24503
Replace #23301
Replace #22754
And maybe more
2023-06-21 11:20:26 +05:30
args := [ ] string { "--config=" + setting . CustomConf , "serv" , "key-" + keyID }
2019-07-07 06:58:09 +05:30
log . Trace ( "SSH: Arguments: %v" , args )
2021-07-14 20:13:13 +05:30
ctx , cancel := context . WithCancel ( session . Context ( ) )
defer cancel ( )
2022-08-02 13:26:38 +05:30
gitProtocol := ""
for _ , env := range session . Environ ( ) {
if strings . HasPrefix ( env , "GIT_PROTOCOL=" ) {
2022-08-03 04:04:50 +05:30
_ , gitProtocol , _ = strings . Cut ( env , "=" )
2022-08-02 13:26:38 +05:30
break
}
}
2021-07-14 20:13:13 +05:30
cmd := exec . CommandContext ( ctx , setting . AppPath , args ... )
2019-07-07 06:58:09 +05:30
cmd . Env = append (
os . Environ ( ) ,
"SSH_ORIGINAL_COMMAND=" + command ,
"SKIP_MINWINSVC=1" ,
2022-08-02 13:26:38 +05:30
"GIT_PROTOCOL=" + gitProtocol ,
2019-07-07 06:58:09 +05:30
)
stdout , err := cmd . StdoutPipe ( )
2014-07-26 09:54:27 +05:30
if err != nil {
2019-07-07 06:58:09 +05:30
log . Error ( "SSH: StdoutPipe: %v" , err )
return
2014-07-26 09:54:27 +05:30
}
2021-07-14 20:13:13 +05:30
defer stdout . Close ( )
2019-07-07 06:58:09 +05:30
stderr , err := cmd . StderrPipe ( )
if err != nil {
log . Error ( "SSH: StderrPipe: %v" , err )
return
}
2021-07-14 20:13:13 +05:30
defer stderr . Close ( )
2019-07-07 06:58:09 +05:30
stdin , err := cmd . StdinPipe ( )
if err != nil {
log . Error ( "SSH: StdinPipe: %v" , err )
return
}
2021-07-14 20:13:13 +05:30
defer stdin . Close ( )
2019-07-07 06:58:09 +05:30
2022-06-03 20:06:18 +05:30
process . SetSysProcAttribute ( cmd )
2019-07-07 06:58:09 +05:30
wg := & sync . WaitGroup { }
wg . Add ( 2 )
if err = cmd . Start ( ) ; err != nil {
log . Error ( "SSH: Start: %v" , err )
return
}
go func ( ) {
defer stdin . Close ( )
if _ , err := io . Copy ( stdin , session ) ; err != nil {
log . Error ( "Failed to write session to stdin. %s" , err )
}
} ( )
go func ( ) {
defer wg . Done ( )
2021-07-14 20:13:13 +05:30
defer stdout . Close ( )
2019-07-07 06:58:09 +05:30
if _ , err := io . Copy ( session , stdout ) ; err != nil {
log . Error ( "Failed to write stdout to session. %s" , err )
}
} ( )
go func ( ) {
defer wg . Done ( )
2021-07-14 20:13:13 +05:30
defer stderr . Close ( )
2019-07-07 06:58:09 +05:30
if _ , err := io . Copy ( session . Stderr ( ) , stderr ) ; err != nil {
log . Error ( "Failed to write stderr to session. %s" , err )
2014-07-26 09:54:27 +05:30
}
2019-07-07 06:58:09 +05:30
} ( )
// Ensure all the output has been written before we wait on the command
// to exit.
wg . Wait ( )
// Wait for the command to exit and log any errors we get
err = cmd . Wait ( )
if err != nil {
2022-07-29 01:26:55 +05:30
// Cannot use errors.Is here because ExitError doesn't implement Is
// Thus errors.Is will do equality test NOT type comparison
if _ , ok := err . ( * exec . ExitError ) ; ! ok {
log . Error ( "SSH: Wait: %v" , err )
}
2019-07-07 06:58:09 +05:30
}
2022-07-29 01:26:55 +05:30
if err := session . Exit ( getExitStatusFromError ( err ) ) ; err != nil && ! errors . Is ( err , io . EOF ) {
2019-07-07 06:58:09 +05:30
log . Error ( "Session failed to exit. %s" , err )
}
}
func publicKeyHandler ( ctx ssh . Context , key ssh . PublicKey ) bool {
2023-08-10 07:35:37 +05:30
// FIXME: the "ssh.Context" is not thread-safe, so db operations should use the immutable parent "Context"
// TODO: Remove after https://github.com/gliderlabs/ssh/pull/211
parentCtx := reflect . ValueOf ( ctx ) . Elem ( ) . FieldByName ( "Context" ) . Interface ( ) . ( context . Context )
2020-12-15 14:15:13 +05:30
if log . IsDebug ( ) { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
log . Debug ( "Handle Public Key: Fingerprint: %s from %s" , gossh . FingerprintSHA256 ( key ) , ctx . RemoteAddr ( ) )
}
2019-07-07 06:58:09 +05:30
if ctx . User ( ) != setting . SSH . BuiltinServerUser {
2020-12-15 14:15:13 +05:30
log . Warn ( "Invalid SSH username %s - must use %s for all git operations via ssh" , ctx . User ( ) , setting . SSH . BuiltinServerUser )
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
2019-07-07 06:58:09 +05:30
return false
}
2016-02-01 22:40:49 +05:30
2020-10-11 06:08:09 +05:30
// check if we have a certificate
if cert , ok := key . ( * gossh . Certificate ) ; ok {
2020-12-15 14:15:13 +05:30
if log . IsDebug ( ) { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
log . Debug ( "Handle Certificate: %s Fingerprint: %s is a certificate" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( key ) )
}
2020-10-11 06:08:09 +05:30
if len ( setting . SSH . TrustedUserCAKeys ) == 0 {
2020-12-15 14:15:13 +05:30
log . Warn ( "Certificate Rejected: No trusted certificate authorities for this server" )
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
2020-10-11 06:08:09 +05:30
return false
}
2023-09-01 19:15:22 +05:30
if cert . CertType != gossh . UserCert {
log . Warn ( "Certificate Rejected: Not a user certificate" )
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
return false
}
2020-10-11 06:08:09 +05:30
// look for the exact principal
2020-12-12 04:22:38 +05:30
principalLoop :
2020-10-11 06:08:09 +05:30
for _ , principal := range cert . ValidPrincipals {
2023-08-10 07:35:37 +05:30
pkey , err := asymkey_model . SearchPublicKeyByContentExact ( parentCtx , principal )
2020-10-11 06:08:09 +05:30
if err != nil {
2021-12-10 13:44:24 +05:30
if asymkey_model . IsErrKeyNotExist ( err ) {
2020-12-15 14:15:13 +05:30
log . Debug ( "Principal Rejected: %s Unknown Principal: %s" , ctx . RemoteAddr ( ) , principal )
2020-12-12 04:22:38 +05:30
continue principalLoop
}
2020-10-11 06:08:09 +05:30
log . Error ( "SearchPublicKeyByContentExact: %v" , err )
return false
}
c := & gossh . CertChecker {
IsUserAuthority : func ( auth gossh . PublicKey ) bool {
2022-06-05 12:46:14 +05:30
marshaled := auth . Marshal ( )
2020-10-11 06:08:09 +05:30
for _ , k := range setting . SSH . TrustedUserCAKeysParsed {
2022-06-05 12:46:14 +05:30
if bytes . Equal ( marshaled , k . Marshal ( ) ) {
2020-10-11 06:08:09 +05:30
return true
}
}
return false
} ,
}
// check the CA of the cert
if ! c . IsUserAuthority ( cert . SignatureKey ) {
2020-12-15 14:15:13 +05:30
if log . IsDebug ( ) {
log . Debug ( "Principal Rejected: %s Untrusted Authority Signature Fingerprint %s for Principal: %s" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( cert . SignatureKey ) , principal )
}
2020-12-12 04:22:38 +05:30
continue principalLoop
2020-10-11 06:08:09 +05:30
}
// validate the cert for this principal
if err := c . CheckCert ( principal , cert ) ; err != nil {
2020-12-15 14:15:13 +05:30
// User is presenting an invalid certificate - STOP any further processing
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-22 04:05:11 +05:30
log . Error ( "Invalid Certificate KeyID %s with Signature Fingerprint %s presented for Principal: %s from %s" , cert . KeyId , gossh . FingerprintSHA256 ( cert . SignatureKey ) , principal , ctx . RemoteAddr ( ) )
2020-12-15 14:15:13 +05:30
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
2020-10-11 06:08:09 +05:30
return false
}
2020-12-15 14:15:13 +05:30
if log . IsDebug ( ) { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
log . Debug ( "Successfully authenticated: %s Certificate Fingerprint: %s Principal: %s" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( key ) , principal )
}
2020-10-11 06:08:09 +05:30
ctx . SetValue ( giteaKeyID , pkey . ID )
return true
}
2020-12-15 14:15:13 +05:30
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-22 04:05:11 +05:30
log . Warn ( "From %s Fingerprint: %s is a certificate, but no valid principals found" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( key ) )
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
2020-12-15 14:15:13 +05:30
return false
}
if log . IsDebug ( ) { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
log . Debug ( "Handle Public Key: %s Fingerprint: %s is not a certificate" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( key ) )
2020-10-11 06:08:09 +05:30
}
2023-08-10 07:35:37 +05:30
pkey , err := asymkey_model . SearchPublicKeyByContent ( parentCtx , strings . TrimSpace ( string ( gossh . MarshalAuthorizedKey ( key ) ) ) )
2019-07-07 06:58:09 +05:30
if err != nil {
2021-12-10 13:44:24 +05:30
if asymkey_model . IsErrKeyNotExist ( err ) {
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-22 04:05:11 +05:30
log . Warn ( "Unknown public key: %s from %s" , gossh . FingerprintSHA256 ( key ) , ctx . RemoteAddr ( ) )
log . Warn ( "Failed authentication attempt from %s" , ctx . RemoteAddr ( ) )
2020-12-12 04:22:38 +05:30
return false
}
2020-12-15 14:15:13 +05:30
log . Error ( "SearchPublicKeyByContent: %v" , err )
2019-07-07 06:58:09 +05:30
return false
2014-07-26 09:54:27 +05:30
}
2019-07-07 06:58:09 +05:30
2020-12-15 14:15:13 +05:30
if log . IsDebug ( ) { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
log . Debug ( "Successfully authenticated: %s Public Key Fingerprint: %s" , ctx . RemoteAddr ( ) , gossh . FingerprintSHA256 ( key ) )
}
2019-07-07 06:58:09 +05:30
ctx . SetValue ( giteaKeyID , pkey . ID )
return true
2014-07-26 09:54:27 +05:30
}
2021-06-28 22:35:27 +05:30
// sshConnectionFailed logs a failed connection
// - this mainly exists to give a nice function name in logging
func sshConnectionFailed ( conn net . Conn , err error ) {
// Log the underlying error with a specific message
log . Warn ( "Failed connection from %s with error: %v" , conn . RemoteAddr ( ) , err )
// Log with the standard failed authentication from message for simpler fail2ban configuration
log . Warn ( "Failed authentication attempt from %s" , conn . RemoteAddr ( ) )
}
2014-07-26 09:54:27 +05:30
// Listen starts a SSH server listens on given port.
2021-12-20 10:11:31 +05:30
func Listen ( host string , port int , ciphers , keyExchanges , macs [ ] string ) {
2019-07-07 06:58:09 +05:30
srv := ssh . Server {
2021-11-06 11:53:32 +05:30
Addr : net . JoinHostPort ( host , strconv . Itoa ( port ) ) ,
2019-07-07 06:58:09 +05:30
PublicKeyHandler : publicKeyHandler ,
Handler : sessionHandler ,
2021-01-30 18:50:32 +05:30
ServerConfigCallback : func ( ctx ssh . Context ) * gossh . ServerConfig {
config := & gossh . ServerConfig { }
config . KeyExchanges = keyExchanges
config . MACs = macs
config . Ciphers = ciphers
return config
} ,
2021-06-28 22:35:27 +05:30
ConnectionFailedCallback : sshConnectionFailed ,
2019-07-07 06:58:09 +05:30
// We need to explicitly disable the PtyCallback so text displays
// properly.
PtyCallback : func ( ctx ssh . Context , pty ssh . Pty ) bool {
return false
2014-07-26 09:54:27 +05:30
} ,
}
2021-03-08 08:13:59 +05:30
keys := make ( [ ] string , 0 , len ( setting . SSH . ServerHostKeys ) )
for _ , key := range setting . SSH . ServerHostKeys {
isExist , err := util . IsExist ( key )
if err != nil {
log . Fatal ( "Unable to check if %s exists. Error: %v" , setting . SSH . ServerHostKeys , err )
}
if isExist {
keys = append ( keys , key )
}
2020-11-28 08:12:08 +05:30
}
2021-03-08 08:13:59 +05:30
if len ( keys ) == 0 {
filePath := filepath . Dir ( setting . SSH . ServerHostKeys [ 0 ] )
2016-12-01 05:26:15 +05:30
if err := os . MkdirAll ( filePath , os . ModePerm ) ; err != nil {
2019-04-02 13:18:31 +05:30
log . Error ( "Failed to create dir %s: %v" , filePath , err )
2016-12-01 05:26:15 +05:30
}
2021-03-08 08:13:59 +05:30
err := GenKeyPair ( setting . SSH . ServerHostKeys [ 0 ] )
2015-11-14 23:51:31 +05:30
if err != nil {
2019-04-02 13:18:31 +05:30
log . Fatal ( "Failed to generate private key: %v" , err )
2015-11-14 23:51:31 +05:30
}
2021-03-08 08:13:59 +05:30
log . Trace ( "New private key is generated: %s" , setting . SSH . ServerHostKeys [ 0 ] )
keys = append ( keys , setting . SSH . ServerHostKeys [ 0 ] )
2015-11-14 23:51:31 +05:30
}
2021-03-08 08:13:59 +05:30
for _ , key := range keys {
log . Info ( "Adding SSH host key: %s" , key )
err := srv . SetOption ( ssh . HostKeyFile ( key ) )
if err != nil {
log . Error ( "Failed to set Host Key. %s" , err )
}
2014-07-26 09:54:27 +05:30
}
2022-03-31 22:31:43 +05:30
go func ( ) {
_ , _ , finished := process . GetManager ( ) . AddTypedContext ( graceful . GetManager ( ) . HammerContext ( ) , "Service: Built-in SSH server" , process . SystemProcessType , true )
defer finished ( )
listen ( & srv )
} ( )
2014-07-26 09:54:27 +05:30
}
2019-02-07 12:43:12 +05:30
// GenKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
func GenKeyPair ( keyPath string ) error {
2021-03-08 08:13:59 +05:30
privateKey , err := rsa . GenerateKey ( rand . Reader , 4096 )
2019-02-07 12:43:12 +05:30
if err != nil {
return err
}
privateKeyPEM := & pem . Block { Type : "RSA PRIVATE KEY" , Bytes : x509 . MarshalPKCS1PrivateKey ( privateKey ) }
2022-01-20 23:16:10 +05:30
f , err := os . OpenFile ( keyPath , os . O_RDWR | os . O_CREATE | os . O_TRUNC , 0 o600 )
2019-02-07 12:43:12 +05:30
if err != nil {
return err
}
2019-06-13 01:11:28 +05:30
defer func ( ) {
if err = f . Close ( ) ; err != nil {
log . Error ( "Close: %v" , err )
}
} ( )
2019-02-07 12:43:12 +05:30
if err := pem . Encode ( f , privateKeyPEM ) ; err != nil {
return err
}
// generate public key
2019-07-07 06:58:09 +05:30
pub , err := gossh . NewPublicKey ( & privateKey . PublicKey )
2019-02-07 12:43:12 +05:30
if err != nil {
return err
}
2019-07-07 06:58:09 +05:30
public := gossh . MarshalAuthorizedKey ( pub )
2022-01-20 23:16:10 +05:30
p , err := os . OpenFile ( keyPath + ".pub" , os . O_RDWR | os . O_CREATE | os . O_TRUNC , 0 o600 )
2019-02-07 12:43:12 +05:30
if err != nil {
return err
}
2019-06-13 01:11:28 +05:30
defer func ( ) {
if err = p . Close ( ) ; err != nil {
log . Error ( "Close: %v" , err )
}
} ( )
2019-02-07 12:43:12 +05:30
_ , err = p . Write ( public )
return err
}