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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
|
package certificate
import (
"bytes"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"os"
"github.com/pkg/errors"
"github.com/smallstep/certinfo"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/utils"
zx509 "github.com/smallstep/zcrypto/x509"
"github.com/urfave/cli"
)
func inspectCommand() cli.Command {
return cli.Command{
Name: "inspect",
Action: cli.ActionFunc(inspectAction),
Usage: `print certificate or CSR details in human readable format`,
UsageText: `**step certificate inspect** <crt_file>
[**--bundle**] [**--short**] [**--format**=<format>] [**--roots**=<root-bundle>]
[**--servername**=<servername>]`,
Description: `**step certificate inspect** prints the details of a certificate
or CSR in a human readable format. Output from the inspect command is printed to
STDERR instead of STDOUT. This is an intentional barrier to accidental
misuse: scripts should never rely on the contents of an unvalidated certificate.
For scripting purposes, use **step certificate verify**.
If crt_file contains multiple certificates (i.e., it is a certificate "bundle")
the first certificate in the bundle will be output. Pass the --bundle option to
print all certificates in the order in which they appear in the bundle.
## POSITIONAL ARGUMENTS
<crt_file>
: Path to a certificate or certificate signing request (CSR) to inspect. A hyphen ("-") indicates STDIN as <crt_file>.
## EXIT CODES
This command returns 0 on success and \>0 if any error occurs.
## EXAMPLES
Inspect a local certificate (default to text format):
'''
$ step certificate inspect ./certificate.crt
'''
Inspect a local certificate bundle (default to text format):
'''
$ step certificate inspect ./certificate-bundle.crt --bundle
'''
Inspect a local certificate in json format:
'''
$ step certificate inspect ./certificate.crt --format json
'''
Inspect a local certificate bundle in json format:
'''
$ step certificate inspect ./certificate.crt --format json --bundle
'''
Inspect a remote certificate (using the default root certificate bundle to verify the server):
'''
$ step certificate inspect https://smallstep.com
'''
Inspect an invalid remote certificate:
'''
$ step certificate inspect --insecure https://expired.badssl.com
'''
Inspect a remote certificate chain (using the default root certificate bundle to verify the server):
'''
$ step certificate inspect https://google.com --bundle
'''
Inspect a remote certificate using a custom root certificate to verify the server:
'''
$ step certificate inspect https://smallstep.com --roots ./root-ca.crt
'''
Inspect a remote certificate using a custom list of root certificates to verify the server:
'''
$ step certificate inspect https://smallstep.com \
--roots "./root-ca.crt,./root-ca2.crt,/root-ca3.crt"
'''
Inspect a remote certificate using a custom directory of root certificates to verify the server:
'''
$ step certificate inspect https://smallstep.com \
--roots "./path/to/root/certificates/"
'''
Inspect a remote certificate chain in json format using a custom directory of
root certificates to verify the server:
'''
$ step certificate inspect https://google.com --format json \
--roots "./path/to/root/certificates/" --bundle
'''
Inspect a remote certificate chain in PEM format:
'''
$ step certificate inspect https://smallstep.com --format pem --bundle
'''
Inspect a local CSR in text format (default):
'''
$ step certificate inspect foo.csr
'''
Inspect a local CSR in json:
'''
$ step certificate inspect foo.csr --format json
'''
`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Value: "text",
Usage: `The output format for printing the introspection details.
: <format> is a string and must be one of:
**text**
: Print output in unstructured text suitable for a human to read.
**json**
: Print output in JSON format.
**pem**
: Print output in PEM format.`,
},
cli.StringFlag{
Name: "roots",
Usage: `Root certificate(s) that will be used to verify the
authenticity of the remote server.
: <roots> is a case-sensitive string and may be one of:
**file**
: Relative or full path to a file. All certificates in the file will be used for path validation.
**list of files**
: Comma-separated list of relative or full file paths. Every PEM encoded certificate from each file will be used for path validation.
**directory**
: Relative or full path to a directory. Every PEM encoded certificate from each file in the directory will be used for path validation.`,
},
cli.BoolFlag{
Name: `bundle`,
Usage: `Print all certificates in the order in which they appear in the bundle.
If the output format is 'json' then output a list of certificates, even if
the bundle only contains one certificate. This flag will result in an error
if the input bundle includes any PEM that does not have type CERTIFICATE.`,
},
cli.BoolFlag{
Name: "short",
Usage: "Print the certificate or CSR details in shorter and more friendly format.",
},
cli.BoolFlag{
Name: "insecure",
Usage: `Use an insecure client to retrieve a remote peer certificate. Useful for
debugging invalid certificates remotely.`,
},
flags.ServerName,
},
}
}
func inspectAction(ctx *cli.Context) error {
if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil {
return err
}
var (
crtFile = ctx.Args().Get(0)
bundle = ctx.Bool("bundle")
format = ctx.String("format")
roots = ctx.String("roots")
serverName = ctx.String("servername")
short = ctx.Bool("short")
insecure = ctx.Bool("insecure")
)
// Use stdin if no argument is used.
if crtFile == "" {
crtFile = "-"
}
if format != "text" && format != "json" && format != "pem" {
return errs.InvalidFlagValue(ctx, "format", format, "text, json, pem")
}
if short && (format == "json" || format == "pem") {
return errs.IncompatibleFlagWithFlag(ctx, "short", "format json")
}
var block *pem.Block
var blocks []*pem.Block
if addr, isURL, err := trimURL(crtFile); err != nil {
return err
} else if isURL {
peerCertificates, err := getPeerCertificates(addr, serverName, roots, insecure)
if err != nil {
return err
}
for _, crt := range peerCertificates {
blocks = append(blocks, &pem.Block{
Type: "CERTIFICATE",
Bytes: crt.Raw,
})
}
} else {
crtBytes, err := utils.ReadFile(crtFile)
if err != nil {
return errs.FileError(err, crtFile)
}
if bytes.HasPrefix(crtBytes, []byte("-----BEGIN ")) {
for len(crtBytes) > 0 {
block, crtBytes = pem.Decode(crtBytes)
if block == nil {
break
}
if bundle && block.Type != "CERTIFICATE" {
return errors.Errorf("certificate bundle %s contains an unexpected PEM block of type %s\n\n expected type: CERTIFICATE",
crtFile, block.Type)
}
blocks = append(blocks, block)
}
} else {
if block = derToPemBlock(crtBytes); block == nil {
return errors.Errorf("%s contains an invalid PEM block", crtFile)
}
blocks = append(blocks, block)
}
}
// Keep the first one if !bundle
if !bundle {
blocks = []*pem.Block{blocks[0]}
}
switch blocks[0].Type {
case "CERTIFICATE":
return inspectCertificates(ctx, blocks, os.Stdout)
case "CERTIFICATE REQUEST", "NEW CERTIFICATE REQUEST": // only one is supported
return inspectCertificateRequest(ctx, blocks[0])
default:
return errors.Errorf("Invalid PEM type in %s. Expected [CERTIFICATE|CERTIFICATE REQUEST] but got %s)", crtFile, block.Type)
}
}
func inspectCertificates(ctx *cli.Context, blocks []*pem.Block, w io.Writer) error {
format, short := ctx.String("format"), ctx.Bool("short")
switch format {
case "text":
var text string
for _, block := range blocks {
crt, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return errors.WithStack(err)
}
if short {
if text, err = certinfo.CertificateShortText(crt); err != nil {
return err
}
} else {
if text, err = certinfo.CertificateText(crt); err != nil {
return err
}
}
fmt.Fprint(w, text)
}
return nil
case "json":
var v interface{}
if len(blocks) == 1 {
zcrt, err := zx509.ParseCertificate(blocks[0].Bytes)
if err != nil {
return errors.WithStack(err)
}
v = struct{ *zx509.Certificate }{zcrt}
} else {
var zcrts []*zx509.Certificate
for _, block := range blocks {
zcrt, err := zx509.ParseCertificate(block.Bytes)
if err != nil {
return errors.WithStack(err)
}
zcrts = append(zcrts, zcrt)
}
v = zcrts
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
err := enc.Encode(v)
if err != nil {
return errors.WithStack(err)
}
return nil
case "pem":
for _, block := range blocks {
err := pem.Encode(w, block)
if err != nil {
return errors.WithStack(err)
}
}
return nil
default:
return errs.InvalidFlagValue(ctx, "format", format, "text, json, pem")
}
}
func inspectCertificateRequest(ctx *cli.Context, block *pem.Block) error {
format, short := ctx.String("format"), ctx.Bool("short")
switch format {
case "text":
var text string
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return errors.WithStack(err)
}
if short {
text, err = certinfo.CertificateRequestShortText(csr)
if err != nil {
return err
}
} else {
text, err = certinfo.CertificateRequestText(csr)
if err != nil {
return err
}
}
fmt.Print(text)
return nil
case "json":
zcsr, err := zx509.ParseCertificateRequest(block.Bytes)
if err != nil {
return errors.WithStack(err)
}
b, err := json.MarshalIndent(struct {
*zx509.CertificateRequest
}{zcsr}, "", " ")
if err != nil {
return errors.WithStack(err)
}
os.Stdout.Write(b)
return nil
default:
return errs.InvalidFlagValue(ctx, "format", format, "text, json")
}
}
// derToPemBlock attempts to parse the ASN.1 data as a certificate or a
// certificate request, returning a pem.Block of the one that succeeds. Returns
// nil if it cannot parse the data.
func derToPemBlock(b []byte) *pem.Block {
if _, err := x509.ParseCertificate(b); err == nil {
return &pem.Block{Type: "CERTIFICATE", Bytes: b}
}
if _, err := x509.ParseCertificateRequest(b); err == nil {
return &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: b}
}
return nil
}
|