100 Zeilen
2.0 KiB
Go
100 Zeilen
2.0 KiB
Go
package saml
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/crewjam/saml"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func initcert(file string, verify func(any) bool) (key any, err error) {
|
|
var blocks []*pem.Block
|
|
if file == "" {
|
|
err = fmt.Errorf("File %s is empty", file)
|
|
return
|
|
}
|
|
blocks, err = loadcerts(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, b := range blocks {
|
|
var key any
|
|
key, err = x509.ParsePKCS8PrivateKey(b.Bytes)
|
|
if err != nil {
|
|
key, err = x509.ParseCertificate(b.Bytes)
|
|
if err != nil {
|
|
log.Warn().AnErr("parsingerror", err).Msgf("could not parse file %s as publickey or as an privatekey", file)
|
|
continue
|
|
}
|
|
}
|
|
if key == nil {
|
|
return nil, fmt.Errorf("Cannot find an Key in %s", file)
|
|
}
|
|
if verify(key) {
|
|
return key, nil
|
|
}
|
|
}
|
|
return nil, errors.New("No key found")
|
|
}
|
|
|
|
func loadcerts(filename string) (blocks []*pem.Block, err error) {
|
|
var file *os.File
|
|
if file, err = os.Open(filename); err != nil {
|
|
return
|
|
}
|
|
var buffer bytes.Buffer
|
|
read, err := buffer.ReadFrom(file)
|
|
log.Debug().Int64("read bytes", read).Err(err).Msgf("Read file %s", filename)
|
|
if err != nil {
|
|
return
|
|
}
|
|
data := buffer.Bytes()
|
|
var block *pem.Block
|
|
for {
|
|
if len(data) == 0 {
|
|
return
|
|
}
|
|
block, data = pem.Decode(data)
|
|
if block != nil {
|
|
blocks = append(blocks, block)
|
|
}
|
|
}
|
|
}
|
|
func empty(data []string) bool {
|
|
for _, t := range data {
|
|
if t == "" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func jwttoken(claim jwt.Claims, privatekey any) (string, error) {
|
|
token := jwt.NewWithClaims(
|
|
jwt.SigningMethodPS512,
|
|
claim,
|
|
)
|
|
return token.SignedString(privatekey)
|
|
}
|
|
|
|
func attributeStatementstomap(a []saml.AttributeStatement) map[string][]string {
|
|
var output = map[string][]string{}
|
|
for _, b := range a {
|
|
for _, c := range b.Attributes {
|
|
if _, ok := output[c.FriendlyName]; !ok {
|
|
output[c.FriendlyName] = []string{}
|
|
}
|
|
for _, d := range c.Values {
|
|
output[c.FriendlyName] = append(output[c.FriendlyName], d.Value)
|
|
}
|
|
}
|
|
}
|
|
return output
|
|
}
|