package identity import ( "encoding/hex" "errors" "time" "git.stinnesbeck.com/nils/allmende/internal/jcs" ) const ( CertVersion = 1 MaxCertLifetime = 366 * 24 * time.Hour certContext = "allmende-cert-v1\n" ) // Cert is the identity key's statement "this device may sign on my behalf". // It is public and travels with every listing. type Cert struct { Version int `json:"v"` Author string `json:"author"` // identity public key, hex Device string `json:"device"` // device public key, hex IssuedAt int64 `json:"issued_at"` ExpiresAt int64 `json:"expires_at"` Sig string `json:"sig,omitempty"` } func (c *Cert) signingBytes() ([]byte, error) { cp := *c cp.Sig = "" b, err := jcs.Marshal(&cp) if err != nil { return nil, err } return append([]byte(certContext), b...), nil } // IssueCert signs a certificate for devicePub with the identity key. func IssueCert(root *Identity, devicePub string, issuedAt, expiresAt time.Time) (*Cert, error) { c := &Cert{ Version: CertVersion, Author: root.PublicKeyHex(), Device: devicePub, IssuedAt: issuedAt.Unix(), ExpiresAt: expiresAt.Unix(), } if err := c.checkFields(); err != nil { return nil, err } b, err := c.signingBytes() if err != nil { return nil, err } c.Sig = hex.EncodeToString(root.Sign(b)) return c, nil } func (c *Cert) checkFields() error { switch { case c.Version != CertVersion: return errors.New("identity: unsupported cert version") case !isHex(c.Author, 64) || !isHex(c.Device, 64): return errors.New("identity: cert keys must be 64 hex characters") case c.ExpiresAt <= c.IssuedAt: return errors.New("identity: cert expires before it is issued") case time.Duration(c.ExpiresAt-c.IssuedAt)*time.Second > MaxCertLifetime: return errors.New("identity: cert lifetime too long") } return nil } // Check verifies structure and signature. It does not look at the clock; // use Covers for that. func (c *Cert) Check() error { if err := c.checkFields(); err != nil { return err } sig, err := hex.DecodeString(c.Sig) if err != nil || len(sig) != 64 { return errors.New("identity: malformed cert signature") } b, err := c.signingBytes() if err != nil { return err } if !Verify(c.Author, b, sig) { return errors.New("identity: bad cert signature") } return nil } // Covers reports whether unix time t lies within the certificate's validity. func (c *Cert) Covers(t int64) bool { return t >= c.IssuedAt && t < c.ExpiresAt } func isHex(s string, n int) bool { if len(s) != n { return false } for i := 0; i < len(s); i++ { c := s[i] if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { return false } } return true }