go lint and vet

This commit is contained in:
Matt Drollette
2017-10-15 14:14:50 -05:00
parent 529c4a084f
commit 2b56d44114
13 changed files with 164 additions and 214 deletions

View File

@@ -1,15 +0,0 @@
FROM golang:1.9-alpine3.6
# Copy the local package files to the container's workspace.
ADD . /go/src/github.com/martin61/i2p-tools
# Make project CWD
WORKDIR /go/src/github.com/martin61/i2p-tools
# Build everything
RUN apk add --no-cache --update git && \
go get && \
apk del git
RUN go build -o /i2p-tools
CMD ["/i2p-tools"]

View File

@@ -1,24 +0,0 @@
NAME = i2p-tools
DOCKER_IMAGE = MDrollette/$(NAME)
all: build
.build: .
docker pull golang:1.4.2
docker pull progrium/busybox:latest
docker build -t $(NAME) .
docker inspect -f '{{.Id}}' $(NAME) > .build
build: .build
release: build
cd release && docker run --rm --entrypoint /bin/sh $(NAME) -c 'tar cf - /$(NAME)' | tar xf -
docker build --rm -t $(DOCKER_IMAGE) release
push: release
docker push $(DOCKER_IMAGE)
clean:
rm -f .build release/i2p-tools
.PHONY: push release build all clean

View File

@@ -8,9 +8,8 @@ This tool provides a secure and efficient reseed server for the I2P network. The
If you have go installed you can download, build, and install this tool with `go get`
```
export GOPATH=$HOME/go; mkdir $GOPATH; cd $GOPATH
go get github.com/martin61/i2p-tools
bin/i2p-tools -h
go get github.com/MDrollette/i2p-tools
i2p-tools -h
```
## Usage
@@ -18,13 +17,13 @@ bin/i2p-tools -h
### Locally behind a webserver (reverse proxy setup), preferred:
```
GOPATH=$HOME/go; cd $GOPATH; bin/i2p-tools reseed --signer=you@mail.i2p --netdb=/home/i2p/.i2p/netDb --port=8443 --ip=127.0.0.1 --trustProxy
i2p-tools reseed --signer=you@mail.i2p --netdb=/home/i2p/.i2p/netDb --port=8443 --ip=127.0.0.1 --trustProxy
```
### Without a webserver, standalone with TLS support
```
GOPATH=$HOME/go; cd $GOPATH; bin/i2p-tools reseed --signer=you@mail.i2p --netdb=/home/i2p/.i2p/netDb --tlsHost=your-domain.tld
i2p-tools reseed --signer=you@mail.i2p --netdb=/home/i2p/.i2p/netDb --tlsHost=your-domain.tld
```
If this is your first time running a reseed server (ie. you don't have any existing keys),

View File

@@ -25,16 +25,16 @@ func NewKeygenCommand() cli.Command {
}
func keygenAction(c *cli.Context) {
signerId := c.String("signer")
signerID := c.String("signer")
tlsHost := c.String("tlsHost")
if signerId == "" && tlsHost == "" {
if signerID == "" && tlsHost == "" {
fmt.Println("You must specify either --tlsHost or --signer")
return
}
if signerId != "" {
if err := createSigningCertificate(signerId); nil != err {
if signerID != "" {
if err := createSigningCertificate(signerID); nil != err {
fmt.Println(err)
return
}

View File

@@ -97,8 +97,8 @@ func reseedAction(c *cli.Context) {
return
}
signerId := c.String("signer")
if signerId == "" {
signerID := c.String("signer")
if signerID == "" {
fmt.Println("--signer is required")
return
}
@@ -132,13 +132,13 @@ func reseedAction(c *cli.Context) {
}
signerKey := c.String("key")
// if no key is specified, default to the signerId.pem in the current dir
// if no key is specified, default to the signerID.pem in the current dir
if signerKey == "" {
signerKey = signerFile(signerId) + ".pem"
signerKey = signerFile(signerID) + ".pem"
}
// load our signing privKey
privKey, err := getOrNewSigningCert(&signerKey, signerId)
privKey, err := getOrNewSigningCert(&signerKey, signerID)
if nil != err {
log.Fatalln(err)
}
@@ -149,7 +149,7 @@ func reseedAction(c *cli.Context) {
// create a reseeder
reseeder := reseed.NewReseeder(netdb)
reseeder.SigningKey = privKey
reseeder.SignerId = []byte(signerId)
reseeder.SignerID = []byte(signerID)
reseeder.NumRi = c.Int("numRi")
reseeder.NumSu3 = c.Int("numSu3")
reseeder.RebuildInterval = reloadIntvl

View File

@@ -35,25 +35,24 @@ func loadPrivateKey(path string) (*rsa.PrivateKey, error) {
return privKey, nil
}
func signerFile(signerId string) string {
return strings.Replace(signerId, "@", "_at_", 1)
func signerFile(signerID string) string {
return strings.Replace(signerID, "@", "_at_", 1)
}
func getOrNewSigningCert(signerKey *string, signerId string) (*rsa.PrivateKey, error) {
func getOrNewSigningCert(signerKey *string, signerID string) (*rsa.PrivateKey, error) {
if _, err := os.Stat(*signerKey); nil != err {
fmt.Printf("Unable to read signing key '%s'\n", *signerKey)
fmt.Printf("Would you like to generate a new signing key for %s? (y or n): ", signerId)
fmt.Printf("Would you like to generate a new signing key for %s? (y or n): ", signerID)
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if []byte(input)[0] != 'y' {
return nil, fmt.Errorf("A signing key is required")
} else {
if err := createSigningCertificate(signerId); nil != err {
}
if err := createSigningCertificate(signerID); nil != err {
return nil, err
}
*signerKey = signerFile(signerId) + ".pem"
}
*signerKey = signerFile(signerID) + ".pem"
}
return loadPrivateKey(*signerKey)
@@ -76,7 +75,8 @@ func checkOrNewTLSCert(tlsHost string, tlsCert, tlsKey *string) error {
if []byte(input)[0] != 'y' {
fmt.Println("Continuing without TLS")
return nil
} else {
}
if err := createTLSCertificate(tlsHost); nil != err {
return err
}
@@ -84,12 +84,11 @@ func checkOrNewTLSCert(tlsHost string, tlsCert, tlsKey *string) error {
*tlsCert = tlsHost + ".crt"
*tlsKey = tlsHost + ".pem"
}
}
return nil
}
func createSigningCertificate(signerId string) error {
func createSigningCertificate(signerID string) error {
// generate private key
fmt.Println("Generating signing keys. This may take a minute...")
signerKey, err := rsa.GenerateKey(rand.Reader, 4096)
@@ -97,26 +96,26 @@ func createSigningCertificate(signerId string) error {
return err
}
signerCert, err := su3.NewSigningCertificate(signerId, signerKey)
signerCert, err := su3.NewSigningCertificate(signerID, signerKey)
if nil != err {
return err
}
// save cert
certFile := signerFile(signerId) + ".crt"
certFile := signerFile(signerID) + ".crt"
certOut, err := os.Create(certFile)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", certFile, err)
return fmt.Errorf("failed to open %s for writing: %v", certFile, err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: signerCert})
certOut.Close()
fmt.Println("\tSigning certificate saved to:", certFile)
// save signing private key
privFile := signerFile(signerId) + ".pem"
privFile := signerFile(signerID) + ".pem"
keyOut, err := os.OpenFile(privFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", privFile, err)
return fmt.Errorf("failed to open %s for writing: %v", privFile, err)
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(signerKey)})
pem.Encode(keyOut, &pem.Block{Type: "CERTIFICATE", Bytes: signerCert})
@@ -124,7 +123,7 @@ func createSigningCertificate(signerId string) error {
fmt.Println("\tSigning private key saved to:", privFile)
// CRL
crlFile := signerFile(signerId) + ".crl"
crlFile := signerFile(signerID) + ".crl"
crlOut, err := os.OpenFile(crlFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s", crlFile, err)
@@ -159,7 +158,6 @@ func createSigningCertificate(signerId string) error {
func createTLSCertificate(host string) error {
fmt.Println("Generating TLS keys. This may take a minute...")
// priv, err := rsa.GenerateKey(rand.Reader, 4096)
priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return err
@@ -183,7 +181,7 @@ func createTLSCertificate(host string) error {
privFile := host + ".pem"
keyOut, err := os.OpenFile(privFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %s for writing: %s\n", privFile, err)
return fmt.Errorf("failed to open %s for writing: %v", privFile, err)
}
secp384r1, err := asn1.Marshal(asn1.ObjectIdentifier{1, 3, 132, 0, 34}) // http://www.ietf.org/rfc/rfc5480.txt
pem.Encode(keyOut, &pem.Block{Type: "EC PARAMETERS", Bytes: secp384r1})

View File

@@ -25,7 +25,7 @@ func NewSu3VerifyCommand() cli.Command {
}
func su3VerifyAction(c *cli.Context) {
su3File := su3.Su3File{}
su3File := su3.New()
data, err := ioutil.ReadFile(c.Args().Get(0))
if nil != err {
@@ -39,7 +39,7 @@ func su3VerifyAction(c *cli.Context) {
// get the reseeder key
ks := reseed.KeyStore{Path: "./certificates"}
cert, err := ks.ReseederCertificate(su3File.SignerId)
cert, err := ks.ReseederCertificate(su3File.SignerID)
if nil != err {
fmt.Println(err)
return
@@ -49,7 +49,7 @@ func su3VerifyAction(c *cli.Context) {
panic(err)
}
fmt.Printf("Signature is valid for signer '%s'\n", su3File.SignerId)
fmt.Printf("Signature is valid for signer '%s'\n", su3File.SignerID)
if c.Bool("extract") {
// @todo: don't assume zip

View File

@@ -1,7 +0,0 @@
FROM progrium/busybox:latest
ADD i2p-tools i2p-tools
ENTRYPOINT ["/i2p-tools"]
EXPOSE 443

View File

@@ -20,7 +20,7 @@ func (s *Blacklist) LoadFile(file string) error {
if file != "" {
if content, err := ioutil.ReadFile(file); err == nil {
for _, ip := range strings.Split(string(content), "\n") {
s.BlockIp(ip)
s.BlockIP(ip)
}
} else {
return err
@@ -30,7 +30,7 @@ func (s *Blacklist) LoadFile(file string) error {
return nil
}
func (s *Blacklist) BlockIp(ip string) {
func (s *Blacklist) BlockIP(ip string) {
s.m.Lock()
defer s.m.Unlock()

View File

@@ -17,7 +17,7 @@ import (
)
const (
I2P_USER_AGENT = "Wget/1.11.4"
i2pUserAgent = "Wget/1.11.4"
)
type Server struct {
@@ -26,48 +26,6 @@ type Server struct {
Blacklist *Blacklist
}
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(newBlacklistListener(ln, srv.Blacklist))
}
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
tlsListener := tls.NewListener(newBlacklistListener(ln, srv.Blacklist), config)
return srv.Serve(tlsListener)
}
func NewServer(prefix string, trustProxy bool) *Server {
config := &tls.Config{
MinVersion: tls.VersionTLS10,
@@ -109,7 +67,50 @@ func NewServer(prefix string, trustProxy bool) *Server {
return &server
}
func (s *Server) reseedHandler(w http.ResponseWriter, r *http.Request) {
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(newBlacklistListener(ln, srv.Blacklist))
}
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
if srv.TLSConfig == nil {
srv.TLSConfig = &tls.Config{}
}
if srv.TLSConfig.NextProtos == nil {
srv.TLSConfig.NextProtos = []string{"http/1.1"}
}
var err error
srv.TLSConfig.Certificates = make([]tls.Certificate, 1)
srv.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
tlsListener := tls.NewListener(newBlacklistListener(ln, srv.Blacklist), srv.TLSConfig)
return srv.Serve(tlsListener)
}
func (srv *Server) reseedHandler(w http.ResponseWriter, r *http.Request) {
var peer Peer
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
peer = Peer(ip)
@@ -117,7 +118,7 @@ func (s *Server) reseedHandler(w http.ResponseWriter, r *http.Request) {
peer = Peer(r.RemoteAddr)
}
su3Bytes, err := s.Reseeder.PeerSu3Bytes(peer)
su3Bytes, err := srv.Reseeder.PeerSu3Bytes(peer)
if nil != err {
http.Error(w, "500 Unable to serve su3", http.StatusInternalServerError)
return
@@ -144,7 +145,7 @@ func loggingMiddleware(next http.Handler) http.Handler {
func verifyMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if I2P_USER_AGENT != r.UserAgent() {
if i2pUserAgent != r.UserAgent() {
http.Error(w, "403 Forbidden", http.StatusForbidden)
return
}

View File

@@ -43,7 +43,7 @@ type ReseederImpl struct {
su3s chan [][]byte
SigningKey *rsa.PrivateKey
SignerId []byte
SignerID []byte
NumRi int
RebuildInterval time.Duration
NumSu3 int
@@ -110,7 +110,7 @@ func (rs *ReseederImpl) rebuild() error {
// fail if we don't have enough RIs to make a single reseed file
if rs.NumRi > len(ris) {
return fmt.Errorf("Not enough routerInfos.")
return fmt.Errorf("not enough routerInfos - have: %d, need: %d", len(ris), rs.NumRi)
}
// build a pipeline ris -> seeds -> su3
@@ -179,8 +179,8 @@ func (rs *ReseederImpl) seedsProducer(ris []routerInfo) <-chan []routerInfo {
return out
}
func (rs *ReseederImpl) su3Builder(in <-chan []routerInfo) <-chan *su3.Su3File {
out := make(chan *su3.Su3File)
func (rs *ReseederImpl) su3Builder(in <-chan []routerInfo) <-chan *su3.File {
out := make(chan *su3.File)
go func() {
for seeds := range in {
gs, err := rs.createSu3(seeds)
@@ -207,10 +207,10 @@ func (rs *ReseederImpl) PeerSu3Bytes(peer Peer) ([]byte, error) {
return m[peer.Hash()%len(m)], nil
}
func (rs *ReseederImpl) createSu3(seeds []routerInfo) (*su3.Su3File, error) {
su3File := su3.NewSu3File()
su3File.FileType = su3.FILE_TYPE_ZIP
su3File.ContentType = su3.CONTENT_TYPE_RESEED
func (rs *ReseederImpl) createSu3(seeds []routerInfo) (*su3.File, error) {
su3File := su3.New()
su3File.FileType = su3.FileTypeZIP
su3File.ContentType = su3.ContentTypeReseed
zipped, err := zipSeeds(seeds)
if nil != err {
@@ -218,7 +218,7 @@ func (rs *ReseederImpl) createSu3(seeds []routerInfo) (*su3.Su3File, error) {
}
su3File.Content = zipped
su3File.SignerId = rs.SignerId
su3File.SignerID = rs.SignerID
su3File.Sign(rs.SigningKey)
return su3File, nil
@@ -275,8 +275,8 @@ func (db *LocalNetDbImpl) RouterInfos() (routerInfos []routerInfo, err error) {
return
}
func fanIn(inputs ...<-chan *su3.Su3File) <-chan *su3.Su3File {
out := make(chan *su3.Su3File, len(inputs))
func fanIn(inputs ...<-chan *su3.File) <-chan *su3.File {
out := make(chan *su3.File, len(inputs))
var wg sync.WaitGroup
wg.Add(len(inputs))
@@ -288,7 +288,7 @@ func fanIn(inputs ...<-chan *su3.Su3File) <-chan *su3.Su3File {
// fan-in all the inputs to a single output
for _, input := range inputs {
go func(in <-chan *su3.Su3File) {
go func(in <-chan *su3.File) {
defer wg.Done()
for n := range in {
out <- n

View File

@@ -76,7 +76,7 @@ func checkSignature(c *x509.Certificate, algo x509.SignatureAlgorithm, signed, s
return x509.ErrUnsupportedAlgorithm
}
func NewSigningCertificate(signerId string, privateKey *rsa.PrivateKey) ([]byte, error) {
func NewSigningCertificate(signerID string, privateKey *rsa.PrivateKey) ([]byte, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
@@ -86,7 +86,7 @@ func NewSigningCertificate(signerId string, privateKey *rsa.PrivateKey) ([]byte,
template := &x509.Certificate{
BasicConstraintsValid: true,
IsCA: true,
SubjectKeyId: []byte(signerId),
SubjectKeyId: []byte(signerID),
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"I2P Anonymous Network"},
@@ -94,7 +94,7 @@ func NewSigningCertificate(signerId string, privateKey *rsa.PrivateKey) ([]byte,
Locality: []string{"XX"},
StreetAddress: []string{"XX"},
Country: []string{"XX"},
CommonName: signerId,
CommonName: signerID,
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),

View File

@@ -13,65 +13,63 @@ import (
)
const (
MIN_VERSION_LENGTH = 16
minVersionLength = 16
SIGTYPE_DSA = uint16(0)
SIGTYPE_ECDSA_SHA256 = uint16(1)
SIGTYPE_ECDSA_SHA384 = uint16(2)
SIGTYPE_ECDSA_SHA512 = uint16(3)
SIGTYPE_RSA_SHA256 = uint16(4)
SIGTYPE_RSA_SHA384 = uint16(5)
SIGTYPE_RSA_SHA512 = uint16(6)
SigTypeDSA = uint16(0)
SigTypeECDSAWithSHA256 = uint16(1)
SigTypeECDSAWithSHA384 = uint16(2)
SigTypeECDSAWithSHA512 = uint16(3)
SigTypeRSAWithSHA256 = uint16(4)
SigTypeRSAWithSHA384 = uint16(5)
SigTypeRSAWithSHA512 = uint16(6)
CONTENT_TYPE_UNKNOWN = uint8(0)
CONTENT_TYPE_ROUTER = uint8(1)
CONTENT_TYPE_PLUGIN = uint8(2)
CONTENT_TYPE_RESEED = uint8(3)
CONTENT_TYPE_NEWS = uint8(4)
ContentTypeUnknown = uint8(0)
ContentTypeRouter = uint8(1)
ContentTypePlugin = uint8(2)
ContentTypeReseed = uint8(3)
ContentTypeNews = uint8(4)
FILE_TYPE_ZIP = uint8(0)
FILE_TYPE_XML = uint8(1)
FILE_TYPE_HTML = uint8(2)
FILE_TYPE_XMLGZ = uint8(3)
FileTypeZIP = uint8(0)
FileTypeXML = uint8(1)
FileTypeHTML = uint8(2)
FileTypeXMLGZ = uint8(3)
magicBytes = "I2Psu3"
)
var (
MAGIC_BYTES = []byte("I2Psu3")
)
type Su3File struct {
type File struct {
Format uint8
SignatureType uint16
FileType uint8
ContentType uint8
Version []byte
SignerId []byte
SignerID []byte
Content []byte
Signature []byte
SignedBytes []byte
}
func NewSu3File() *Su3File {
return &Su3File{
func New() *File {
return &File{
Version: []byte(strconv.FormatInt(time.Now().Unix(), 10)),
SignatureType: SIGTYPE_RSA_SHA512,
SignatureType: SigTypeRSAWithSHA512,
}
}
func (s *Su3File) Sign(privkey *rsa.PrivateKey) error {
func (s *File) Sign(privkey *rsa.PrivateKey) error {
var hashType crypto.Hash
switch s.SignatureType {
case SIGTYPE_DSA:
case SigTypeDSA:
hashType = crypto.SHA1
case SIGTYPE_ECDSA_SHA256, SIGTYPE_RSA_SHA256:
case SigTypeECDSAWithSHA256, SigTypeRSAWithSHA256:
hashType = crypto.SHA256
case SIGTYPE_ECDSA_SHA384, SIGTYPE_RSA_SHA384:
case SigTypeECDSAWithSHA384, SigTypeRSAWithSHA384:
hashType = crypto.SHA384
case SIGTYPE_ECDSA_SHA512, SIGTYPE_RSA_SHA512:
case SigTypeECDSAWithSHA512, SigTypeRSAWithSHA512:
hashType = crypto.SHA512
default:
return fmt.Errorf("Unknown signature type.")
return fmt.Errorf("unknown signature type: %d", s.SignatureType)
}
h := hashType.New()
@@ -88,7 +86,7 @@ func (s *Su3File) Sign(privkey *rsa.PrivateKey) error {
return nil
}
func (s *Su3File) BodyBytes() []byte {
func (s *File) BodyBytes() []byte {
var (
buf = new(bytes.Buffer)
@@ -97,31 +95,31 @@ func (s *Su3File) BodyBytes() []byte {
versionLength = uint8(len(s.Version))
signatureLength = uint16(512)
signerIdLength = uint8(len(s.SignerId))
signerIDLength = uint8(len(s.SignerID))
contentLength = uint64(len(s.Content))
)
// determine sig length based on type
switch s.SignatureType {
case SIGTYPE_DSA:
case SigTypeDSA:
signatureLength = uint16(40)
case SIGTYPE_ECDSA_SHA256, SIGTYPE_RSA_SHA256:
case SigTypeECDSAWithSHA256, SigTypeRSAWithSHA256:
signatureLength = uint16(256)
case SIGTYPE_ECDSA_SHA384, SIGTYPE_RSA_SHA384:
case SigTypeECDSAWithSHA384, SigTypeRSAWithSHA384:
signatureLength = uint16(384)
case SIGTYPE_ECDSA_SHA512, SIGTYPE_RSA_SHA512:
case SigTypeECDSAWithSHA512, SigTypeRSAWithSHA512:
signatureLength = uint16(512)
}
// pad the version field
if len(s.Version) < MIN_VERSION_LENGTH {
minBytes := make([]byte, MIN_VERSION_LENGTH)
if len(s.Version) < minVersionLength {
minBytes := make([]byte, minVersionLength)
copy(minBytes, s.Version)
s.Version = minBytes
versionLength = uint8(len(s.Version))
}
binary.Write(buf, binary.BigEndian, MAGIC_BYTES)
binary.Write(buf, binary.BigEndian, []byte(magicBytes))
binary.Write(buf, binary.BigEndian, skip)
binary.Write(buf, binary.BigEndian, s.Format)
binary.Write(buf, binary.BigEndian, s.SignatureType)
@@ -129,7 +127,7 @@ func (s *Su3File) BodyBytes() []byte {
binary.Write(buf, binary.BigEndian, skip)
binary.Write(buf, binary.BigEndian, versionLength)
binary.Write(buf, binary.BigEndian, skip)
binary.Write(buf, binary.BigEndian, signerIdLength)
binary.Write(buf, binary.BigEndian, signerIDLength)
binary.Write(buf, binary.BigEndian, contentLength)
binary.Write(buf, binary.BigEndian, skip)
binary.Write(buf, binary.BigEndian, s.FileType)
@@ -137,13 +135,13 @@ func (s *Su3File) BodyBytes() []byte {
binary.Write(buf, binary.BigEndian, s.ContentType)
binary.Write(buf, binary.BigEndian, bigSkip)
binary.Write(buf, binary.BigEndian, s.Version)
binary.Write(buf, binary.BigEndian, s.SignerId)
binary.Write(buf, binary.BigEndian, s.SignerID)
binary.Write(buf, binary.BigEndian, s.Content)
return buf.Bytes()
}
func (s *Su3File) MarshalBinary() ([]byte, error) {
func (s *File) MarshalBinary() ([]byte, error) {
buf := bytes.NewBuffer(s.BodyBytes())
// append the signature
@@ -152,17 +150,17 @@ func (s *Su3File) MarshalBinary() ([]byte, error) {
return buf.Bytes(), nil
}
func (s *Su3File) UnmarshalBinary(data []byte) error {
func (s *File) UnmarshalBinary(data []byte) error {
var (
r = bytes.NewReader(data)
magic = MAGIC_BYTES
magic = []byte(magicBytes)
skip [1]byte
bigSkip [12]byte
signatureLength uint16
versionLength uint8
signerIdLength uint8
signerIDLength uint8
contentLength uint64
)
@@ -174,7 +172,7 @@ func (s *Su3File) UnmarshalBinary(data []byte) error {
binary.Read(r, binary.BigEndian, &skip)
binary.Read(r, binary.BigEndian, &versionLength)
binary.Read(r, binary.BigEndian, &skip)
binary.Read(r, binary.BigEndian, &signerIdLength)
binary.Read(r, binary.BigEndian, &signerIDLength)
binary.Read(r, binary.BigEndian, &contentLength)
binary.Read(r, binary.BigEndian, &skip)
binary.Read(r, binary.BigEndian, &s.FileType)
@@ -183,43 +181,43 @@ func (s *Su3File) UnmarshalBinary(data []byte) error {
binary.Read(r, binary.BigEndian, &bigSkip)
s.Version = make([]byte, versionLength)
s.SignerId = make([]byte, signerIdLength)
s.SignerID = make([]byte, signerIDLength)
s.Content = make([]byte, contentLength)
s.Signature = make([]byte, signatureLength)
binary.Read(r, binary.BigEndian, &s.Version)
binary.Read(r, binary.BigEndian, &s.SignerId)
binary.Read(r, binary.BigEndian, &s.SignerID)
binary.Read(r, binary.BigEndian, &s.Content)
binary.Read(r, binary.BigEndian, &s.Signature)
return nil
}
func (s *Su3File) VerifySignature(cert *x509.Certificate) error {
func (s *File) VerifySignature(cert *x509.Certificate) error {
var sigAlg x509.SignatureAlgorithm
switch s.SignatureType {
case SIGTYPE_DSA:
case SigTypeDSA:
sigAlg = x509.DSAWithSHA1
case SIGTYPE_ECDSA_SHA256:
case SigTypeECDSAWithSHA256:
sigAlg = x509.ECDSAWithSHA256
case SIGTYPE_ECDSA_SHA384:
case SigTypeECDSAWithSHA384:
sigAlg = x509.ECDSAWithSHA384
case SIGTYPE_ECDSA_SHA512:
case SigTypeECDSAWithSHA512:
sigAlg = x509.ECDSAWithSHA512
case SIGTYPE_RSA_SHA256:
case SigTypeRSAWithSHA256:
sigAlg = x509.SHA256WithRSA
case SIGTYPE_RSA_SHA384:
case SigTypeRSAWithSHA384:
sigAlg = x509.SHA384WithRSA
case SIGTYPE_RSA_SHA512:
case SigTypeRSAWithSHA512:
sigAlg = x509.SHA512WithRSA
default:
return fmt.Errorf("Unknown signature type.")
return fmt.Errorf("unknown signature type: %d", s.SignatureType)
}
return checkSignature(cert, sigAlg, s.BodyBytes(), s.Signature)
}
func (s *Su3File) String() string {
func (s *File) String() string {
var b bytes.Buffer
// header
@@ -229,7 +227,7 @@ func (s *Su3File) String() string {
fmt.Fprintf(&b, "FileType: %q\n", s.FileType)
fmt.Fprintf(&b, "ContentType: %q\n", s.ContentType)
fmt.Fprintf(&b, "Version: %q\n", bytes.Trim(s.Version, "\x00"))
fmt.Fprintf(&b, "SignerId: %q\n", s.SignerId)
fmt.Fprintf(&b, "SignerId: %q\n", s.SignerID)
fmt.Fprintf(&b, "---------------------------")
// content & signature