6 Commits

Author SHA1 Message Date
052c690509 feat(middleware): log more informations on authentification errors
Some checks failed
Cadoles/go-http-peering/pipeline/head There was a failure building this commit
2024-01-04 16:22:13 +01:00
e8e484a7ff feat(keygen): add -verify-token command 2024-01-04 16:21:40 +01:00
72f6073e47 feat: use armored gpg signature
Some checks failed
Cadoles/go-http-peering/pipeline/head There was a failure building this commit
2024-01-04 11:35:30 +01:00
1bf8d755ed fix: load dek header-less private keys
Some checks reported warnings
Cadoles/go-http-peering/pipeline/head This commit is unstable
2023-11-21 14:13:32 +01:00
ced46bf6eb fix: use detached signature for release
Some checks reported warnings
Cadoles/go-http-peering/pipeline/head This commit is unstable
2023-11-21 12:21:42 +01:00
cf8f026574 feat: sign released binaries
Some checks reported warnings
Cadoles/go-http-peering/pipeline/head This commit is unstable
2023-10-19 15:44:01 +02:00
10 changed files with 135 additions and 58 deletions

2
.env.dist Normal file
View File

@ -0,0 +1,2 @@
GPG_SIGNING_KEY=
ARCH_TARGETS='amd64 arm arm64 386'

5
.gitignore vendored
View File

@ -3,4 +3,7 @@
/bin
/testdata
/release
/out
/out
/.mktools
/tools
/.env

13
Jenkinsfile vendored
View File

@ -25,19 +25,6 @@ pipeline {
}
}
}
stage('Release') {
steps {
script {
sh 'make tidy'
sh 'ARCH_TARGETS="amd64 arm arm64 mipsle" make release'
def attachments = sh(returnStdout: true, script: 'find release -maxdepth 1 -type f').split(' ')
gitea.release('forge-jenkins', 'Cadoles', 'go-http-peering', [
'attachments': attachments
])
}
}
}
}
post {

View File

@ -1,3 +1,5 @@
SHELL := /bin/bash
test:
go clean -testcache
go test -cover -v ./...
@ -5,8 +7,11 @@ test:
watch:
go run -mod=readonly github.com/cortesi/modd/cmd/modd@latest
release:
script/release
release: tidy .env
( set -o allexport && source .env && set +o allexport && script/release )
.env:
cp .env.dist .env
tidy:
go mod tidy
@ -17,4 +22,26 @@ lint:
bin/keygen:
CGO_ENABLED=0 go build -o bin/keygen ./cmd/keygen
.PHONY: test lint doc sequence-diagram bin/keygen release
.PHONY: test lint doc sequence-diagram bin/keygen release
gitea-release: .mktools tools/gitea-release/bin/gitea-release.sh release
GITEA_RELEASE_PROJECT="go-http-peering" \
GITEA_RELEASE_ORG="Cadoles" \
GITEA_RELEASE_BASE_URL="https://forge.cadoles.com" \
GITEA_RELEASE_VERSION="$(MKT_PROJECT_VERSION)" \
GITEA_RELEASE_NAME="$(MKT_PROJECT_VERSION)" \
GITEA_RELEASE_COMMITISH_TARGET="$(GIT_VERSION)" \
GITEA_RELEASE_IS_DRAFT="false" \
GITEA_RELEASE_BODY="" \
GITEA_RELEASE_ATTACHMENTS="$$(find release -type f -name '*.tar.gz')" \
tools/gitea-release/bin/gitea-release.sh
.PHONY: mktools
mktools:
rm -rf .mktools
curl -k -q https://forge.cadoles.com/Cadoles/mktools/raw/branch/master/install.sh | $(SHELL)
.mktools:
$(MAKE) mktools
-include .mktools/*.mk

View File

@ -11,8 +11,10 @@ var (
createKeyCmd = false
getPublicKeyCmd = false
createTokenCmd = false
verifyTokenCmd = false
debug = false
keyFile string
tokenFile string
tokenIssuer string
tokenPeerID = uuid.New()
keySize = 2048
@ -28,12 +30,17 @@ func init() {
&createTokenCmd, "create-token", createTokenCmd,
"Create a new signed authentication token",
)
flag.BoolVar(
&verifyTokenCmd, "verify-token", verifyTokenCmd,
"Verify a token generated with the given key",
)
flag.BoolVar(
&getPublicKeyCmd, "get-public-key", getPublicKeyCmd,
"Get the PEM encoded public key associated with the private key",
)
flag.BoolVar(&debug, "debug", debug, "Debug mode")
flag.StringVar(&keyFile, "key", keyFile, "Path to the encrypted PEM encoded key")
flag.StringVar(&tokenFile, "token", tokenFile, "Path to the token to verify")
flag.StringVar(&tokenIssuer, "token-issuer", tokenIssuer, "Token issuer")
flag.StringVar(&tokenPeerID, "token-peer-id", tokenPeerID, "Token peer ID")
flag.IntVar(&keySize, "key-size", keySize, "Size of the private key")
@ -48,6 +55,8 @@ func main() {
getPublicKey()
case createTokenCmd:
createToken()
case verifyTokenCmd:
verifyToken()
default:
flag.Usage()
}

View File

@ -2,10 +2,7 @@ package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
@ -47,25 +44,6 @@ func askPassphrase() ([]byte, error) {
return passphrase, nil
}
func privateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) {
if passphrase == nil {
return nil, errors.New("passphrase cannot be empty")
}
// Convert it to pem
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
block, err := x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, passphrase, x509.PEMCipherAES256)
if err != nil {
return nil, errors.WithStack(err)
}
return pem.EncodeToMemory(block), nil
}
func loadPrivateKey() (*rsa.PrivateKey, error) {
if keyFile == "" {
return nil, errors.New("you must specify a key file to load")
@ -85,6 +63,19 @@ func loadPrivateKey() (*rsa.PrivateKey, error) {
return privateKey, nil
}
func loadToken() ([]byte, error) {
if tokenFile == "" {
return nil, errors.New("you must specify a token file to load")
}
token, err := os.ReadFile(tokenFile)
if err != nil {
return nil, errors.WithStack(err)
}
return token, nil
}
func handleError(err error) {
if !debug {
fmt.Printf("%+v\n", errors.WithStack(err))

View File

@ -0,0 +1,55 @@
package main
import (
"encoding/json"
"fmt"
peering "forge.cadoles.com/Cadoles/go-http-peering"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
func verifyToken() {
rawToken, err := loadToken()
if err != nil {
handleError(errors.WithStack(err))
}
privateKey, err := loadPrivateKey()
if err != nil {
handleError(errors.WithStack(err))
}
fn := func(token *jwt.Token) (interface{}, error) {
return &privateKey.PublicKey, nil
}
token, err := jwt.ParseWithClaims(string(rawToken), &peering.ServerTokenClaims{}, fn)
if err != nil {
validationError, ok := err.(*jwt.ValidationError)
if ok {
handleError(errors.WithStack(validationError.Inner))
}
handleError(errors.WithStack(err))
}
if !token.Valid {
handleError(errors.New("token is invalid"))
}
claims, ok := token.Claims.(*peering.ServerTokenClaims)
if !ok {
handleError(errors.New("unexpected token claims"))
}
data, err := json.MarshalIndent(claims, "", " ")
if err != nil {
handleError(errors.WithStack(err))
}
fmt.Println("Token OK.")
fmt.Println("Claims:")
fmt.Println(string(data))
}

View File

@ -9,6 +9,7 @@ import (
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) {
@ -28,25 +29,23 @@ func DecodePEMToPublicKey(pem []byte) (crypto.PublicKey, error) {
}
func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) {
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("invalid PEM block")
}
var (
rawKey interface{}
err error
)
decryptedBlock, err := x509.DecryptPEMBlock(block, passphrase)
if len(passphrase) == 0 {
rawKey, err = ssh.ParseRawPrivateKey(key)
} else {
rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase(key, passphrase)
}
if err != nil {
return nil, errors.WithStack(err)
}
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(decryptedBlock); err != nil {
return nil, errors.WithStack(err)
}
var privateKey *rsa.PrivateKey
var ok bool
if privateKey, ok = parsedKey.(*rsa.PrivateKey); !ok {
if privateKey, ok = rawKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("invalid RSA private key")
}

View File

@ -37,6 +37,10 @@ function build {
upx --best "$destdir/$name"
fi
if [ ! -z "${GPG_SIGNING_KEY}" ]; then
echo "signing '$destdir/$name' with gpg key '$GPG_SIGNING_KEY'..."
gpg --sign --default-key "${GPG_SIGNING_KEY}" --armor --detach-sign --output "$destdir/$name.sig" "$destdir/$name"
fi
}
function copy {

View File

@ -51,7 +51,7 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
serverClaims, err := assertServerToken(key, serverToken)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
sendError(w, http.StatusUnauthorized)
return
}
@ -64,13 +64,13 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
options.IgnoredClientTokenErrors...,
)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
switch err {
case peering.ErrPeerNotFound:
sendError(w, http.StatusUnauthorized)
case ErrNotPeered:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
sendError(w, http.StatusInternalServerError)
return
}
@ -78,7 +78,7 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
return
case ErrPeerRejected:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
sendError(w, http.StatusInternalServerError)
return
}
@ -92,19 +92,19 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
match, body, err := assertBodySum(r.Body, clientClaims.BodySum)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
sendError(w, http.StatusInternalServerError)
return
}
if !match {
logger.Printf("[ERROR] %s", ErrInvalidChecksum)
logger.Printf("[ERROR] %+v", ErrInvalidChecksum)
sendError(w, http.StatusBadRequest)
return
}
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", err)
sendError(w, http.StatusInternalServerError)
return
}