VerifyMetadataSignature checks that the root element of the SAML metadata in data, an EntityDescriptor or an EntitiesDescriptor, carries a valid enveloped XML signature made with one of certs (saml-metadata-2.0-os §3). It returns the metadata the signature covers: the root element without its Signat
(data []byte, certs []*x509.Certificate)
| 29 | // validity periods are not checked, as for other certificates taken from |
| 30 | // metadata, and neither are the metadata's validUntil and cacheDuration. |
| 31 | func VerifyMetadataSignature(data []byte, certs []*x509.Certificate) ([]byte, error) { |
| 32 | if len(certs) == 0 { |
| 33 | return nil, errors.New("cannot verify metadata signature: no certificate to verify it with") |
| 34 | } |
| 35 | |
| 36 | if err := xmlroundtrip.Validate(data); err != nil { |
| 37 | return nil, classify(fmt.Errorf("invalid xml: %w", err), ErrMalformedMessage) |
| 38 | } |
| 39 | doc := etree.NewDocument() |
| 40 | if err := doc.ReadFromBytes(data); err != nil { |
| 41 | return nil, classify(fmt.Errorf("invalid xml: %w", err), ErrMalformedMessage) |
| 42 | } |
| 43 | root := doc.Root() |
| 44 | if root == nil { |
| 45 | return nil, classify(errors.New("invalid xml: no root"), ErrMalformedMessage) |
| 46 | } |
| 47 | |
| 48 | ctx, err := etreeutils.NSBuildParentContext(root) |
| 49 | if err != nil { |
| 50 | return nil, classify(err, ErrMalformedMessage) |
| 51 | } |
| 52 | ctx, err = ctx.SubContext(root) |
| 53 | if err != nil { |
| 54 | return nil, classify(err, ErrMalformedMessage) |
| 55 | } |
| 56 | ns, err := ctx.LookupPrefix(root.Space) |
| 57 | if err != nil || ns != metadataNamespace || (root.Tag != "EntityDescriptor" && root.Tag != "EntitiesDescriptor") { |
| 58 | return nil, classify(fmt.Errorf("expected an EntityDescriptor or EntitiesDescriptor in %s, not %s", metadataNamespace, root.Tag), ErrMalformedMessage) |
| 59 | } |
| 60 | |
| 61 | signed, err := verifiedEnvelopedElement(root, certs, nil) |
| 62 | if err != nil { |
| 63 | if errors.Is(err, errSignatureElementNotPresent) { |
| 64 | return nil, classify(errors.New("metadata is not signed"), ErrInvalidSignature) |
| 65 | } |
| 66 | return nil, classify(fmt.Errorf("cannot validate signature on %s: %w", root.Tag, err), ErrInvalidSignature) |
| 67 | } |
| 68 | |
| 69 | out := etree.NewDocument() |
| 70 | out.SetRoot(signed) |
| 71 | return out.WriteToBytes() |
| 72 | } |