Compare commits

...

19 Commits

Author SHA1 Message Date
wpetit 51bdf4d015 fix: variable bad scoping
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2024-01-05 16:17:39 +01:00
wpetit 635f170762 feat: only show warn in log when peer id is already used
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-05 14:16:15 +01:00
wpetit 834f6346dd chore(ci): remove superfluous build dependency
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2024-01-05 12:38:41 +01:00
wpetit 34adfb3e87 feat: log more information on authentication errors
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-05 12:31:33 +01:00
wpetit b28a87cc5d fix(keygen): correctly load token for validation
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-05 11:12:27 +01:00
wpetit db06098fdd fix: generate non encrypted key when passphrase is empty
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-05 09:55:15 +01:00
wpetit 20c4bef161 feat(middleware): log more informations on authentification errors
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-04 22:54:03 +01:00
wpetit e8e484a7ff feat(keygen): add -verify-token command 2024-01-04 16:21:40 +01:00
wpetit 72f6073e47 feat: use armored gpg signature
Cadoles/go-http-peering/pipeline/head There was a failure building this commit Details
2024-01-04 11:35:30 +01:00
wpetit 1bf8d755ed fix: load dek header-less private keys
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2023-11-21 14:13:32 +01:00
wpetit ced46bf6eb fix: use detached signature for release
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2023-11-21 12:21:42 +01:00
wpetit cf8f026574 feat: sign released binaries
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2023-10-19 15:44:01 +02:00
wpetit 891cfa7540 Fix panic when peer is not yet associated
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2023-09-04 21:08:46 -06:00
wpetit d38f0be312 Use GOMIPS=softfloat by default and do not use UPX on mips targeted binaries
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2022-09-16 14:47:40 +02:00
wpetit 5be381d2b7 Disable upx compression for mips arch
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2022-09-12 18:22:49 +02:00
wpetit 7cff0e3f91 Add mipsle target
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2022-09-12 17:47:51 +02:00
wpetit f872a68906 Return wrapped errors 2022-09-12 17:46:59 +02:00
wpetit 6257330dd3 Use jenkins main library version
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2022-09-05 14:40:36 +02:00
wpetit 9c26b79769 Refactor Makefile
Cadoles/go-http-peering/pipeline/head This commit is unstable Details
2022-09-05 12:54:33 +02:00
21 changed files with 298 additions and 155 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

20
Jenkinsfile vendored
View File

@ -1,4 +1,4 @@
@Library('cadoles@gitea-release') _
@Library('cadoles') _
pipeline {
agent {
@ -9,15 +9,19 @@ pipeline {
}
stages {
stage('Release') {
stage('Lint') {
steps {
script {
sh 'ARCH_TARGETS="amd64 arm arm64" 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
])
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
sh 'make lint'
}
}
}
}
stage('Test') {
steps {
script {
sh 'make test'
}
}
}

View File

@ -1,35 +1,56 @@
test:
SHELL := /bin/bash
test: go-test keygen-test
go-test:
go clean -testcache
go test -cover -v ./...
watch:
modd
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 )
deps:
GO111MODULE=off go get -u golang.org/x/tools/cmd/godoc
GO111MODULE=off go get -u github.com/cortesi/modd/cmd/modd
GO111MODULE=off go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
GO111MODULE=off go get -u github.com/lmika/goseq
.env:
cp .env.dist .env
tidy:
go mod tidy
lint:
golangci-lint run --tests=false --enable-all
sequence-diagram: sd-advertise sd-update sd-ping
sd-%:
goseq doc/sequence-diagram/$*.seq > doc/sequence-diagram/$*.svg
doc:
@echo "open your browser to http://localhost:6060/pkg/forge.cadoles.com/Cadoles/go-http-peering to see the documentation"
godoc -http=:6060
go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.49.0 run --tests=false --enable-all
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
keygen-test: tools/bash_unit/bin/bash_unit
tools/bash_unit/bin/bash_unit misc/bash_unit/keygen_test.sh
tools/bash_unit/bin/bash_unit:
mkdir -p tools/bash_unit/bin
cd tools/bash_unit/bin && bash <(curl -s https://raw.githubusercontent.com/pgrange/bash_unit/master/install.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

@ -5,11 +5,11 @@ import (
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"errors"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
peering "forge.cadoles.com/Cadoles/go-http-peering"
"forge.cadoles.com/Cadoles/go-http-peering/crypto"
@ -52,7 +52,7 @@ func (c *Client) Advertise(attrs peering.PeerAttributes) error {
case http.StatusConflict:
return peering.ErrPeerExists
default:
return ErrUnexpectedResponse
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode)
}
}
@ -76,7 +76,7 @@ func (c *Client) UpdateAttributes(attrs peering.PeerAttributes) error {
case http.StatusForbidden:
return ErrRejected
default:
return ErrUnexpectedResponse
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode)
}
}
@ -96,7 +96,7 @@ func (c *Client) Ping() error {
case http.StatusForbidden:
return ErrRejected
default:
return ErrUnexpectedResponse
return errors.Wrapf(ErrUnexpectedResponse, "unexpected http status code '%d'", res.StatusCode)
}
}

View File

@ -4,20 +4,21 @@ import (
"fmt"
"forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
)
func createKey() {
passphrase, err := getPassphrase()
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
key, err := crypto.CreateRSAKey(keySize)
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
privatePEM, err := crypto.EncodePrivateKeyToEncryptedPEM(key, passphrase)
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
fmt.Print(string(privatePEM))
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
"forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
peering "forge.cadoles.com/Cadoles/go-http-peering"
)
@ -11,11 +12,11 @@ import (
func createToken() {
privateKey, err := loadPrivateKey()
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
token, err := crypto.CreateServerToken(privateKey, tokenIssuer, peering.PeerID(tokenPeerID))
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
fmt.Println(token)
}

View File

@ -4,16 +4,17 @@ import (
"fmt"
"forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
)
func getPublicKey() {
privateKey, err := loadPrivateKey()
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
publicPEM, err := crypto.EncodePublicKeyToPEM(privateKey.Public())
if err != nil {
handleError(err)
handleError(errors.WithStack(err))
}
fmt.Print(string(publicPEM))
}

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,17 +2,15 @@ package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"syscall"
"forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh/terminal"
)
@ -29,14 +27,14 @@ func askPassphrase() ([]byte, error) {
fmt.Print("Passphrase: ")
passphrase, err := terminal.ReadPassword(syscall.Stdin)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
fmt.Println()
fmt.Print("Confirm passphrase: ")
passphraseConfirmation, err := terminal.ReadPassword(syscall.Stdin)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
fmt.Println()
@ -47,50 +45,43 @@ 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, 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")
}
pem, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
passphrase, err := getPassphrase()
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
privateKey, err := crypto.DecodePEMEncryptedPrivateKey(pem, passphrase)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
return privateKey, nil
}
func loadToken() (string, error) {
if tokenFile == "" {
return "", errors.New("you must specify a token file to load")
}
token, err := os.ReadFile(tokenFile)
if err != nil {
return "", errors.WithStack(err)
}
return strings.TrimSpace(string(token)), nil
}
func handleError(err error) {
if !debug {
fmt.Println(err)
fmt.Printf("%+v\n", errors.WithStack(err))
} else {
panic(err)
panic(fmt.Sprintf("%+v", errors.WithStack(err)))
}
os.Exit(1)
}

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(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

@ -6,15 +6,16 @@ import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) {
pub, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
data := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
@ -28,27 +29,23 @@ func DecodePEMToPublicKey(pem []byte) (crypto.PublicKey, error) {
}
func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) {
var err error
var (
rawKey interface{}
err error
)
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("invalid PEM block")
if len(passphrase) == 0 {
rawKey, err = ssh.ParseRawPrivateKey(key)
} else {
rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase(key, passphrase)
}
decryptedBlock, err := x509.DecryptPEMBlock(block, passphrase)
if err != nil {
return nil, err
}
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(decryptedBlock); err != nil {
return nil, err
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")
}
@ -56,21 +53,21 @@ func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKe
}
func EncodePrivateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) {
if passphrase == nil {
return nil, errors.New("passphrase cannot be empty")
}
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, err
if len(passphrase) != 0 {
encryptedBlock, err := x509.EncryptPEMBlock(
rand.Reader, block.Type,
block.Bytes, passphrase, x509.PEMCipherAES256,
)
if err != nil {
return nil, errors.WithStack(err)
}
block = encryptedBlock
}
return pem.EncodeToMemory(block), nil

View File

@ -8,12 +8,13 @@ import (
peering "forge.cadoles.com/Cadoles/go-http-peering"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
func CreateRSAKey(bits int) (*rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, err
return nil, errors.WithStack(err)
}
return key, nil
}
@ -28,7 +29,7 @@ func CreateServerToken(privateKey *rsa.PrivateKey, issuer string, peerID peering
})
tokenStr, err := token.SignedString(privateKey)
if err != nil {
return "", err
return "", errors.WithStack(err)
}
return tokenStr, nil
}

13
go.mod
View File

@ -1,12 +1,17 @@
module forge.cadoles.com/Cadoles/go-http-peering
require (
github.com/davecgh/go-spew v1.1.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-chi/chi v3.3.3+incompatible
github.com/pborman/uuid v1.2.0
golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 // indirect
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
)
go 1.13
require (
github.com/google/uuid v1.0.0 // indirect
github.com/pkg/errors v0.9.1
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 // indirect
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect
)
go 1.18

14
go.sum
View File

@ -1,5 +1,3 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/go-chi/chi v3.3.3+incompatible h1:KHkmBEMNkwKuK4FdQL7N2wOeB9jnIx7jR5wsuSBEFI8=
@ -8,7 +6,11 @@ github.com/google/uuid v1.0.0 h1:b4Gk+7WdP/d3HZH8EJsZpvV7EtDOgaZLtnaNGIu1adA=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2 h1:NwxKRvbkH5MsNkvOtPZi3/3kmI8CAzs3mtv+GLQMkNo=
golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 h1:Y/gsMcFOcR+6S6f3YeMKl5g+dZMEWqcz5Czj/GWYbkM=
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 h1:v6hYoSR9T5oet+pMXwUWkbiVqx/63mlHjefrHmxwfeY=
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc=
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=

View File

@ -0,0 +1,49 @@
#!/bin/bash
KEYGEN_BIN=${KEYGEN_BIN:-go run ../../cmd/keygen}
test_create_key_without_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key without passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE= $KEYGEN_BIN -create-key > "${key_path}"
}
test_create_key_with_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key with passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-key > "${key_path}"
}
test_verify_token_without_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key without passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE= $KEYGEN_BIN -create-key > "${key_path}"
# Generate a new token
local token_path="${workspace}/token.jwt"
KEY_PASSPHRASE= $KEYGEN_BIN -create-token -key "${key_path}" > "${token_path}"
# Verify token
KEY_PASSPHRASE= $KEYGEN_BIN -verify-token -key "${key_path}" -token "${token_path}" 1>/dev/null
}
test_verify_token_with_passphrase() {
local workspace=$(mktemp -d)
# Generate a new private key with passphrase
local key_path="${workspace}/private.key"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-key > "${key_path}"
# Generate a new token
local token_path="${workspace}/token.jwt"
KEY_PASSPHRASE=foobar $KEYGEN_BIN -create-token -key "${key_path}" > "${token_path}"
# Verify token
KEY_PASSPHRASE=foobar $KEYGEN_BIN -verify-token -key "${key_path}" -token "${token_path}" 1>/dev/null
}

View File

@ -1,5 +1,5 @@
FROM golang:1.19
FROM reg.cadoles.com/proxy_cache/library/golang:1.21
RUN apt-get update && apt-get install -y make upx-ucl curl ca-certificates bash jq
RUN apt-get update && apt-get install -y make curl ca-certificates bash jq
RUN curl -k https://forge.cadoles.com/Cadoles/Jenkins/raw/branch/master/resources/com/cadoles/common/add-letsencrypt-ca.sh | bash

View File

@ -2,8 +2,4 @@
!vendor/**.go {
prep: make test
prep: make bin/keygen
}
doc/sequence-diagram/*.seq {
prep: make sequence-diagram
}

View File

@ -3,7 +3,9 @@
set -eo pipefail
OS_TARGETS=(linux)
ARCH_TARGETS=${ARCH_TARGETS:-amd64}
ARCH_TARGETS=${ARCH_TARGETS:-amd64 mipsle}
export GOMIPS=softfloat
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
@ -29,10 +31,16 @@ function build {
-o "$destdir/$name" \
"$srcdir"
if [ ! -z "$(which upx)" ]; then
# Disable UPX compression for MIPS archs
# See https://github.com/upx/upx/issues/339
if [ ! -z "$(which upx)" ] && [[ ! "$arch" =~ "mips" ]]; then
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

@ -3,12 +3,12 @@ package server
import (
"crypto/rsa"
"encoding/json"
"errors"
"net/http"
"time"
peering "forge.cadoles.com/Cadoles/go-http-peering"
peeringCrypto "forge.cadoles.com/Cadoles/go-http-peering/crypto"
"github.com/pkg/errors"
)
var (
@ -34,7 +34,7 @@ func AdvertiseHandler(store peering.Store, key *rsa.PublicKey, funcs ...OptionFu
serverClaims, err := assertServerToken(key, serverToken)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.Wrapf(err, "could not validate token '%s'", serverToken))
sendError(w, http.StatusUnauthorized)
return
}
@ -43,54 +43,53 @@ func AdvertiseHandler(store peering.Store, key *rsa.PublicKey, funcs ...OptionFu
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(advertising); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest)
return
}
if _, err := peeringCrypto.DecodePEMToPublicKey(advertising.PublicKey); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, ErrInvalidAdvertisingRequest)
return
}
peer, err := store.Get(serverClaims.PeerID)
_, err = store.Get(serverClaims.PeerID)
if err == nil {
logger.Printf("[ERROR] %s", ErrPeerIDAlreadyInUse)
logger.Printf("[WARN] %s", errors.WithStack(ErrPeerIDAlreadyInUse))
options.ErrorHandler(w, r, ErrPeerIDAlreadyInUse)
return
}
if err != peering.ErrPeerNotFound {
logger.Printf("[ERROR] %s", err)
if !errors.Is(err, peering.ErrPeerNotFound) {
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
attrs := filterAttributes(options.PeerAttributes, advertising.Attributes)
peer, err = store.Create(serverClaims.PeerID, attrs)
peer, err := store.Create(serverClaims.PeerID, attrs)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
if err := store.UpdatePublicKey(peer.ID, advertising.PublicKey); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
@ -117,39 +116,39 @@ func UpdateHandler(store peering.Store, funcs ...OptionFunc) http.HandlerFunc {
peerID, err := GetPeerID(r)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
peer, err := store.Get(peerID)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
if peer == nil {
logger.Printf("[ERROR] %s", ErrUnauthorized)
logger.Printf("[ERROR] %+v", errors.WithStack(ErrUnauthorized))
options.ErrorHandler(w, r, ErrUnauthorized)
return
}
if peer.Status == peering.StatusRejected {
logger.Printf("[ERROR] %s", ErrPeerRejected)
logger.Printf("[ERROR] %+v", errors.WithStack(ErrPeerRejected))
options.ErrorHandler(w, r, ErrPeerRejected)
return
}
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
attrs := filterAttributes(options.PeerAttributes, update.Attributes)
if err := store.UpdateAttributes(peer.ID, attrs); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
@ -176,32 +175,32 @@ func PingHandler(store peering.Store, funcs ...OptionFunc) http.HandlerFunc {
peerID, err := GetPeerID(r)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
peer, err := store.Get(peerID)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}
if peer == nil {
logger.Printf("[ERROR] %s", ErrUnauthorized)
logger.Printf("[ERROR] %+v", errors.WithStack(ErrUnauthorized))
options.ErrorHandler(w, r, ErrUnauthorized)
return
}
if peer.Status == peering.StatusRejected {
logger.Printf("[ERROR] %s", ErrPeerRejected)
logger.Printf("[ERROR] %+v", errors.WithStack(ErrPeerRejected))
options.ErrorHandler(w, r, ErrPeerRejected)
return
}
if err := store.UpdateLastContact(peer.ID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
options.ErrorHandler(w, r, err)
return
}

View File

@ -5,17 +5,16 @@ import (
"context"
"crypto/rsa"
"crypto/sha256"
"errors"
"io"
"io/ioutil"
"net/http"
"time"
peeringCrypto "forge.cadoles.com/Cadoles/go-http-peering/crypto"
peering "forge.cadoles.com/Cadoles/go-http-peering"
jwt "github.com/dgrijalva/jwt-go"
"net/http"
"github.com/pkg/errors"
)
const (
@ -38,7 +37,6 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
middleware := func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
serverToken := r.Header.Get(ServerTokenHeader)
if serverToken == "" {
sendError(w, http.StatusUnauthorized)
@ -53,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", errors.WithStack(err))
sendError(w, http.StatusUnauthorized)
return
}
@ -66,20 +64,21 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
options.IgnoredClientTokenErrors...,
)
if err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(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", errors.WithStack(err))
sendError(w, http.StatusInternalServerError)
return
}
sendError(w, http.StatusUnauthorized)
return
case ErrPeerRejected:
if err := store.UpdateLastContact(serverClaims.PeerID, r.RemoteAddr, time.Now()); err != nil {
logger.Printf("[ERROR] %s", err)
logger.Printf("[ERROR] %+v", errors.WithStack(err))
sendError(w, http.StatusInternalServerError)
return
}
@ -93,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", errors.WithStack(err))
sendError(w, http.StatusInternalServerError)
return
}
if !match {
logger.Printf("[ERROR] %s", ErrInvalidChecksum)
logger.Printf("[ERROR] %+v", errors.WithStack(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", errors.WithStack(err))
sendError(w, http.StatusInternalServerError)
return
}
@ -115,7 +114,6 @@ func Authenticate(store peering.Store, key *rsa.PublicKey, funcs ...OptionFunc)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
@ -185,7 +183,7 @@ func assertClientToken(peerID peering.PeerID, store peering.Store, clientToken s
if ok {
for _, c := range ignoredValidationErrors {
if validationError.Errors&c != 0 {
logger.Printf("ignoring token validation error: '%s'", validationError.Inner)
logger.Printf("ignoring token validation error: '%+v'", errors.WithStack(validationError.Inner))
return getPeeringClaims(token)
}
}