| 1 |
package sshutil |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"time" |
| 6 |
|
| 7 |
"golang.org/x/crypto/ssh" |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
const certificateInspectLayout = "2006-01-02T15:04:05" |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
type CertificateInspect struct { |
| 16 |
Type string |
| 17 |
KeyName string |
| 18 |
KeyID string |
| 19 |
KeyAlgo string |
| 20 |
KeyFingerprint string |
| 21 |
SigningKeyAlgo string |
| 22 |
SigningKeyFingerprint string |
| 23 |
Serial uint64 |
| 24 |
ValidAfter time.Time |
| 25 |
ValidBefore time.Time |
| 26 |
Principals []string |
| 27 |
CriticalOptions map[string]string |
| 28 |
Extensions map[string]string |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
func InspectCertificate(cert *ssh.Certificate) (*CertificateInspect, error) { |
| 34 |
var certType string |
| 35 |
var validAfter, validBefore time.Time |
| 36 |
|
| 37 |
switch cert.CertType { |
| 38 |
case ssh.HostCert: |
| 39 |
certType = "host" |
| 40 |
case ssh.UserCert: |
| 41 |
certType = "user" |
| 42 |
default: |
| 43 |
certType = "unknown" |
| 44 |
} |
| 45 |
|
| 46 |
algo, sum, err := inspectPublicKey(cert.Key) |
| 47 |
if err != nil { |
| 48 |
return nil, err |
| 49 |
} |
| 50 |
sigAlgo, sigSum, err := inspectPublicKey(cert.SignatureKey) |
| 51 |
if err != nil { |
| 52 |
return nil, err |
| 53 |
} |
| 54 |
|
| 55 |
validAfter = time.Unix(int64(cert.ValidAfter), 0) |
| 56 |
if cert.ValidBefore != ssh.CertTimeInfinity { |
| 57 |
validBefore = time.Unix(int64(cert.ValidBefore), 0) |
| 58 |
} |
| 59 |
|
| 60 |
return &CertificateInspect{ |
| 61 |
Type: certType, |
| 62 |
KeyName: cert.Type(), |
| 63 |
KeyID: cert.KeyId, |
| 64 |
KeyAlgo: algo, |
| 65 |
KeyFingerprint: sum, |
| 66 |
SigningKeyAlgo: sigAlgo, |
| 67 |
SigningKeyFingerprint: sigSum, |
| 68 |
Serial: cert.Serial, |
| 69 |
ValidAfter: validAfter, |
| 70 |
ValidBefore: validBefore, |
| 71 |
Principals: cert.ValidPrincipals, |
| 72 |
CriticalOptions: cert.CriticalOptions, |
| 73 |
Extensions: cert.Extensions, |
| 74 |
}, nil |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
func (c *CertificateInspect) Validity() string { |
| 80 |
if c.ValidBefore.IsZero() { |
| 81 |
return "forever" |
| 82 |
} |
| 83 |
return fmt.Sprintf("from %s to %s", |
| 84 |
c.ValidAfter.Local().Format(certificateInspectLayout), |
| 85 |
c.ValidBefore.Local().Format(certificateInspectLayout), |
| 86 |
) |
| 87 |
} |
| 88 |
|
| 89 |
func inspectPublicKey(key ssh.PublicKey) (string, string, error) { |
| 90 |
fp := ssh.FingerprintSHA256(key) |
| 91 |
typ, _, err := publicKeyTypeAndSize(key) |
| 92 |
if err != nil { |
| 93 |
return "", "", err |
| 94 |
} |
| 95 |
|
| 96 |
return typ, fp, nil |
| 97 |
} |