File: wire.go

package info (click to toggle)
golang-github-hiddeco-sshsig 0.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 176 kB
  • sloc: makefile: 17
file content (75 lines) | stat: -rw-r--r-- 2,366 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package sshsig

import (
	"errors"
	"fmt"

	"golang.org/x/crypto/ssh"
)

var (
	// ErrUnsupportedSignatureVersion is returned when the signature version is
	// not supported.
	ErrUnsupportedSignatureVersion = errors.New("unsupported signature version")
	// ErrInvalidMagicPreamble is returned when the magic preamble is invalid.
	ErrInvalidMagicPreamble = errors.New("invalid magic preamble")
)

// sigVersion is the supported version of the SSH signature format.
// xref: https://github.com/openssh/openssh-portable/blob/V_9_2_P1/PROTOCOL.sshsig#L35
const sigVersion = 1

// magicPreamble is the six-byte sequence "SSHSIG". It is included to
// ensure that manual signatures can never be confused with any message
// signed during SSH user or host authentication.
// xref: https://github.com/openssh/openssh-portable/blob/V_9_2_P1/PROTOCOL.sshsig#L89-L91
var magicPreamble = [6]byte{'S', 'S', 'H', 'S', 'I', 'G'}

// signedData represents data that is signed.
// xref: https://github.com/openssh/openssh-portable/blob/V_9_2_P1/PROTOCOL.sshsig#L79
type signedData struct {
	Namespace     string
	Reserved      string
	HashAlgorithm string
	Hash          string
}

// Marshal returns the signed data in SSH wire format.
func (s signedData) Marshal() []byte {
	return append(magicPreamble[:], ssh.Marshal(s)...)
}

// blob represents the SSH signature blob.
// xref: https://github.com/openssh/openssh-portable/blob/V_9_2_P1/PROTOCOL.sshsig#L32
type blob struct {
	// MagicPreamble is included in the struct to ensure we can unmarshal the
	// blob correctly.
	MagicPreamble [6]byte
	Version       uint32
	PublicKey     string
	Namespace     string
	Reserved      string
	HashAlgorithm string
	Signature     string
}

// Validate returns an error if the blob is invalid. This does not check the
// signature itself.
func (b blob) Validate() error {
	if b.Version != sigVersion {
		return fmt.Errorf("%w %d: expected %d", ErrUnsupportedSignatureVersion, b.Version, sigVersion)
	}
	if b.MagicPreamble != magicPreamble {
		return fmt.Errorf("%w %q: expected %q", ErrInvalidMagicPreamble, b.MagicPreamble, magicPreamble)
	}
	if err := HashAlgorithm(b.HashAlgorithm).Supported(); err != nil {
		return err
	}
	return nil
}

// Marshal returns the blob in SSH wire format.
func (b blob) Marshal() []byte {
	copy(b.MagicPreamble[:], magicPreamble[:])
	return ssh.Marshal(b)
}