diff --git a/internal/tools/ooxmlgate.go b/internal/tools/ooxmlgate.go index 292e995..5e647b5 100644 --- a/internal/tools/ooxmlgate.go +++ b/internal/tools/ooxmlgate.go @@ -14,14 +14,23 @@ import ( "encoding/xml" "fmt" "io" + "net/url" "path" "path/filepath" "strings" ) const ( + nsPackageRel = "http://schemas.openxmlformats.org/package/2006/relationships" + nsContentTypes = "http://schemas.openxmlformats.org/package/2006/content-types" nsPresentationML = "http://schemas.openxmlformats.org/presentationml/2006/main" nsOfficeDocRel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" + relOfficeDoc = nsOfficeDocRel + "/officeDocument" + relStrictOffice = "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument" + ctWordDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" + ctWordTemplate = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml" + ctWordMacroDoc = "application/vnd.ms-word.document.macroEnabled.main+xml" + ctWordMacroTpl = "application/vnd.ms-word.template.macroEnabledTemplate.main+xml" ctPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml" ctSlide = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml" ctSlideLayout = "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml" @@ -44,20 +53,324 @@ func ooxmlStructuralCheck(name string, content []byte) error { } } -// isWordprocessingMLPackage identifies Word OPC packages from their mandatory -// main document part instead of trusting the caller-controlled filename. The -// part is shared by document/template and macro-enabled variants. +// isWordprocessingMLPackage identifies Word OPC packages from the package-level +// officeDocument relationship and the resolved main part's content type. A +// purported officeDocument package with malformed, ambiguous, or unsafe +// metadata is treated as Word so the registration boundary fails closed. func isWordprocessingMLPackage(content []byte) bool { zr, err := zip.NewReader(bytes.NewReader(content), int64(len(content))) if err != nil { return false } - for _, file := range zr.File { - if strings.EqualFold(strings.TrimPrefix(file.Name, "/"), "word/document.xml") { - return true + isWord, purportsOfficeDocument, err := ooxmlClassifyWordPackage(zr) + if err != nil { + return purportsOfficeDocument + } + return isWord +} + +func ooxmlClassifyWordPackage(zr *zip.Reader) (isWord, purportsOfficeDocument bool, err error) { + relsFile, found, err := ooxmlUniquePart(zr, "_rels/.rels") + if err != nil { + return false, true, err + } + if !found { + return false, false, nil + } + rels, purportsOfficeDocument, err := ooxmlPackageRelationships(relsFile) + if err != nil { + return false, purportsOfficeDocument, err + } + + var officeRels []ooxmlRel + for _, rel := range rels { + if rel.typ == relOfficeDoc || rel.typ == relStrictOffice { + officeRels = append(officeRels, rel) } } - return false + if len(officeRels) == 0 { + return false, false, nil + } + if len(officeRels) != 1 { + return false, true, fmt.Errorf("package relationships contain %d officeDocument relationships", len(officeRels)) + } + + mainPart, err := ooxmlSafePackageTarget(officeRels[0].target, officeRels[0].targetMode) + if err != nil { + return false, true, err + } + if _, found, err := ooxmlUniquePartFold(zr, mainPart); err != nil || !found { + if err != nil { + return false, true, err + } + return false, true, fmt.Errorf("officeDocument target %q is missing", mainPart) + } + + contentTypesFile, found, err := ooxmlUniquePart(zr, "[Content_Types].xml") + if err != nil { + return false, true, err + } + if !found { + return false, true, fmt.Errorf("officeDocument package is missing [Content_Types].xml") + } + contentTypes, err := ooxmlParseContentTypes(contentTypesFile) + if err != nil { + return false, true, err + } + contentType, found := contentTypes.contentType(mainPart) + if !found { + return false, true, fmt.Errorf("officeDocument target %q has no content type", mainPart) + } + return ooxmlIsWordMainContentType(contentType), true, nil +} + +type ooxmlContentTypeTable struct { + defaults map[string]string + overrides map[string]string +} + +func (t ooxmlContentTypeTable) contentType(part string) (string, bool) { + if contentType, ok := t.overrides[strings.ToLower(part)]; ok { + return contentType, true + } + extension := strings.TrimPrefix(path.Ext(part), ".") + contentType, ok := t.defaults[strings.ToLower(extension)] + return contentType, ok +} + +func ooxmlIsWordMainContentType(contentType string) bool { + switch contentType { + case ctWordDocument, ctWordTemplate, ctWordMacroDoc, ctWordMacroTpl: + return true + default: + return false + } +} + +func ooxmlPackageRelationships(file *zip.File) ([]ooxmlRel, bool, error) { + rc, err := file.Open() + if err != nil { + return nil, false, fmt.Errorf("_rels/.rels cannot be read: %w", err) + } + defer rc.Close() + + dec := xml.NewDecoder(rc) + var rels []ooxmlRel + seenIDs := map[string]bool{} + rootSeen := false + rootValid := false + depth := 0 + purportsOfficeDocument := false + var metadataErr error + for { + tok, err := dec.Token() + if err == io.EOF { + break + } + if err != nil { + return nil, purportsOfficeDocument, fmt.Errorf("_rels/.rels is not valid XML: %w", err) + } + switch node := tok.(type) { + case xml.EndElement: + depth-- + continue + case xml.StartElement: + depth++ + if !rootSeen { + rootSeen = true + rootValid = node.Name.Space == nsPackageRel && node.Name.Local == "Relationships" + if !rootValid { + metadataErr = fmt.Errorf("_rels/.rels has an invalid Relationships root") + } + continue + } + + var rel ooxmlRel + seenAttrs := map[string]bool{} + for _, attr := range node.Attr { + if attr.Name.Space != "" { + continue + } + if seenAttrs[attr.Name.Local] { + metadataErr = fmt.Errorf("_rels/.rels contains duplicate %s attributes", attr.Name.Local) + } + seenAttrs[attr.Name.Local] = true + switch attr.Name.Local { + case "Id": + rel.id = attr.Value + case "Type": + rel.typ = attr.Value + case "Target": + rel.target = attr.Value + case "TargetMode": + rel.targetMode = attr.Value + } + } + if rel.typ == relOfficeDoc || rel.typ == relStrictOffice { + purportsOfficeDocument = true + } + if depth != 2 || node.Name.Space != nsPackageRel || node.Name.Local != "Relationship" { + metadataErr = fmt.Errorf("_rels/.rels contains an invalid relationship element") + continue + } + if rel.id == "" || rel.typ == "" || rel.target == "" { + metadataErr = fmt.Errorf("_rels/.rels contains an incomplete Relationship") + continue + } + if seenIDs[rel.id] { + metadataErr = fmt.Errorf("_rels/.rels contains duplicate relationship Id %q", rel.id) + continue + } + seenIDs[rel.id] = true + rels = append(rels, rel) + } + } + if !rootSeen { + return nil, false, fmt.Errorf("_rels/.rels is empty") + } + if !rootValid || metadataErr != nil { + return nil, purportsOfficeDocument, metadataErr + } + return rels, purportsOfficeDocument, nil +} + +func ooxmlParseContentTypes(file *zip.File) (ooxmlContentTypeTable, error) { + table := ooxmlContentTypeTable{ + defaults: map[string]string{}, + overrides: map[string]string{}, + } + rc, err := file.Open() + if err != nil { + return table, fmt.Errorf("[Content_Types].xml cannot be read: %w", err) + } + defer rc.Close() + + dec := xml.NewDecoder(rc) + rootSeen := false + for { + tok, err := dec.Token() + if err == io.EOF { + break + } + if err != nil { + return table, fmt.Errorf("[Content_Types].xml is not valid XML: %w", err) + } + se, ok := tok.(xml.StartElement) + if !ok { + continue + } + if !rootSeen { + rootSeen = true + if se.Name.Space != nsContentTypes || se.Name.Local != "Types" { + return table, fmt.Errorf("[Content_Types].xml has an invalid Types root") + } + continue + } + if se.Name.Space != nsContentTypes { + continue + } + attrs := map[string]string{} + for _, attr := range se.Attr { + if attr.Name.Space == "" { + attrs[attr.Name.Local] = attr.Value + } + } + switch se.Name.Local { + case "Default": + extension := strings.ToLower(attrs["Extension"]) + contentType := attrs["ContentType"] + if extension == "" || strings.ContainsAny(extension, ".\\/ \t\r\n") || contentType == "" { + return table, fmt.Errorf("[Content_Types].xml contains an invalid Default") + } + if _, exists := table.defaults[extension]; exists { + return table, fmt.Errorf("[Content_Types].xml contains duplicate Default for %q", extension) + } + table.defaults[extension] = contentType + case "Override": + partName, err := ooxmlSafePartName(attrs["PartName"]) + if err != nil || attrs["ContentType"] == "" { + return table, fmt.Errorf("[Content_Types].xml contains an invalid Override") + } + key := strings.ToLower(partName) + if _, exists := table.overrides[key]; exists { + return table, fmt.Errorf("[Content_Types].xml contains duplicate Override for %q", partName) + } + table.overrides[key] = attrs["ContentType"] + } + } + if !rootSeen { + return table, fmt.Errorf("[Content_Types].xml is empty") + } + return table, nil +} + +func ooxmlSafePackageTarget(target, targetMode string) (string, error) { + if targetMode != "" && !strings.EqualFold(targetMode, "Internal") { + return "", fmt.Errorf("officeDocument target must be internal") + } + return ooxmlSafePartPath(target, strings.HasPrefix(target, "/")) +} + +func ooxmlSafePartName(partName string) (string, error) { + if !strings.HasPrefix(partName, "/") { + return "", fmt.Errorf("OPC part name must be absolute") + } + return ooxmlSafePartPath(partName, true) +} + +func ooxmlSafePartPath(raw string, absolute bool) (string, error) { + if raw == "" || strings.ContainsAny(raw, "\\\x00") { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + parsed, err := url.Parse(raw) + if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Opaque != "" || parsed.RawQuery != "" || parsed.Fragment != "" { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + decoded, err := url.PathUnescape(parsed.EscapedPath()) + if err != nil || strings.ContainsAny(decoded, "\\\x00") { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + if absolute != strings.HasPrefix(decoded, "/") { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + decoded = strings.TrimPrefix(decoded, "/") + if decoded == "" || strings.HasSuffix(decoded, "/") { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + for _, segment := range strings.Split(decoded, "/") { + if segment == "" || segment == "." || segment == ".." { + return "", fmt.Errorf("unsafe OPC part path %q", raw) + } + } + return decoded, nil +} + +func ooxmlUniquePart(zr *zip.Reader, name string) (*zip.File, bool, error) { + var found *zip.File + for _, file := range zr.File { + if file.Name != name { + continue + } + if found != nil { + return nil, false, fmt.Errorf("duplicate OPC metadata part %s", name) + } + found = file + } + return found, found != nil, nil +} + +func ooxmlUniquePartFold(zr *zip.Reader, name string) (*zip.File, bool, error) { + var found *zip.File + for _, file := range zr.File { + if !strings.EqualFold(file.Name, name) { + continue + } + if found != nil { + return nil, false, fmt.Errorf("duplicate OPC part %s", name) + } + found = file + } + return found, found != nil, nil } // ooxmlCheckParts 校验容器与必备正文部件存在、XML 合法、命名空间前缀齐备 @@ -538,9 +851,10 @@ func ooxmlPart(zr *zip.Reader, name string) (*zip.File, error) { // ooxmlRel 是 rels 部件里的一条关系:Id、类型 URI 与目标(原样保留相对形式)。 type ooxmlRel struct { - id string - typ string - target string + id string + typ string + target string + targetMode string } // ooxmlRels 解析 part 的关系表(