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 ssh certificate support #12281

Merged
merged 47 commits into from
Oct 11, 2020
Merged
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
60fb3ed
Add ssh certificate support
42wim Jul 20, 2020
2dcb3f8
Add ssh certificate support to builtin ssh
42wim Jul 21, 2020
4cacc44
Write trusted-user-ca-keys.pem based on configuration
42wim Jul 22, 2020
3e928d0
Update app.example.ini
42wim Jul 22, 2020
8d9989a
Update templates/user/settings/keys_principal.tmpl
42wim Jul 23, 2020
d5e5a40
Remove unused locale string
42wim Jul 26, 2020
cd27073
Update options/locale/locale_en-US.ini
42wim Jul 26, 2020
0ade115
Update options/locale/locale_en-US.ini
42wim Jul 26, 2020
8defaaf
Update models/ssh_key.go
42wim Jul 26, 2020
2f10d27
Add missing creation of SSH.Rootpath
42wim Jul 26, 2020
3a198e4
Update cheatsheet, example and locale strings
42wim Jul 26, 2020
1d0dea8
Update models/ssh_key.go
42wim Jul 28, 2020
3e39a5c
Update models/ssh_key.go
42wim Jul 28, 2020
63b6bc9
Update models/ssh_key.go
42wim Jul 28, 2020
c27e664
Update models/ssh_key.go
42wim Jul 28, 2020
aedeac0
Update models/ssh_key.go
zeripath Jul 28, 2020
8f492ff
Optimizations based on feedback
42wim Jul 28, 2020
eacedf5
Validate CA keys for external sshd
42wim Jul 28, 2020
2e73472
Add filename option and change default filename
42wim Jul 28, 2020
b0ac111
Remove unneeded principalkey functions
42wim Jul 28, 2020
0f88094
Add blank line
42wim Aug 22, 2020
455982a
Apply suggestions from code review
42wim Aug 29, 2020
9ebfffd
Add SSH_AUTHORIZED_PRINCIPALS_ALLOW option
42wim Aug 29, 2020
b63e231
Rewrite principal keys file on user deletion
42wim Aug 29, 2020
6a16067
Merge branch 'master' into certificates
lafriks Aug 29, 2020
6c65bb1
Use correct rewrite method
42wim Aug 29, 2020
aa2c19f
Set correct AuthorizedPrincipalsBackup default setting
42wim Aug 29, 2020
27f64d0
Rewrite principalsfile when adding principals
42wim Aug 29, 2020
86f3af6
Add update authorized_principals option to admin dashboard
42wim Aug 29, 2020
5c03b58
Merge remote-tracking branch 'origin/master' into 42wim-certificates
zeripath Aug 31, 2020
a0d356d
Handle non-primary emails
zeripath Aug 31, 2020
c46bb5f
Add the command actually to the dashboard template
42wim Aug 31, 2020
ce8487a
Update models/ssh_key.go
techknowlogick Sep 5, 2020
bc03f3a
Merge branch 'master' into certificates
techknowlogick Sep 5, 2020
fc5fa28
Merge remote-tracking branch 'origin/master' into 42wim-certificates
zeripath Sep 6, 2020
012dfda
By default do not show principal options unless there are CA keys set…
zeripath Sep 6, 2020
98b8447
allow settings when enabled
techknowlogick Sep 24, 2020
e767b63
Merge branch 'master' into certificates
techknowlogick Sep 27, 2020
d9f8713
Fix typos in TrustedUserCAKeys path
42wim Sep 27, 2020
1e3352d
Allow every CASignatureAlgorithms algorithm
42wim Sep 27, 2020
5f42f3a
Update models/ssh_key.go
42wim Sep 29, 2020
66b99f7
Merge branch 'master' into certificates
42wim Sep 29, 2020
91d0d5b
Fix linting issue
42wim Sep 29, 2020
8711842
Merge branch 'master' into certificates
zeripath Sep 29, 2020
108a65e
Merge branch 'master' into certificates
zeripath Sep 30, 2020
0efcab0
Merge remote-tracking branch 'origin/master' into 42wim-certificates
zeripath Oct 1, 2020
9a896de
Merge branch 'master' into certificates
techknowlogick Oct 11, 2020
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
7 changes: 5 additions & 2 deletions cmd/serv.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,12 @@ func runServ(c *cli.Context) error {
if err != nil {
fail("Internal error", "Failed to check provided key: %v", err)
}
if key.Type == models.KeyTypeDeploy {
switch key.Type {
case models.KeyTypeDeploy:
println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
} else {
case models.KeyTypePrincipal:
println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Gitea does not provide shell access.")
default:
println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
}
println("If this is unexpected, please log in with password and setup Gitea under another user.")
Expand Down
24 changes: 23 additions & 1 deletion custom/conf/app.example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,9 @@ SSH_ROOT_PATH =
; Gitea will create a authorized_keys file by default when it is not using the internal ssh server
; If you intend to use the AuthorizedKeysCommand functionality then you should turn this off.
SSH_CREATE_AUTHORIZED_KEYS_FILE = true
; Gitea will create a authorized_principals file by default when it is not using the internal ssh server
; If you intend to use the AuthorizedPrincipalsCommand functionality then you should turn this off.
SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE = true
; For the built-in SSH server, choose the ciphers to support for SSH connections,
; for system SSH this setting has no effect
SSH_SERVER_CIPHERS = aes128-ctr, aes192-ctr, aes256-ctr, aes128-gcm@openssh.com, arcfour256, arcfour128
Expand All @@ -302,7 +305,26 @@ SSH_KEY_TEST_PATH =
; Path to ssh-keygen, default is 'ssh-keygen' which means the shell is responsible for finding out which one to call.
SSH_KEYGEN_PATH = ssh-keygen
; Enable SSH Authorized Key Backup when rewriting all keys, default is true
SSH_BACKUP_AUTHORIZED_KEYS = true
SSH_AUTHORIZED_KEYS_BACKUP = true
zeripath marked this conversation as resolved.
Show resolved Hide resolved
; Determines which principals to allow
; - empty: if SSH_TRUSTED_USER_CA_KEYS is empty this will default to off, otherwise will default to email, username.
; - off: Do not allow authorized principals
; - email: the principal must match the user's email
; - username: the principal must match the user's username
; - anything: there will be no checking on the content of the principal
SSH_AUTHORIZED_PRINCIPALS_ALLOW = email, username
; Enable SSH Authorized Principals Backup when rewriting all keys, default is true
SSH_AUTHORIZED_PRINCIPALS_BACKUP = true
; Specifies the public keys of certificate authorities that are trusted to sign user certificates for authentication.
42wim marked this conversation as resolved.
Show resolved Hide resolved
; Multiple keys should be comma separated.
; E.g."ssh-<algorithm> <key>". or "ssh-<algorithm> <key1>, ssh-<algorithm> <key2>".
; For more information see "TrustedUserCAKeys" in the sshd config manpages.
SSH_TRUSTED_USER_CA_KEYS =
42wim marked this conversation as resolved.
Show resolved Hide resolved
; Absolute path of the `TrustedUserCaKeys` file gitea will manage.
; Default this `RUN_USER`/.ssh/gitea-trusted-user-ca-keys.pem
; If you're running your own ssh server and you want to use the gitea managed file you'll also need to modify your
; sshd_config to point to this file. The official docker image will automatically work without further configuration.
SSH_TRUSTED_USER_CA_KEYS_FILENAME =
; Enable exposure of SSH clone URL to anonymous visitors, default is false
SSH_EXPOSE_ANONYMOUS = false
; Indicate whether to check minimum key size with corresponding type
Expand Down
2 changes: 2 additions & 0 deletions docker/root/etc/templates/sshd_config
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ HostKey /data/ssh/ssh_host_dsa_key
HostKey /data/ssh/ssh_host_ecdsa_key

AuthorizedKeysFile .ssh/authorized_keys
AuthorizedPrincipalsFile .ssh/authorized_principals
TrustedUserCAKeys /data/.git/ssh/gitea-trusted-user-ca-keys.pem

UseDNS no
AllowAgentForwarding no
Expand Down
5 changes: 5 additions & 0 deletions docs/content/doc/advanced/config-cheat-sheet.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@ Values containing `#` or `;` must be quoted using `` ` `` or `"""`.
- `SSH_PORT`: **22**: SSH port displayed in clone URL.
- `SSH_LISTEN_HOST`: **0.0.0.0**: Listen address for the built-in SSH server.
- `SSH_LISTEN_PORT`: **%(SSH\_PORT)s**: Port for the built-in SSH server.
- `SSH_TRUSTED_USER_CA_KEYS`: **\<empty\>**: Specifies the public keys of certificate authorities that are trusted to sign user certificates for authentication. Multiple keys should be comma separated. E.g.`ssh-<algorithm> <key>` or `ssh-<algorithm> <key1>, ssh-<algorithm> <key2>`. For more information see `TrustedUserCAKeys` in the sshd config man pages. When empty no file will be created and `SSH_AUTHORIZED_PRINCIPALS_ALLOW` will default to `off`.
- `SSH_TRUSTED_USER_CA_KEYS_FILENAME`: **`RUN_USER`/.ssh/gitea-trusted-user-ca-keys.pem**: Absolute path of the `TrustedUserCaKeys` file gitea will manage. If you're running your own ssh server and you want to use the gitea managed file you'll also need to modify your sshd_config to point to this file. The official docker image will automatically work without further configuration.
- `SSH_AUTHORIZED_PRINCIPALS_ALLOW`: **off** or **username, email**: \[off, username, email, anything\]: Specify the principals values that users are allowed to use as principal. When set to `anything` no checks are done on the principal string. When set to `off` authorized principal are not allowed to be set.
- `SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE`: **false/true**: Gitea will create a authorized_principals file by default when it is not using the internal ssh server and `SSH_AUTHORIZED_PRINCIPALS_ALLOW` is not `off`.
- `SSH_AUTHORIZED_PRINCIPALS_BACKUP`: **false/true**: Enable SSH Authorized Principals Backup when rewriting all keys, default is true if `SSH_AUTHORIZED_PRINCIPALS_ALLOW` is not `off`.
- `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures.
- `DISABLE_ROUTER_LOG`: **false**: Mute printing of the router log.
- `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. From 1.11 paths are relative to `CUSTOM_PATH`.
Expand Down
236 changes: 232 additions & 4 deletions models/ssh_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ const (
tplCommentPrefix = `# gitea public key`
tplCommand = "%s --config=%q serv key-%d"
tplPublicKey = tplCommentPrefix + "\n" + `command=%q,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"

authorizedPrincipalsFile = "authorized_principals"
42wim marked this conversation as resolved.
Show resolved Hide resolved
)

var sshOpLocker sync.Mutex
Expand All @@ -52,6 +54,8 @@ const (
KeyTypeUser = iota + 1
// KeyTypeDeploy specifies the deploy key
KeyTypeDeploy
// KeyTypePrincipal specifies the authorized principal key
KeyTypePrincipal
)

// PublicKey represents a user or deploy SSH public key.
Expand Down Expand Up @@ -401,6 +405,9 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
}

for _, key := range keys {
if key.Type == KeyTypePrincipal {
continue
}
if _, err = f.WriteString(key.AuthorizedString()); err != nil {
return err
}
Expand Down Expand Up @@ -571,6 +578,25 @@ func SearchPublicKeyByContent(content string) (*PublicKey, error) {
return searchPublicKeyByContentWithEngine(x, content)
}

func searchPublicKeyByContentExactWithEngine(e Engine, content string) (*PublicKey, error) {
key := new(PublicKey)
has, err := e.
Where("content = ?", content).
Get(key)
if err != nil {
return nil, err
} else if !has {
return nil, ErrKeyNotExist{}
}
return key, nil
}

// SearchPublicKeyByContentExact searches content
// and returns public key found.
func SearchPublicKeyByContentExact(content string) (*PublicKey, error) {
return searchPublicKeyByContentExactWithEngine(x, content)
}

// SearchPublicKey returns a list of public keys matching the provided arguments.
func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5)
Expand All @@ -586,7 +612,7 @@ func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {

// ListPublicKeys returns a list of public keys belongs to given user.
func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
sess := x.Where("owner_id = ?", uid)
sess := x.Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal)
if listOptions.Page != 0 {
sess = listOptions.setSessionPagination(sess)

Expand Down Expand Up @@ -662,6 +688,10 @@ func DeletePublicKey(doer *User, id int64) (err error) {
}
sess.Close()

if key.Type == KeyTypePrincipal {
return RewriteAllPrincipalKeys()
}

return RewriteAllPublicKeys()
}

Expand Down Expand Up @@ -727,11 +757,10 @@ func RegeneratePublicKeys(t io.StringWriter) error {
}

func regeneratePublicKeys(e Engine, t io.StringWriter) error {
err := e.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
if err := e.Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err
})
if err != nil {
}); err != nil {
return err
}

Expand Down Expand Up @@ -1041,3 +1070,202 @@ func SearchDeployKeys(repoID int64, keyID int64, fingerprint string) ([]*DeployK
}
return keys, x.Where(cond).Find(&keys)
}

// __________ .__ .__ .__
// \______ _______|__| ____ ____ |_____________ | | ______
// | ___\_ __ | |/ \_/ ___\| \____ \__ \ | | / ___/
// | | | | \| | | \ \___| | |_> / __ \| |__\___ \
// |____| |__| |__|___| /\___ |__| __(____ |____/____ >
// \/ \/ |__| \/ \/

// AddPrincipalKey adds new principal to database and authorized_principals file.
func AddPrincipalKey(ownerID int64, content string, loginSourceID int64) (*PublicKey, error) {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return nil, err
}

// Principals cannot be duplicated.
has, err := sess.
Where("content = ? AND type = ?", content, KeyTypePrincipal).
Get(new(PublicKey))
if err != nil {
return nil, err
} else if has {
return nil, ErrKeyAlreadyExist{0, "", content}
}

key := &PublicKey{
OwnerID: ownerID,
Name: content,
Content: content,
Mode: AccessModeWrite,
Type: KeyTypePrincipal,
LoginSourceID: loginSourceID,
}
if err = addPrincipalKey(sess, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err)
}

if err = sess.Commit(); err != nil {
return nil, err
}

42wim marked this conversation as resolved.
Show resolved Hide resolved
42wim marked this conversation as resolved.
Show resolved Hide resolved
return key, RewriteAllPrincipalKeys()
}

func addPrincipalKey(e Engine, key *PublicKey) (err error) {
// Save Key representing a principal.
if _, err = e.Insert(key); err != nil {
return err
}

return nil
}

// CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines
func CheckPrincipalKeyString(user *User, content string) (_ string, err error) {
if setting.SSH.Disabled {
return "", ErrSSHDisabled{}
}

content = strings.TrimSpace(content)
if strings.ContainsAny(content, "\r\n") {
return "", errors.New("only a single line with a single principal please")
}

42wim marked this conversation as resolved.
Show resolved Hide resolved
// check all the allowed principals, email, username or anything
// if any matches, return ok
for _, v := range setting.SSH.AuthorizedPrincipalsAllow {
switch v {
case "anything":
return content, nil
case "email":
emails, err := GetEmailAddresses(user.ID)
if err != nil {
return "", err
}
for _, email := range emails {
if !email.IsActivated {
continue
}
if content == email.Email {
return content, nil
}
}

case "username":
if content == user.Name {
return content, nil
}
}
}

return "", fmt.Errorf("didn't match allowed principals: %s", setting.SSH.AuthorizedPrincipalsAllow)
}

// RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again.
// Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
// outside any session scope independently.
func RewriteAllPrincipalKeys() error {
return rewriteAllPrincipalKeys(x)
}

func rewriteAllPrincipalKeys(e Engine) error {
// Don't rewrite key if internal server
if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedPrincipalsFile {
return nil
}

sshOpLocker.Lock()
defer sshOpLocker.Unlock()

if setting.SSH.RootPath != "" {
// First of ensure that the RootPath is present, and if not make it with 0700 permissions
// This of course doesn't guarantee that this is the right directory for authorized_keys
// but at least if it's supposed to be this directory and it doesn't exist and we're the
// right user it will at least be created properly.
err := os.MkdirAll(setting.SSH.RootPath, 0700)
if err != nil {
log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
return err
}
}

fPath := filepath.Join(setting.SSH.RootPath, authorizedPrincipalsFile)
tmpPath := fPath + ".tmp"
t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer func() {
t.Close()
os.Remove(tmpPath)
}()

if setting.SSH.AuthorizedPrincipalsBackup && com.IsExist(fPath) {
bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
if err = com.Copy(fPath, bakPath); err != nil {
return err
}
}

if err := regeneratePrincipalKeys(e, t); err != nil {
return err
}

t.Close()
return os.Rename(tmpPath, fPath)
}

// ListPrincipalKeys returns a list of principals belongs to given user.
func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
sess := x.Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal)
if listOptions.Page != 0 {
sess = listOptions.setSessionPagination(sess)

keys := make([]*PublicKey, 0, listOptions.PageSize)
return keys, sess.Find(&keys)
}

keys := make([]*PublicKey, 0, 5)
return keys, sess.Find(&keys)
}

// RegeneratePrincipalKeys regenerates the authorized_principals file
func RegeneratePrincipalKeys(t io.StringWriter) error {
return regeneratePrincipalKeys(x, t)
}

func regeneratePrincipalKeys(e Engine, t io.StringWriter) error {
if err := e.Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err
}); err != nil {
return err
}
zeripath marked this conversation as resolved.
Show resolved Hide resolved

fPath := filepath.Join(setting.SSH.RootPath, authorizedPrincipalsFile)
if com.IsExist(fPath) {
f, err := os.Open(fPath)
if err != nil {
return err
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, tplCommentPrefix) {
scanner.Scan()
continue
}
_, err = t.WriteString(line + "\n")
if err != nil {
f.Close()
return err
}
}
f.Close()
}
return nil
}
4 changes: 4 additions & 0 deletions models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -1254,6 +1254,10 @@ func deleteUser(e *xorm.Session, u *User) error {
if err != nil {
return err
}
err = rewriteAllPrincipalKeys(e)
if err != nil {
return err
}
// ***** END: PublicKey *****

// ***** START: GPGPublicKey *****
Expand Down
Loading