pax_global_header00006660000000000000000000000064145512234450014517gustar00rootroot0000000000000052 comment=aa22af2c60985e3b557b2a2f793e0d415460f64e golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/000077500000000000000000000000001455122344500241145ustar00rootroot00000000000000golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/LICENSE000066400000000000000000000261351455122344500251300ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/README.md000066400000000000000000000055571455122344500254070ustar00rootroot00000000000000# go-fuzz-headers This repository contains various helper functions for go fuzzing. It is mostly used in combination with [go-fuzz](https://github.com/dvyukov/go-fuzz), but compatibility with fuzzing in the standard library will also be supported. Any coverage guided fuzzing engine that provides an array or slice of bytes can be used with go-fuzz-headers. ## Usage Using go-fuzz-headers is easy. First create a new consumer with the bytes provided by the fuzzing engine: ```go import ( fuzz "github.com/AdaLogics/go-fuzz-headers" ) data := []byte{'R', 'a', 'n', 'd', 'o', 'm'} f := fuzz.NewConsumer(data) ``` This creates a `Consumer` that consumes the bytes of the input as it uses them to fuzz different types. After that, `f` can be used to easily create fuzzed instances of different types. Below are some examples: ### Structs One of the most useful features of go-fuzz-headers is its ability to fill structs with the data provided by the fuzzing engine. This is done with a single line: ```go type Person struct { Name string Age int } p := Person{} // Fill p with values based on the data provided by the fuzzing engine: err := f.GenerateStruct(&p) ``` This includes nested structs too. In this example, the fuzz Consumer will also insert values in `p.BestFriend`: ```go type PersonI struct { Name string Age int BestFriend PersonII } type PersonII struct { Name string Age int } p := PersonI{} err := f.GenerateStruct(&p) ``` If the consumer should insert values for unexported fields as well as exported, this can be enabled with: ```go f.AllowUnexportedFields() ``` ...and disabled with: ```go f.DisallowUnexportedFields() ``` ### Other types: Other useful APIs: ```go createdString, err := f.GetString() // Gets a string createdInt, err := f.GetInt() // Gets an integer createdByte, err := f.GetByte() // Gets a byte createdBytes, err := f.GetBytes() // Gets a byte slice createdBool, err := f.GetBool() // Gets a boolean err := f.FuzzMap(target_map) // Fills a map createdTarBytes, err := f.TarBytes() // Gets bytes of a valid tar archive err := f.CreateFiles(inThisDir) // Fills inThisDir with files createdString, err := f.GetStringFrom("anyCharInThisString", ofThisLength) // Gets a string that consists of chars from "anyCharInThisString" and has the exact length "ofThisLength" ``` Most APIs are added as they are needed. ## Projects that use go-fuzz-headers - [runC](https://github.com/opencontainers/runc) - [Istio](https://github.com/istio/istio) - [Vitess](https://github.com/vitessio/vitess) - [Containerd](https://github.com/containerd/containerd) Feel free to add your own project to the list, if you use go-fuzz-headers to fuzz it. ## Status The project is under development and will be updated regularly. ## References go-fuzz-headers' approach to fuzzing structs is strongly inspired by [gofuzz](https://github.com/google/gofuzz).golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/bytesource/000077500000000000000000000000001455122344500263005ustar00rootroot00000000000000golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/bytesource/bytesource.go000066400000000000000000000037771455122344500310310ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bytesource import ( "bytes" "encoding/binary" "io" "math/rand" ) type ByteSource struct { *bytes.Reader fallback rand.Source } // New returns a new ByteSource from a given slice of bytes. func New(input []byte) *ByteSource { s := &ByteSource{ Reader: bytes.NewReader(input), fallback: rand.NewSource(0), } if len(input) > 0 { s.fallback = rand.NewSource(int64(s.consumeUint64())) } return s } func (s *ByteSource) Uint64() uint64 { // Return from input if it was not exhausted. if s.Len() > 0 { return s.consumeUint64() } // Input was exhausted, return random number from fallback (in this case fallback should not be // nil). Try first having a Uint64 output (Should work in current rand implementation), // otherwise return a conversion of Int63. if s64, ok := s.fallback.(rand.Source64); ok { return s64.Uint64() } return uint64(s.fallback.Int63()) } func (s *ByteSource) Int63() int64 { return int64(s.Uint64() >> 1) } func (s *ByteSource) Seed(seed int64) { s.fallback = rand.NewSource(seed) s.Reader = bytes.NewReader(nil) } // consumeUint64 reads 8 bytes from the input and convert them to a uint64. It assumes that the the // bytes reader is not empty. func (s *ByteSource) consumeUint64() uint64 { var bytes [8]byte _, err := s.Read(bytes[:]) if err != nil && err != io.EOF { panic("failed reading source") // Should not happen. } return binary.BigEndian.Uint64(bytes[:]) } golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/consumer.go000066400000000000000000000540661455122344500263110ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders import ( "archive/tar" "bytes" "encoding/binary" "errors" "fmt" "io" "math" "os" "path/filepath" "reflect" "strconv" "strings" "time" "unsafe" ) var ( MaxTotalLen uint32 = 2000000 maxDepth = 100 ) func SetMaxTotalLen(newLen uint32) { MaxTotalLen = newLen } type ConsumeFuzzer struct { data []byte dataTotal uint32 CommandPart []byte RestOfArray []byte NumberOfCalls int position uint32 fuzzUnexportedFields bool curDepth int Funcs map[reflect.Type]reflect.Value } func IsDivisibleBy(n int, divisibleby int) bool { return (n % divisibleby) == 0 } func NewConsumer(fuzzData []byte) *ConsumeFuzzer { return &ConsumeFuzzer{ data: fuzzData, dataTotal: uint32(len(fuzzData)), Funcs: make(map[reflect.Type]reflect.Value), curDepth: 0, position: uint32(0), } } func (f *ConsumeFuzzer) Split(minCalls, maxCalls int) error { if f.dataTotal == 0 { return errors.New("could not split") } numberOfCalls := int(f.data[0]) if numberOfCalls < minCalls || numberOfCalls > maxCalls { return errors.New("bad number of calls") } if int(f.dataTotal) < numberOfCalls+numberOfCalls+1 { return errors.New("length of data does not match required parameters") } // Define part 2 and 3 of the data array commandPart := f.data[1 : numberOfCalls+1] restOfArray := f.data[numberOfCalls+1:] // Just a small check. It is necessary if len(commandPart) != numberOfCalls { return errors.New("length of commandPart does not match number of calls") } // Check if restOfArray is divisible by numberOfCalls if !IsDivisibleBy(len(restOfArray), numberOfCalls) { return errors.New("length of commandPart does not match number of calls") } f.CommandPart = commandPart f.RestOfArray = restOfArray f.NumberOfCalls = numberOfCalls return nil } func (f *ConsumeFuzzer) AllowUnexportedFields() { f.fuzzUnexportedFields = true } func (f *ConsumeFuzzer) DisallowUnexportedFields() { f.fuzzUnexportedFields = false } func (f *ConsumeFuzzer) GenerateStruct(targetStruct interface{}) error { e := reflect.ValueOf(targetStruct).Elem() return f.fuzzStruct(e, false) } func (f *ConsumeFuzzer) setCustom(v reflect.Value) error { // First: see if we have a fuzz function for it. doCustom, ok := f.Funcs[v.Type()] if !ok { return fmt.Errorf("could not find a custom function") } switch v.Kind() { case reflect.Ptr: if v.IsNil() { if !v.CanSet() { return fmt.Errorf("could not use a custom function") } v.Set(reflect.New(v.Type().Elem())) } case reflect.Map: if v.IsNil() { if !v.CanSet() { return fmt.Errorf("could not use a custom function") } v.Set(reflect.MakeMap(v.Type())) } default: return fmt.Errorf("could not use a custom function") } verr := doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ F: f, })}) // check if we return an error if verr[0].IsNil() { return nil } return fmt.Errorf("could not use a custom function") } func (f *ConsumeFuzzer) fuzzStruct(e reflect.Value, customFunctions bool) error { if f.curDepth >= maxDepth { // return err or nil here? return nil } f.curDepth++ defer func() { f.curDepth-- }() // We check if we should check for custom functions if customFunctions && e.IsValid() && e.CanAddr() { err := f.setCustom(e.Addr()) if err != nil { return err } } //fmt.Println("HEere1", e.Kind()) switch e.Kind() { case reflect.Struct: for i := 0; i < e.NumField(); i++ { var v reflect.Value //fmt.Println(e.Type().Field(i).Name, "position: ", f.position, "data: ", f.data[f.position:f.position+20]) //fmt.Printf("%s: \n", e.Type().Field(i).Name) // Check if field is optional jsonTag := e.Type().Field(i).Tag.Get("json") if strings.Contains(jsonTag, ",omitempty") { // field is optional //fmt.Println("Checking whether optional") shouldSkip, err := f.GetBool() if err != nil { return err } //fmt.Println("shouldSkip: ", shouldSkip) if shouldSkip { continue } } if !e.Field(i).CanSet() { if f.fuzzUnexportedFields { v = reflect.NewAt(e.Field(i).Type(), unsafe.Pointer(e.Field(i).UnsafeAddr())).Elem() } if err := f.fuzzStruct(v, customFunctions); err != nil { return err } } else { v = e.Field(i) if err := f.fuzzStruct(v, customFunctions); err != nil { return err } } } case reflect.String: //fmt.Println("In GetString") str, err := f.GetString() if err != nil { return err } if e.CanSet() { e.SetString(str) } case reflect.Slice: var maxElements uint32 // Byte slices should not be restricted if e.Type().String() == "[]uint8" { maxElements = 10000000 } else { maxElements = 50 } randQty, err := f.GetUint32() if err != nil { return err } numOfElements := randQty % maxElements if (f.dataTotal - f.position) < numOfElements { numOfElements = f.dataTotal - f.position } uu := reflect.MakeSlice(e.Type(), int(numOfElements), int(numOfElements)) for i := 0; i < int(numOfElements); i++ { // If we have more than 10, then we can proceed with that. if err := f.fuzzStruct(uu.Index(i), customFunctions); err != nil { if i >= 10 { if e.CanSet() { e.Set(uu) } return nil } else { return err } } } if e.CanSet() { e.Set(uu) } case reflect.Uint16: newInt, err := f.GetUint16() if err != nil { return err } if e.CanSet() { e.SetUint(uint64(newInt)) } case reflect.Uint32: newInt, err := f.GetUint32() if err != nil { return err } if e.CanSet() { e.SetUint(uint64(newInt)) } case reflect.Uint64: newInt, err := f.GetInt() if err != nil { return err } if e.CanSet() { e.SetUint(uint64(newInt)) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: //fmt.Println("INT position: ", f.position, f.data[f.position:f.position+10], int(f.data[f.position])) newInt, err := f.GetInt() if err != nil { return err } //fmt.Println("Second pos: f.position ", f.position) if e.CanSet() { e.SetInt(int64(newInt)) } case reflect.Float32: newFloat, err := f.GetFloat32() if err != nil { return err } if e.CanSet() { e.SetFloat(float64(newFloat)) } case reflect.Float64: newFloat, err := f.GetFloat64() if err != nil { return err } if e.CanSet() { e.SetFloat(float64(newFloat)) } case reflect.Map: //fmt.Println("MAP position: ", f.position, f.data[f.position:f.position+10], int(f.data[f.position])) if e.CanSet() { e.Set(reflect.MakeMap(e.Type())) const maxElements = 50 randQty, err := f.GetInt() if err != nil { return err } numOfElements := randQty % maxElements for i := 0; i < numOfElements; i++ { key := reflect.New(e.Type().Key()).Elem() if err := f.fuzzStruct(key, customFunctions); err != nil { return err } val := reflect.New(e.Type().Elem()).Elem() if err = f.fuzzStruct(val, customFunctions); err != nil { return err } e.SetMapIndex(key, val) } } case reflect.Ptr: if e.CanSet() { e.Set(reflect.New(e.Type().Elem())) if err := f.fuzzStruct(e.Elem(), customFunctions); err != nil { return err } return nil } case reflect.Uint8: b, err := f.GetByte() if err != nil { return err } if e.CanSet() { e.SetUint(uint64(b)) } case reflect.Bool: b, err := f.GetBool() if err != nil { return err } if e.CanSet() { e.SetBool(b) } } return nil } func (f *ConsumeFuzzer) GetStringArray() (reflect.Value, error) { // The max size of the array: const max uint32 = 20 arraySize := f.position if arraySize > max { arraySize = max } stringArray := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf("string")), int(arraySize), int(arraySize)) if f.position+arraySize >= f.dataTotal { return stringArray, errors.New("could not make string array") } for i := 0; i < int(arraySize); i++ { stringSize := uint32(f.data[f.position]) if f.position+stringSize >= f.dataTotal { return stringArray, nil } stringToAppend := string(f.data[f.position : f.position+stringSize]) strVal := reflect.ValueOf(stringToAppend) stringArray = reflect.Append(stringArray, strVal) f.position += stringSize } return stringArray, nil } func (f *ConsumeFuzzer) GetInt() (int, error) { if f.position >= f.dataTotal { return 0, errors.New("not enough bytes to create int") } returnInt := int(f.data[f.position]) //fmt.Println("returnInt: ", returnInt) f.position++ return returnInt, nil } func (f *ConsumeFuzzer) GetByte() (byte, error) { if f.position >= f.dataTotal { return 0x00, errors.New("not enough bytes to get byte") } returnByte := f.data[f.position] f.position++ return returnByte, nil } func (f *ConsumeFuzzer) GetNBytes(numberOfBytes int) ([]byte, error) { if f.position >= f.dataTotal { return nil, errors.New("not enough bytes to get byte") } returnBytes := make([]byte, 0, numberOfBytes) for i := 0; i < numberOfBytes; i++ { newByte, err := f.GetByte() if err != nil { return nil, err } returnBytes = append(returnBytes, newByte) } return returnBytes, nil } func (f *ConsumeFuzzer) GetUint16() (uint16, error) { u16, err := f.GetNBytes(2) if err != nil { return 0, err } return binary.BigEndian.Uint16(u16), nil } func (f *ConsumeFuzzer) GetUint32() (uint32, error) { u32, err := f.GetNBytes(4) if err != nil { return 0, err } return binary.BigEndian.Uint32(u32), nil } func (f *ConsumeFuzzer) GetUint64() (uint64, error) { u64, err := f.GetNBytes(8) if err != nil { return 0, err } return binary.BigEndian.Uint64(u64), nil } func (f *ConsumeFuzzer) GetBytes() ([]byte, error) { var length uint32 var err error length, err = f.GetUint32() if err != nil { return nil, errors.New("not enough bytes to create byte array") } if length == 0 { length = 30 } bytesLeft := f.dataTotal - f.position if bytesLeft <= 0 { return nil, errors.New("not enough bytes to create byte array") } // If the length is the same as bytes left, we will not overflow // the remaining bytes. if length != bytesLeft { length = length % bytesLeft } byteBegin := f.position if byteBegin+length < byteBegin { return nil, errors.New("numbers overflow") } f.position = byteBegin + length return f.data[byteBegin:f.position], nil } func (f *ConsumeFuzzer) GetString() (string, error) { if f.position >= f.dataTotal { return "nil", errors.New("not enough bytes to create string") } //fmt.Println("f.position:", f.position) length, err := f.GetUint32() if err != nil { return "nil", errors.New("not enough bytes to create string") } //fmt.Println("length: ", length) if f.position > MaxTotalLen { return "nil", errors.New("created too large a string") } byteBegin := f.position if byteBegin >= f.dataTotal { return "nil", errors.New("not enough bytes to create string") } if byteBegin+length > f.dataTotal { return "nil", errors.New("not enough bytes to create string") } if byteBegin > byteBegin+length { return "nil", errors.New("numbers overflow") } f.position = byteBegin + length //fmt.Println(string(f.data[byteBegin:f.position])) return string(f.data[byteBegin:f.position]), nil } func (f *ConsumeFuzzer) GetBool() (bool, error) { if f.position >= f.dataTotal { return false, errors.New("not enough bytes to create bool") } if IsDivisibleBy(int(f.data[f.position]), 2) { f.position++ return true, nil } else { f.position++ return false, nil } } func (f *ConsumeFuzzer) FuzzMap(m interface{}) error { return f.GenerateStruct(m) } func returnTarBytes(buf []byte) ([]byte, error) { return buf, nil // Count files var fileCounter int tr := tar.NewReader(bytes.NewReader(buf)) for { _, err := tr.Next() if err == io.EOF { break } if err != nil { return nil, err } fileCounter++ } if fileCounter >= 1 { return buf, nil } return nil, fmt.Errorf("not enough files were created\n") } func setTarHeaderFormat(hdr *tar.Header, f *ConsumeFuzzer) error { ind, err := f.GetInt() if err != nil { hdr.Format = tar.FormatGNU //return nil } switch ind % 4 { case 0: hdr.Format = tar.FormatUnknown case 1: hdr.Format = tar.FormatUSTAR case 2: hdr.Format = tar.FormatPAX case 3: hdr.Format = tar.FormatGNU } return nil } func setTarHeaderTypeflag(hdr *tar.Header, f *ConsumeFuzzer) error { ind, err := f.GetInt() if err != nil { return err } switch ind % 13 { case 0: hdr.Typeflag = tar.TypeReg case 1: hdr.Typeflag = tar.TypeLink linkname, err := f.GetString() if err != nil { return err } hdr.Linkname = linkname case 2: hdr.Typeflag = tar.TypeSymlink linkname, err := f.GetString() if err != nil { return err } hdr.Linkname = linkname case 3: hdr.Typeflag = tar.TypeChar case 4: hdr.Typeflag = tar.TypeBlock case 5: hdr.Typeflag = tar.TypeDir case 6: hdr.Typeflag = tar.TypeFifo case 7: hdr.Typeflag = tar.TypeCont case 8: hdr.Typeflag = tar.TypeXHeader case 9: hdr.Typeflag = tar.TypeXGlobalHeader case 10: hdr.Typeflag = tar.TypeGNUSparse case 11: hdr.Typeflag = tar.TypeGNULongName case 12: hdr.Typeflag = tar.TypeGNULongLink } return nil } func (f *ConsumeFuzzer) createTarFileBody() ([]byte, error) { return f.GetBytes() /*length, err := f.GetUint32() if err != nil { return nil, errors.New("not enough bytes to create byte array") } // A bit of optimization to attempt to create a file body // when we don't have as many bytes left as "length" remainingBytes := f.dataTotal - f.position if remainingBytes <= 0 { return nil, errors.New("created too large a string") } if f.position+length > MaxTotalLen { return nil, errors.New("created too large a string") } byteBegin := f.position if byteBegin >= f.dataTotal { return nil, errors.New("not enough bytes to create byte array") } if length == 0 { return nil, errors.New("zero-length is not supported") } if byteBegin+length >= f.dataTotal { return nil, errors.New("not enough bytes to create byte array") } if byteBegin+length < byteBegin { return nil, errors.New("numbers overflow") } f.position = byteBegin + length return f.data[byteBegin:f.position], nil*/ } // getTarFileName is similar to GetString(), but creates string based // on the length of f.data to reduce the likelihood of overflowing // f.data. func (f *ConsumeFuzzer) getTarFilename() (string, error) { return f.GetString() /*length, err := f.GetUint32() if err != nil { return "nil", errors.New("not enough bytes to create string") } // A bit of optimization to attempt to create a file name // when we don't have as many bytes left as "length" remainingBytes := f.dataTotal - f.position if remainingBytes <= 0 { return "nil", errors.New("created too large a string") } if f.position > MaxTotalLen { return "nil", errors.New("created too large a string") } byteBegin := f.position if byteBegin >= f.dataTotal { return "nil", errors.New("not enough bytes to create string") } if byteBegin+length > f.dataTotal { return "nil", errors.New("not enough bytes to create string") } if byteBegin > byteBegin+length { return "nil", errors.New("numbers overflow") } f.position = byteBegin + length return string(f.data[byteBegin:f.position]), nil*/ } type TarFile struct { Hdr *tar.Header Body []byte } // TarBytes returns valid bytes for a tar archive func (f *ConsumeFuzzer) TarBytes() ([]byte, error) { numberOfFiles, err := f.GetInt() if err != nil { return nil, err } var tarFiles []*TarFile tarFiles = make([]*TarFile, 0) const maxNoOfFiles = 100 for i := 0; i < numberOfFiles%maxNoOfFiles; i++ { var filename string var filebody []byte var sec, nsec int var err error filename, err = f.getTarFilename() if err != nil { var sb strings.Builder sb.WriteString("file-") sb.WriteString(strconv.Itoa(i)) filename = sb.String() } filebody, err = f.createTarFileBody() if err != nil { var sb strings.Builder sb.WriteString("filebody-") sb.WriteString(strconv.Itoa(i)) filebody = []byte(sb.String()) } sec, err = f.GetInt() if err != nil { sec = 1672531200 // beginning of 2023 } nsec, err = f.GetInt() if err != nil { nsec = 1703980800 // end of 2023 } hdr := &tar.Header{ Name: filename, Size: int64(len(filebody)), Mode: 0o600, ModTime: time.Unix(int64(sec), int64(nsec)), } if err := setTarHeaderTypeflag(hdr, f); err != nil { return []byte(""), err } if err := setTarHeaderFormat(hdr, f); err != nil { return []byte(""), err } tf := &TarFile{ Hdr: hdr, Body: filebody, } tarFiles = append(tarFiles, tf) } var buf bytes.Buffer tw := tar.NewWriter(&buf) defer tw.Close() for _, tf := range tarFiles { tw.WriteHeader(tf.Hdr) tw.Write(tf.Body) } return buf.Bytes(), nil } // This is similar to TarBytes, but it returns a series of // files instead of raw tar bytes. The advantage of this // api is that it is cheaper in terms of cpu power to // modify or check the files in the fuzzer with TarFiles() // because it avoids creating a tar reader. func (f *ConsumeFuzzer) TarFiles() ([]*TarFile, error) { numberOfFiles, err := f.GetInt() if err != nil { return nil, err } var tarFiles []*TarFile tarFiles = make([]*TarFile, 0) const maxNoOfFiles = 100 for i := 0; i < numberOfFiles%maxNoOfFiles; i++ { filename, err := f.getTarFilename() if err != nil { return tarFiles, err } filebody, err := f.createTarFileBody() if err != nil { return tarFiles, err } sec, err := f.GetInt() if err != nil { return tarFiles, err } nsec, err := f.GetInt() if err != nil { return tarFiles, err } hdr := &tar.Header{ Name: filename, Size: int64(len(filebody)), Mode: 0o600, ModTime: time.Unix(int64(sec), int64(nsec)), } if err := setTarHeaderTypeflag(hdr, f); err != nil { hdr.Typeflag = tar.TypeReg } if err := setTarHeaderFormat(hdr, f); err != nil { return tarFiles, err // should not happend } tf := &TarFile{ Hdr: hdr, Body: filebody, } tarFiles = append(tarFiles, tf) } return tarFiles, nil } // CreateFiles creates pseudo-random files in rootDir. // It creates subdirs and places the files there. // It is the callers responsibility to ensure that // rootDir exists. func (f *ConsumeFuzzer) CreateFiles(rootDir string) error { numberOfFiles, err := f.GetInt() if err != nil { return err } maxNumberOfFiles := numberOfFiles % 4000 // This is completely arbitrary if maxNumberOfFiles == 0 { return errors.New("maxNumberOfFiles is nil") } var noOfCreatedFiles int for i := 0; i < maxNumberOfFiles; i++ { // The file to create: fileName, err := f.GetString() if err != nil { if noOfCreatedFiles > 0 { // If files have been created, we don't return an error. break } else { return errors.New("could not get fileName") } } if strings.Contains(fileName, "..") || (len(fileName) > 0 && fileName[0] == 47) || strings.Contains(fileName, "\\") { continue } fullFilePath := filepath.Join(rootDir, fileName) // Find the subdirectory of the file if subDir := filepath.Dir(fileName); subDir != "" && subDir != "." { // create the dir first; avoid going outside the root dir if strings.Contains(subDir, "../") || (len(subDir) > 0 && subDir[0] == 47) || strings.Contains(subDir, "\\") { continue } dirPath := filepath.Join(rootDir, subDir) if _, err := os.Stat(dirPath); os.IsNotExist(err) { err2 := os.MkdirAll(dirPath, 0o777) if err2 != nil { continue } } fullFilePath = filepath.Join(dirPath, fileName) } else { // Create symlink createSymlink, err := f.GetBool() if err != nil { if noOfCreatedFiles > 0 { break } else { return errors.New("could not create the symlink") } } if createSymlink { symlinkTarget, err := f.GetString() if err != nil { return err } err = os.Symlink(symlinkTarget, fullFilePath) if err != nil { return err } // stop loop here, since a symlink needs no further action noOfCreatedFiles++ continue } // We create a normal file fileContents, err := f.GetBytes() if err != nil { if noOfCreatedFiles > 0 { break } else { return errors.New("could not create the file") } } err = os.WriteFile(fullFilePath, fileContents, 0o666) if err != nil { continue } noOfCreatedFiles++ } } return nil } // GetStringFrom returns a string that can only consist of characters // included in possibleChars. It returns an error if the created string // does not have the specified length. func (f *ConsumeFuzzer) GetStringFrom(possibleChars string, length int) (string, error) { if (f.dataTotal - f.position) < uint32(length) { return "", errors.New("not enough bytes to create a string") } output := make([]byte, 0, length) for i := 0; i < length; i++ { charIndex, err := f.GetInt() if err != nil { return string(output), err } output = append(output, possibleChars[charIndex%len(possibleChars)]) } return string(output), nil } func (f *ConsumeFuzzer) GetRune() ([]rune, error) { stringToConvert, err := f.GetString() if err != nil { return []rune("nil"), err } return []rune(stringToConvert), nil } func (f *ConsumeFuzzer) GetFloat32() (float32, error) { u32, err := f.GetNBytes(4) if err != nil { return 0, err } u32BE := binary.BigEndian.Uint32(u32) return math.Float32frombits(u32BE), nil } func (f *ConsumeFuzzer) GetFloat64() (float64, error) { u64, err := f.GetNBytes(8) if err != nil { return 0, err } u64BE := binary.BigEndian.Uint64(u64) return math.Float64frombits(u64BE), nil } func (f *ConsumeFuzzer) CreateSlice(targetSlice interface{}) error { return f.GenerateStruct(targetSlice) } golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/consumer_test.go000066400000000000000000000137321455122344500273430ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders import ( //"archive/tar" //"bytes" //"io" "testing" corev1 "k8s.io/api/core/v1" ) type TestStruct1 struct { Field1 string Field2 string Field3 []byte } type TestStruct2 struct { M map[string]string } func TestMapInStruct(t *testing.T) { data := []byte{0x02, 0x00, 0x00, 0x00, 0x03, 0x41, 0x42, 0x43, 0x00, 0x00, 0x00, 0x03, 0x41, 0x42, 0x43} f := NewConsumer(data) ts := &TestStruct2{} f.GenerateStruct(ts) if _, ok := ts.M["ABC"]; !ok { t.Fatalf("%+v\n", ts) } } func TestStruct_fuzzing1(t *testing.T) { data := []byte{ 0x00, 0x00, 0x00, 0x03, // Length of field 1 0x41, 0x42, 0x43, // Data of field field 1 0x00, 0x00, 0x00, 0x03, // Length of field 2 0x41, 0x42, 0x43, // Data of field 2 0x00, 0x00, 0x00, 0x01, // Length of field 3 0x41, // Data of Field3 } ts1 := TestStruct1{} fuzz1 := NewConsumer(data) err := fuzz1.GenerateStruct(&ts1) if err != nil { t.Errorf("%v", err) } if ts1.Field1 != "ABC" { t.Errorf("ts1.Field1 was %v but should be 'AB'", []byte(ts1.Field1)) } if ts1.Field2 != "ABC" { t.Errorf("ts1.Field2 was %v but should be 'ABC'", ts1.Field2) } if string(ts1.Field3) != "A" { t.Errorf("ts1.Field3 was %v but should be 'A'", ts1.Field3) } } // Tests that we can create long byte slices in structs func TestStruct_fuzzing2(t *testing.T) { data := []byte{ 0x00, 0x00, 0x00, 0x03, // Length field 1 0x41, 0x42, 0x43, // Data of field 1 0x00, 0x00, 0x00, 0x03, // Length of Field2 0x41, 0x42, 0x43, // Content of Field2 0x00, 0x00, 0x00, 0x50, // Length of field3 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // All of this 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // should go 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // into Field3 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, } ts1 := TestStruct1{} fuzz1 := NewConsumer(data) err := fuzz1.GenerateStruct(&ts1) if err != nil { t.Errorf("%v", err) } if ts1.Field1 != "ABC" { t.Errorf("ts1.Field1 was %v but should be 'ABC'", ts1.Field1) } if ts1.Field2 != "ABC" { t.Errorf("ts1.Field2 was %v but should be 'ABC'", ts1.Field2) } if len(ts1.Field3) != 80 { t.Errorf("ts1.Field3 was %v but should be 'ABCD'", ts1.Field3) } } /*func TestTarBytes(t *testing.T) { data := []byte{ 0x01, // number of files 0x00, 0x00, 0x00, 0x08, // Length of first file name 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, // "manifest" 0x00, 0x00, 0x00, 0x09, // Length of file body 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, // file contents 0x04, 0x02, 0x03, 0x00, // type flag 0x01, 0x01, 0x01, 0x01, } f := NewConsumer(data) tb, err := f.TarBytes() if err != nil { t.Fatalf("Fatal: %s", err) } tarReader := tar.NewReader(bytes.NewReader(tb)) for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } if header.Typeflag != 48 { t.Fatalf("typeflag should be 48 (which is a tar.TypeReg) but is %v", header.Typeflag) } switch header.Typeflag { case tar.TypeDir: t.Fatal("Should not be a directory") case tar.TypeReg: if header.Name != "manifest" { t.Fatalf("file name was %s but should be 'manifest'\n", header.Name) } } } }*/ func TestGetUint32(t *testing.T) { data := []byte{ 0x00, 0x00, 0x03, 0x01, } f := NewConsumer(data) i, err := f.GetUint32() if err != nil { t.Fatalf("%v\n", err) } if i != uint32(769) { t.Fatalf("i should be 636 but is %v\n", i) } } func TestGeBytes1(t *testing.T) { data := []byte{ 0x00, 0x00, 0x03, 0x01, } for i := 0; i < 769; i++ { data = append(data, 0x00) } f := NewConsumer(data) b, err := f.GetBytes() if err != nil { t.Fatalf("%v\n", err) } if len(b) != 769 { t.Fatalf("len(b) should be 769 but is %v\n", len(b)) } for i := 0; i < 769; i++ { if b[i] != 0 { t.Fatalf("b[%d] should be 0x00 but is %v\n", i, b[i]) } } } func TestGeBytes2(t *testing.T) { data := []byte{ 0x00, 0x00, 0x03, 0x01, } for i := 0; i < 767; i++ { data = append(data, 0x00) } f := NewConsumer(data) b, err := f.GetBytes() if err != nil { t.Fatalf("%v\n", err) } if len(b) != 2 { t.Fatalf("len(b) should be 2 but is %v\n", len(b)) } for i := 0; i < 2; i++ { if b[i] != 0 { t.Fatalf("b[%d] should be 0x00 but is %v\n", i, b[i]) } } } func TestGeBytes3(t *testing.T) { data := []byte{ 0x00, 0x00, 0x03, 0x01, } for i := 0; i < 500; i++ { data = append(data, 0x00) } f := NewConsumer(data) b, err := f.GetBytes() if err != nil { t.Fatalf("%v\n", err) } if len(b) != 269 { t.Fatalf("len(b) should be 269 but is %v\n", len(b)) } for i := 0; i < 269; i++ { if b[i] != 0 { t.Fatalf("b[%d] should be 0x00 but is %v\n", i, b[i]) } } } func TestGeneratePod(t *testing.T) { pod := &corev1.Pod{} data := []byte{0x01,0x00,0x00,0x00,0x03,0x50,0x06f,0x064, // "Kind: Pod" 0x01,0x00,0x00,0x00,0x02,0x76,0x31, // "APIVersion: v1" 0x00, // Skip ObjectMeta 0x01, // Do not skip Spec } ff := NewConsumer(data) ff.GenerateStruct(pod) t.Log(pod) }golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/funcs.go000066400000000000000000000033141455122344500255620ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders import ( "fmt" "reflect" ) type Continue struct { F *ConsumeFuzzer } func (f *ConsumeFuzzer) AddFuncs(fuzzFuncs []interface{}) { for i := range fuzzFuncs { v := reflect.ValueOf(fuzzFuncs[i]) if v.Kind() != reflect.Func { panic("Need only funcs!") } t := v.Type() if t.NumIn() != 2 || t.NumOut() != 1 { fmt.Println(t.NumIn(), t.NumOut()) panic("Need 2 in and 1 out params. In must be the type. Out must be an error") } argT := t.In(0) switch argT.Kind() { case reflect.Ptr, reflect.Map: default: panic("fuzzFunc must take pointer or map type") } if t.In(1) != reflect.TypeOf(Continue{}) { panic("fuzzFunc's second parameter must be type Continue") } f.Funcs[argT] = v } } func (f *ConsumeFuzzer) GenerateWithCustom(targetStruct interface{}) error { e := reflect.ValueOf(targetStruct).Elem() return f.fuzzStruct(e, true) } func (c Continue) GenerateStruct(targetStruct interface{}) error { return c.F.GenerateStruct(targetStruct) } func (c Continue) GenerateStructWithCustom(targetStruct interface{}) error { return c.F.GenerateWithCustom(targetStruct) } golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/funcs_test.go000066400000000000000000000034761455122344500266320ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders /* import ( "testing" ) type TestStructFuncs1 struct { Field1 string Field2 string Field3 []byte field4 string } type TestStructFuncs2 struct { Field1 []byte } type TestStructFuncs3 struct { Field1 *TestStructFuncs4 Field2 string } type TestStructFuncs4 struct { Field1 string Field2 string } func TestStruct_fuzzing_CustomFuncs1(t *testing.T) { data := []byte{ 0x02, 0x41, 0x42, // Field1 0x03, 0x41, 0x42, 0x43, // Field2 } ts1 := TestStructFuncs3{} fuzz1 := NewConsumer(data) testfuncss := testFuncs() fuzz1.AddFuncs(testfuncss) err := fuzz1.GenerateWithCustom(&ts1) if err != nil { t.Errorf("%v", err) } if ts1.Field1.Field1 != "AB" { t.Errorf("ts1.Field1.Field1 was %v but should be 'AB'", ts1.Field1) } if ts1.Field1.Field2 != "staticString" { t.Errorf("ts1.Field1.Field2 was %v but should be 'staticString'", ts1.Field1) } if ts1.Field2 != "ABC" { t.Errorf("ts1.Field1 was %v but should be 'ABC'", ts1.Field1) } } func testFuncs() []interface{} { return []interface{}{ func(j *TestStructFuncs4, c Continue) error { newString, err := c.F.GetString() if err != nil { return err } j.Field1 = newString j.Field2 = "staticString" return nil }, } } */ golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/go.mod000066400000000000000000000014641455122344500252270ustar00rootroot00000000000000module github.com/AdamKorcz/go-fuzz-headers-1 go 1.20 require k8s.io/api v0.28.1 require ( github.com/go-logr/logr v1.2.4 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect golang.org/x/net v0.13.0 // indirect golang.org/x/text v0.11.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/apimachinery v0.28.1 // indirect k8s.io/klog/v2 v2.100.1 // indirect k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect ) golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/go.sum000066400000000000000000000165361455122344500252620ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.13.0 h1:Nvo8UFsZ8X3BhAC9699Z1j7XQ3rsZnUUm7jfBEk1ueY= golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= k8s.io/api v0.28.1 h1:i+0O8k2NPBCPYaMB+uCkseEbawEt/eFaiRqUx8aB108= k8s.io/api v0.28.1/go.mod h1:uBYwID+66wiL28Kn2tBjBYQdEU0Xk0z5qF8bIBqk/Dg= k8s.io/apimachinery v0.28.1 h1:EJD40og3GizBSV3mkIoXQBsws32okPOy+MkRyzh6nPY= k8s.io/apimachinery v0.28.1/go.mod h1:X0xh/chESs2hP9koe+SdIAcXWcQ+RM5hy0ZynB+yEvw= k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 h1:qY1Ad8PODbnymg2pRbkyMT/ylpTrCM8P2RJ0yroCyIk= k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/seed.go000066400000000000000000000133251455122344500253670ustar00rootroot00000000000000package gofuzzheaders import ( "bytes" //"fmt" "reflect" //"unsafe" "strings" ) type SeedGenerator struct { curDepth int b *bytes.Buffer } func NewSeedGenerator() *SeedGenerator { by := make([]byte, 0) b := bytes.NewBuffer(by) return &SeedGenerator{ b: b, } } func (f *SeedGenerator) GenerateSeed(targetStruct interface{}) ([]byte) { f.GenerateStruct(targetStruct) return f.b.Bytes() } func (f *SeedGenerator) GenerateStruct(targetStruct interface{}) error { e := reflect.ValueOf(targetStruct).Elem() f.fuzzStruct(e, false) return nil } func (f *SeedGenerator) fuzzStruct(e reflect.Value, customFunctions bool) error { if f.curDepth >= maxDepth { // return err or nil here? return nil } f.curDepth++ defer func() { f.curDepth-- }() switch e.Kind() { case reflect.Struct: for i := 0; i < e.NumField(); i++ { //fmt.Println("Field:") if i == 30 { //fmt.Println(f.b.Bytes()) //panic("Stop here") } var v reflect.Value //fmt.Printf("%s: \n", e.Type().Field(i).Name) jsonTag := e.Type().Field(i).Tag.Get("json") if strings.Contains(jsonTag, ",omitempty") { // do not skip: f.b.Write([]byte{0x01}) } if !e.Field(i).CanSet() { if err := f.fuzzStruct(v, customFunctions); err != nil { return err } } else { v = e.Field(i) if err := f.fuzzStruct(v, customFunctions); err != nil { return err } } } case reflect.String: _, err := f.GetString() if err != nil { return err } case reflect.Slice: var maxElements uint32 // Byte slices should not be restricted if e.Type().String() == "[]uint8" { maxElements = 10000000 } else { maxElements = 50 } // Need uint32(2) randQty, err := f.GetUint32() if err != nil { return err } numOfElements := randQty % maxElements uu := reflect.MakeSlice(e.Type(), int(numOfElements), int(numOfElements)) for i := 0; i < int(numOfElements); i++ { // If we have more than 10, then we can proceed with that. if err := f.fuzzStruct(uu.Index(i), customFunctions); err != nil { } } if e.CanSet() { e.Set(uu) } case reflect.Uint16: _, err := f.GetUint16() if err != nil { return err } case reflect.Uint32: _, err := f.GetUint32() if err != nil { return err } case reflect.Uint64: _, err := f.GetInt() if err != nil { return err } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: _, err := f.GetInt() if err != nil { return err } case reflect.Float32: _, err := f.GetFloat32() if err != nil { return err } case reflect.Float64: _, err := f.GetFloat64() if err != nil { return err } case reflect.Map: if e.CanSet() { e.Set(reflect.MakeMap(e.Type())) const maxElements = 50 // int(2): f.b.Write([]byte{0x02}) randQty := 2 numOfElements := randQty % maxElements for i := 0; i < numOfElements; i++ { if i == 2 { } key := reflect.New(e.Type().Key()).Elem() if err := f.fuzzStruct(key, customFunctions); err != nil { return err } val := reflect.New(e.Type().Elem()).Elem() if err := f.fuzzStruct(val, customFunctions); err != nil { return err } } } case reflect.Ptr: if e.CanSet() { e.Set(reflect.New(e.Type().Elem())) if err := f.fuzzStruct(e.Elem(), customFunctions); err != nil { return err } return nil } case reflect.Uint8: _, err := f.GetByte() if err != nil { return err } } return nil } func (f *SeedGenerator) GetStringArray() (reflect.Value, error) { return reflect.Value{}, nil } func (f *SeedGenerator) GetInt() (int, error) { //int(5): f.b.Write([]byte{0x35}) // 5 return int(byte(0x35)), nil } func (f *SeedGenerator) GetByte() (byte, error) { // "a": f.b.Write([]byte{0x61}) return byte(0x61), nil } // Not used for Structs func (f *SeedGenerator) GetNBytes(numberOfBytes int) ([]byte, error) { return []byte{0x00}, nil } func (f *SeedGenerator) GetUint16() (uint16, error) { // should be uint16(2) f.b.Write([]byte{0x00, 0x02}) return uint16(2), nil } func (f *SeedGenerator) GetUint32() (uint32, error) { // should be uint32(2) f.b.Write([]byte{0x00, 0x00, 0x00, 0x02}) return uint32(2), nil } func (f *SeedGenerator) GetUint64() (uint64, error) { // should be uint32(2) f.b.Write([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}) return uint64(2), nil } func (f *SeedGenerator) GetBytes() ([]byte, error) { f.b.Write([]byte{0x00, 0x00, 0x00, 0x03}) // length f.b.Write([]byte{0x41,0x42,0x43}) return []byte{0x00}, nil } func (f *SeedGenerator) GetString() (string, error) { //fmt.Println("Writing string") f.b.Write([]byte{0x00, 0x00, 0x00, 0x03}) // length f.b.Write([]byte{0x41,0x42,0x43}) return "ABC", nil } func (f *SeedGenerator) GetBool() (bool, error) { // true: f.b.Write([]byte{0x00}) return true, nil } // Not needed func (f *SeedGenerator) FuzzMap(m interface{}) error { return nil } func (f *SeedGenerator) TarBytes() ([]byte, error) { return []byte{0x00}, nil } func (f *SeedGenerator) TarFiles() ([]*TarFile, error) { return []*TarFile{nil}, nil } func (f *SeedGenerator) CreateFiles(rootDir string) error { return nil } func (f *SeedGenerator) GetStringFrom(possibleChars string, length int) (string, error) { return "", nil } func (f *SeedGenerator) GetRune() ([]rune, error) { s := "" return []rune(s), nil } func (f *SeedGenerator) GetFloat32() (float32, error) { f.b.Write([]byte{0x00, 0x00, 0x00, 0x04}) f.b.Write([]byte{0x01}) // little endian: false return float32(0), nil } func (f *SeedGenerator) GetFloat64() (float64, error) { f.b.Write([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04}) f.b.Write([]byte{0x01}) // little endian: false return float64(0), nil } func (f *SeedGenerator) CreateSlice(targetSlice interface{}) error { return nil }golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/seed_test.go000066400000000000000000000167231455122344500264330ustar00rootroot00000000000000package gofuzzheaders import ( "fmt" "strings" "os" "testing" corev1 "k8s.io/api/core/v1" ) func TestGenerateSeed(t *testing.T) { pod := &corev1.Pod{} c := NewSeedGenerator() s := c.GenerateSeed(pod) ff := NewConsumer(s) ff.GenerateStruct(pod) //t.Log(err) t.Logf("%+v\n", pod.TypeMeta.Kind) t.Logf("%+v\n", pod.TypeMeta.APIVersion) t.Logf("%+v\n", pod.ObjectMeta.Name) t.Logf("%+v\n", pod.ObjectMeta.GenerateName) t.Logf("%+v\n", pod.ObjectMeta.Namespace) t.Logf("%+v\n", pod.ObjectMeta.SelfLink) t.Logf("%+v\n", pod.ObjectMeta.ResourceVersion) t.Logf("%+v\n", pod.ObjectMeta.Generation) t.Logf("%+v\n", *pod.ObjectMeta.DeletionGracePeriodSeconds) t.Logf("Labels: %+v\n", pod.ObjectMeta.Labels) t.Logf("%+v\n", pod.ObjectMeta.Annotations) t.Logf("%+v\n", pod.ObjectMeta.OwnerReferences) t.Logf("%+v\n", pod.ObjectMeta.Finalizers) t.Logf("OwnerReferences: %+v\n", pod.ObjectMeta.OwnerReferences) t.Logf("Containers: %+v\n", pod.Spec.Containers) //t.Logf("len(pod.Spec.Containers): %d", len(pod.Spec.Containers)) var sw strings.Builder for _, b := range s { sw.WriteString(fmt.Sprintf("0x%X ", b)) } //t.Log(s[0:2000]) t.Log(len(sw.String())) // creates a seed file: f, err := os.Create("seed1") if err != nil { panic(err) } defer f.Close() f.WriteString(sw.String()) t.Fatal("Done") } func TestPod(t *testing.T) { data := []byte{0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x1, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x2, 0x35, 0x61, 0x35, 0x61, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x1, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x2, 0x35, 0x61, 0x35, 0x61, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x1, 0x35, 0x1, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x2, 0x35, 0x61, 0x35, 0x61, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x61, 0x61, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x0, 0x0, 0x0, 0x2, 0x35, 0x61, 0x35, 0x61, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x61, 0x61, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x35, 0x0, 0x0, 0x0, 0x2, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x35, 0x1, 0x35, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x35, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1, 0x0, 0x0, 0x0, 0x3, 0x41, 0x42, 0x43, 0x1} f := NewConsumer(data) pod := &corev1.Pod{} f.GenerateStruct(pod) if pod.TypeMeta.Kind != "ABC" { t.Fatal("err") } if pod.TypeMeta.APIVersion != "ABC" { t.Fatal("err") } if pod.ObjectMeta.Name != "ABC" { t.Fatal("err") } if pod.ObjectMeta.GenerateName != "ABC" { t.Fatal("err") } if pod.ObjectMeta.Namespace != "ABC" { t.Fatal("err") } if pod.ObjectMeta.SelfLink != "ABC" { t.Fatal("err") } if pod.ObjectMeta.ResourceVersion != "ABC" { t.Fatal("err") } if pod.ObjectMeta.Generation != 53 { t.Fatal("err") } if *pod.ObjectMeta.DeletionGracePeriodSeconds != 0 { t.Fatal("err") } t.Logf("%+v\n", *pod.ObjectMeta.DeletionGracePeriodSeconds) t.Logf("Labels: %+v\n", pod.ObjectMeta.Labels) t.Logf("%+v\n", pod.ObjectMeta.Annotations) t.Logf("%+v\n", pod.ObjectMeta.OwnerReferences) t.Logf("%+v\n", pod.ObjectMeta.Finalizers) }golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/sql.go000066400000000000000000000424201455122344500252440ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders import ( "fmt" "strings" ) // returns a keyword by index func getKeyword(f *ConsumeFuzzer) (string, error) { index, err := f.GetInt() if err != nil { return keywords[0], err } for i, k := range keywords { if i == index { return k, nil } } return keywords[0], fmt.Errorf("could not get a kw") } // Simple utility function to check if a string // slice contains a string. func containsString(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } // These keywords are used specifically for fuzzing Vitess var keywords = []string{ "accessible", "action", "add", "after", "against", "algorithm", "all", "alter", "always", "analyze", "and", "as", "asc", "asensitive", "auto_increment", "avg_row_length", "before", "begin", "between", "bigint", "binary", "_binary", "_utf8mb4", "_utf8", "_latin1", "bit", "blob", "bool", "boolean", "both", "by", "call", "cancel", "cascade", "cascaded", "case", "cast", "channel", "change", "char", "character", "charset", "check", "checksum", "coalesce", "code", "collate", "collation", "column", "columns", "comment", "committed", "commit", "compact", "complete", "compressed", "compression", "condition", "connection", "constraint", "continue", "convert", "copy", "cume_dist", "substr", "substring", "create", "cross", "csv", "current_date", "current_time", "current_timestamp", "current_user", "cursor", "data", "database", "databases", "day", "day_hour", "day_microsecond", "day_minute", "day_second", "date", "datetime", "dec", "decimal", "declare", "default", "definer", "delay_key_write", "delayed", "delete", "dense_rank", "desc", "describe", "deterministic", "directory", "disable", "discard", "disk", "distinct", "distinctrow", "div", "double", "do", "drop", "dumpfile", "duplicate", "dynamic", "each", "else", "elseif", "empty", "enable", "enclosed", "encryption", "end", "enforced", "engine", "engines", "enum", "error", "escape", "escaped", "event", "exchange", "exclusive", "exists", "exit", "explain", "expansion", "export", "extended", "extract", "false", "fetch", "fields", "first", "first_value", "fixed", "float", "float4", "float8", "flush", "for", "force", "foreign", "format", "from", "full", "fulltext", "function", "general", "generated", "geometry", "geometrycollection", "get", "global", "gtid_executed", "grant", "group", "grouping", "groups", "group_concat", "having", "header", "high_priority", "hosts", "hour", "hour_microsecond", "hour_minute", "hour_second", "if", "ignore", "import", "in", "index", "indexes", "infile", "inout", "inner", "inplace", "insensitive", "insert", "insert_method", "int", "int1", "int2", "int3", "int4", "int8", "integer", "interval", "into", "io_after_gtids", "is", "isolation", "iterate", "invoker", "join", "json", "json_table", "key", "keys", "keyspaces", "key_block_size", "kill", "lag", "language", "last", "last_value", "last_insert_id", "lateral", "lead", "leading", "leave", "left", "less", "level", "like", "limit", "linear", "lines", "linestring", "load", "local", "localtime", "localtimestamp", "lock", "logs", "long", "longblob", "longtext", "loop", "low_priority", "manifest", "master_bind", "match", "max_rows", "maxvalue", "mediumblob", "mediumint", "mediumtext", "memory", "merge", "microsecond", "middleint", "min_rows", "minute", "minute_microsecond", "minute_second", "mod", "mode", "modify", "modifies", "multilinestring", "multipoint", "multipolygon", "month", "name", "names", "natural", "nchar", "next", "no", "none", "not", "no_write_to_binlog", "nth_value", "ntile", "null", "numeric", "of", "off", "offset", "on", "only", "open", "optimize", "optimizer_costs", "option", "optionally", "or", "order", "out", "outer", "outfile", "over", "overwrite", "pack_keys", "parser", "partition", "partitioning", "password", "percent_rank", "plugins", "point", "polygon", "precision", "primary", "privileges", "processlist", "procedure", "query", "quarter", "range", "rank", "read", "reads", "read_write", "real", "rebuild", "recursive", "redundant", "references", "regexp", "relay", "release", "remove", "rename", "reorganize", "repair", "repeat", "repeatable", "replace", "require", "resignal", "restrict", "return", "retry", "revert", "revoke", "right", "rlike", "rollback", "row", "row_format", "row_number", "rows", "s3", "savepoint", "schema", "schemas", "second", "second_microsecond", "security", "select", "sensitive", "separator", "sequence", "serializable", "session", "set", "share", "shared", "show", "signal", "signed", "slow", "smallint", "spatial", "specific", "sql", "sqlexception", "sqlstate", "sqlwarning", "sql_big_result", "sql_cache", "sql_calc_found_rows", "sql_no_cache", "sql_small_result", "ssl", "start", "starting", "stats_auto_recalc", "stats_persistent", "stats_sample_pages", "status", "storage", "stored", "straight_join", "stream", "system", "vstream", "table", "tables", "tablespace", "temporary", "temptable", "terminated", "text", "than", "then", "time", "timestamp", "timestampadd", "timestampdiff", "tinyblob", "tinyint", "tinytext", "to", "trailing", "transaction", "tree", "traditional", "trigger", "triggers", "true", "truncate", "uncommitted", "undefined", "undo", "union", "unique", "unlock", "unsigned", "update", "upgrade", "usage", "use", "user", "user_resources", "using", "utc_date", "utc_time", "utc_timestamp", "validation", "values", "variables", "varbinary", "varchar", "varcharacter", "varying", "vgtid_executed", "virtual", "vindex", "vindexes", "view", "vitess", "vitess_keyspaces", "vitess_metadata", "vitess_migration", "vitess_migrations", "vitess_replication_status", "vitess_shards", "vitess_tablets", "vschema", "warnings", "when", "where", "while", "window", "with", "without", "work", "write", "xor", "year", "year_month", "zerofill", } // Keywords that could get an additional keyword var needCustomString = []string{ "DISTINCTROW", "FROM", // Select keywords: "GROUP BY", "HAVING", "WINDOW", "FOR", "ORDER BY", "LIMIT", "INTO", "PARTITION", "AS", // Insert Keywords: "ON DUPLICATE KEY UPDATE", "WHERE", "LIMIT", // Delete keywords "INFILE", "INTO TABLE", "CHARACTER SET", // Load keywords "TERMINATED BY", "ENCLOSED BY", "ESCAPED BY", "STARTING BY", "TERMINATED BY", "STARTING BY", "IGNORE", "VALUE", "VALUES", // Replace tokens "SET", // Update tokens "ENGINE =", // Drop tokens "DEFINER =", "ON SCHEDULE", "RENAME TO", // Alter tokens "COMMENT", "DO", "INITIAL_SIZE = ", "OPTIONS", } var alterTableTokens = [][]string{ {"CUSTOM_FUZZ_STRING"}, {"CUSTOM_ALTTER_TABLE_OPTIONS"}, {"PARTITION_OPTIONS_FOR_ALTER_TABLE"}, } var alterTokens = [][]string{ { "DATABASE", "SCHEMA", "DEFINER = ", "EVENT", "FUNCTION", "INSTANCE", "LOGFILE GROUP", "PROCEDURE", "SERVER", }, {"CUSTOM_FUZZ_STRING"}, { "ON SCHEDULE", "ON COMPLETION PRESERVE", "ON COMPLETION NOT PRESERVE", "ADD UNDOFILE", "OPTIONS", }, {"RENAME TO", "INITIAL_SIZE = "}, {"ENABLE", "DISABLE", "DISABLE ON SLAVE", "ENGINE"}, {"COMMENT"}, {"DO"}, } var setTokens = [][]string{ {"CHARACTER SET", "CHARSET", "CUSTOM_FUZZ_STRING", "NAMES"}, {"CUSTOM_FUZZ_STRING", "DEFAULT", "="}, {"CUSTOM_FUZZ_STRING"}, } var dropTokens = [][]string{ {"TEMPORARY", "UNDO"}, { "DATABASE", "SCHEMA", "EVENT", "INDEX", "LOGFILE GROUP", "PROCEDURE", "FUNCTION", "SERVER", "SPATIAL REFERENCE SYSTEM", "TABLE", "TABLESPACE", "TRIGGER", "VIEW", }, {"IF EXISTS"}, {"CUSTOM_FUZZ_STRING"}, {"ON", "ENGINE = ", "RESTRICT", "CASCADE"}, } var renameTokens = [][]string{ {"TABLE"}, {"CUSTOM_FUZZ_STRING"}, {"TO"}, {"CUSTOM_FUZZ_STRING"}, } var truncateTokens = [][]string{ {"TABLE"}, {"CUSTOM_FUZZ_STRING"}, } var createTokens = [][]string{ {"OR REPLACE", "TEMPORARY", "UNDO"}, // For create spatial reference system { "UNIQUE", "FULLTEXT", "SPATIAL", "ALGORITHM = UNDEFINED", "ALGORITHM = MERGE", "ALGORITHM = TEMPTABLE", }, { "DATABASE", "SCHEMA", "EVENT", "FUNCTION", "INDEX", "LOGFILE GROUP", "PROCEDURE", "SERVER", "SPATIAL REFERENCE SYSTEM", "TABLE", "TABLESPACE", "TRIGGER", "VIEW", }, {"IF NOT EXISTS"}, {"CUSTOM_FUZZ_STRING"}, } /* // For future use. var updateTokens = [][]string{ {"LOW_PRIORITY"}, {"IGNORE"}, {"SET"}, {"WHERE"}, {"ORDER BY"}, {"LIMIT"}, } */ var replaceTokens = [][]string{ {"LOW_PRIORITY", "DELAYED"}, {"INTO"}, {"PARTITION"}, {"CUSTOM_FUZZ_STRING"}, {"VALUES", "VALUE"}, } var loadTokens = [][]string{ {"DATA"}, {"LOW_PRIORITY", "CONCURRENT", "LOCAL"}, {"INFILE"}, {"REPLACE", "IGNORE"}, {"INTO TABLE"}, {"PARTITION"}, {"CHARACTER SET"}, {"FIELDS", "COLUMNS"}, {"TERMINATED BY"}, {"OPTIONALLY"}, {"ENCLOSED BY"}, {"ESCAPED BY"}, {"LINES"}, {"STARTING BY"}, {"TERMINATED BY"}, {"IGNORE"}, {"LINES", "ROWS"}, {"CUSTOM_FUZZ_STRING"}, } // These Are everything that comes after "INSERT" var insertTokens = [][]string{ {"LOW_PRIORITY", "DELAYED", "HIGH_PRIORITY", "IGNORE"}, {"INTO"}, {"PARTITION"}, {"CUSTOM_FUZZ_STRING"}, {"AS"}, {"ON DUPLICATE KEY UPDATE"}, } // These are everything that comes after "SELECT" var selectTokens = [][]string{ {"*", "CUSTOM_FUZZ_STRING", "DISTINCTROW"}, {"HIGH_PRIORITY"}, {"STRAIGHT_JOIN"}, {"SQL_SMALL_RESULT", "SQL_BIG_RESULT", "SQL_BUFFER_RESULT"}, {"SQL_NO_CACHE", "SQL_CALC_FOUND_ROWS"}, {"CUSTOM_FUZZ_STRING"}, {"FROM"}, {"WHERE"}, {"GROUP BY"}, {"HAVING"}, {"WINDOW"}, {"ORDER BY"}, {"LIMIT"}, {"CUSTOM_FUZZ_STRING"}, {"FOR"}, } // These are everything that comes after "DELETE" var deleteTokens = [][]string{ {"LOW_PRIORITY", "QUICK", "IGNORE", "FROM", "AS"}, {"PARTITION"}, {"WHERE"}, {"ORDER BY"}, {"LIMIT"}, } var alter_table_options = []string{ "ADD", "COLUMN", "FIRST", "AFTER", "INDEX", "KEY", "FULLTEXT", "SPATIAL", "CONSTRAINT", "UNIQUE", "FOREIGN KEY", "CHECK", "ENFORCED", "DROP", "ALTER", "NOT", "INPLACE", "COPY", "SET", "VISIBLE", "INVISIBLE", "DEFAULT", "CHANGE", "CHARACTER SET", "COLLATE", "DISABLE", "ENABLE", "KEYS", "TABLESPACE", "LOCK", "FORCE", "MODIFY", "SHARED", "EXCLUSIVE", "NONE", "ORDER BY", "RENAME COLUMN", "AS", "=", "ASC", "DESC", "WITH", "WITHOUT", "VALIDATION", "ADD PARTITION", "DROP PARTITION", "DISCARD PARTITION", "IMPORT PARTITION", "TRUNCATE PARTITION", "COALESCE PARTITION", "REORGANIZE PARTITION", "EXCHANGE PARTITION", "ANALYZE PARTITION", "CHECK PARTITION", "OPTIMIZE PARTITION", "REBUILD PARTITION", "REPAIR PARTITION", "REMOVE PARTITIONING", "USING", "BTREE", "HASH", "COMMENT", "KEY_BLOCK_SIZE", "WITH PARSER", "AUTOEXTEND_SIZE", "AUTO_INCREMENT", "AVG_ROW_LENGTH", "CHECKSUM", "INSERT_METHOD", "ROW_FORMAT", "DYNAMIC", "FIXED", "COMPRESSED", "REDUNDANT", "COMPACT", "SECONDARY_ENGINE_ATTRIBUTE", "STATS_AUTO_RECALC", "STATS_PERSISTENT", "STATS_SAMPLE_PAGES", "ZLIB", "LZ4", "ENGINE_ATTRIBUTE", "KEY_BLOCK_SIZE", "MAX_ROWS", "MIN_ROWS", "PACK_KEYS", "PASSWORD", "COMPRESSION", "CONNECTION", "DIRECTORY", "DELAY_KEY_WRITE", "ENCRYPTION", "STORAGE", "DISK", "MEMORY", "UNION", } // Creates an 'alter table' statement. 'alter table' is an exception // in that it has its own function. The majority of statements // are created by 'createStmt()'. func createAlterTableStmt(f *ConsumeFuzzer) (string, error) { maxArgs, err := f.GetInt() if err != nil { return "", err } maxArgs = maxArgs % 30 if maxArgs == 0 { return "", fmt.Errorf("could not create alter table stmt") } var stmt strings.Builder stmt.WriteString("ALTER TABLE ") for i := 0; i < maxArgs; i++ { // Calculate if we get existing token or custom string tokenType, err := f.GetInt() if err != nil { return "", err } if tokenType%4 == 1 { customString, err := f.GetString() if err != nil { return "", err } stmt.WriteString(" " + customString) } else { tokenIndex, err := f.GetInt() if err != nil { return "", err } stmt.WriteString(" " + alter_table_options[tokenIndex%len(alter_table_options)]) } } return stmt.String(), nil } func chooseToken(tokens []string, f *ConsumeFuzzer) (string, error) { index, err := f.GetInt() if err != nil { return "", err } var token strings.Builder token.WriteString(tokens[index%len(tokens)]) if token.String() == "CUSTOM_FUZZ_STRING" { customFuzzString, err := f.GetString() if err != nil { return "", err } return customFuzzString, nil } // Check if token requires an argument if containsString(needCustomString, token.String()) { customFuzzString, err := f.GetString() if err != nil { return "", err } token.WriteString(" " + customFuzzString) } return token.String(), nil } var stmtTypes = map[string][][]string{ "DELETE": deleteTokens, "INSERT": insertTokens, "SELECT": selectTokens, "LOAD": loadTokens, "REPLACE": replaceTokens, "CREATE": createTokens, "DROP": dropTokens, "RENAME": renameTokens, "TRUNCATE": truncateTokens, "SET": setTokens, "ALTER": alterTokens, "ALTER TABLE": alterTableTokens, // ALTER TABLE has its own set of tokens } var stmtTypeEnum = map[int]string{ 0: "DELETE", 1: "INSERT", 2: "SELECT", 3: "LOAD", 4: "REPLACE", 5: "CREATE", 6: "DROP", 7: "RENAME", 8: "TRUNCATE", 9: "SET", 10: "ALTER", 11: "ALTER TABLE", } func createStmt(f *ConsumeFuzzer) (string, error) { stmtIndex, err := f.GetInt() if err != nil { return "", err } stmtIndex = stmtIndex % len(stmtTypes) queryType := stmtTypeEnum[stmtIndex] tokens := stmtTypes[queryType] // We have custom creator for ALTER TABLE if queryType == "ALTER TABLE" { query, err := createAlterTableStmt(f) if err != nil { return "", err } return query, nil } // Here we are creating a query that is not // an 'alter table' query. For available // queries, see "stmtTypes" // First specify the first query keyword: var query strings.Builder query.WriteString(queryType) // Next create the args for the queryArgs, err := createStmtArgs(tokens, f) if err != nil { return "", err } query.WriteString(" " + queryArgs) return query.String(), nil } // Creates the arguments of a statements. In a select statement // that would be everything after "select". func createStmtArgs(tokenslice [][]string, f *ConsumeFuzzer) (string, error) { var query, token strings.Builder // We go through the tokens in the tokenslice, // create the respective token and add it to // "query" for _, tokens := range tokenslice { // For extra randomization, the fuzzer can // choose to not include this token. includeThisToken, err := f.GetBool() if err != nil { return "", err } if !includeThisToken { continue } // There may be several tokens to choose from: if len(tokens) > 1 { chosenToken, err := chooseToken(tokens, f) if err != nil { return "", err } query.WriteString(" " + chosenToken) } else { token.WriteString(tokens[0]) // In case the token is "CUSTOM_FUZZ_STRING" // we will then create a non-structured string if token.String() == "CUSTOM_FUZZ_STRING" { customFuzzString, err := f.GetString() if err != nil { return "", err } query.WriteString(" " + customFuzzString) continue } // Check if token requires an argument. // Tokens that take an argument can be found // in 'needCustomString'. If so, we add a // non-structured string to the token. if containsString(needCustomString, token.String()) { customFuzzString, err := f.GetString() if err != nil { return "", err } token.WriteString(fmt.Sprintf(" %s", customFuzzString)) } query.WriteString(fmt.Sprintf(" %s", token.String())) } } return query.String(), nil } // Creates a semi-structured query. It creates a string // that is a combination of the keywords and random strings. func createQuery(f *ConsumeFuzzer) (string, error) { queryLen, err := f.GetInt() if err != nil { return "", err } maxLen := queryLen % 60 if maxLen == 0 { return "", fmt.Errorf("could not create a query") } var query strings.Builder for i := 0; i < maxLen; i++ { // Get a new token: useKeyword, err := f.GetBool() if err != nil { return "", err } if useKeyword { keyword, err := getKeyword(f) if err != nil { return "", err } query.WriteString(" " + keyword) } else { customString, err := f.GetString() if err != nil { return "", err } query.WriteString(" " + customString) } } if query.String() == "" { return "", fmt.Errorf("could not create a query") } return query.String(), nil } // GetSQLString is the API that users interact with. // // Usage: // // f := NewConsumer(data) // sqlString, err := f.GetSQLString() func (f *ConsumeFuzzer) GetSQLString() (string, error) { var query string veryStructured, err := f.GetBool() if err != nil { return "", err } if veryStructured { query, err = createStmt(f) if err != nil { return "", err } } else { query, err = createQuery(f) if err != nil { return "", err } } return query, nil } golang-github-adamkorcz-go-fuzz-headers-1-0.0~git20230919.8b5d3ce/sql_test.go000066400000000000000000000023011455122344500262750ustar00rootroot00000000000000// Copyright 2023 The go-fuzz-headers Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gofuzzheaders import ( "testing" ) func TestSQLAPI(t *testing.T) { t.Run("Test 1", func(t *testing.T) { data := []byte{1, 1, 0, 1} f := NewConsumer(data) query, err := f.GetSQLString() if err != nil { t.Error(err) } if query != " action" { t.Errorf("expected ' action', got: '%s'", query) } }) t.Run("Test 2", func(t *testing.T) { data := []byte{ 222, 255, 0, 100, 10, 64, 2, 0, 0, 0, 0, 0, 0, 100, 6, 0, 0, 0, 0, 0, 0, 255, 61, 100, 170, 0, 0, } f := NewConsumer(data) query, err := f.GetSQLString() if err != nil { t.Error(err) } t.Log(query) }) }