github.com/quic-go/quic-go@v0.44.0/fuzzing/internal/helper/helper.go (about) 1 package helper 2 3 import ( 4 "crypto" 5 "crypto/rand" 6 "crypto/sha1" 7 "crypto/tls" 8 "crypto/x509" 9 "crypto/x509/pkix" 10 "encoding/hex" 11 "math/big" 12 "os" 13 "path/filepath" 14 "time" 15 ) 16 17 // NthBit gets the n-th bit of a byte (counting starts at 0). 18 func NthBit(val uint8, n int) bool { 19 if n < 0 || n > 7 { 20 panic("invalid value for n") 21 } 22 return val>>n&0x1 == 1 23 } 24 25 // WriteCorpusFile writes data to a corpus file in directory path. 26 // The filename is calculated from the SHA1 sum of the file contents. 27 func WriteCorpusFile(path string, data []byte) error { 28 // create the directory, if it doesn't exist yet 29 if _, err := os.Stat(path); os.IsNotExist(err) { 30 if err := os.MkdirAll(path, os.ModePerm); err != nil { 31 return err 32 } 33 } 34 hash := sha1.Sum(data) 35 return os.WriteFile(filepath.Join(path, hex.EncodeToString(hash[:])), data, 0o644) 36 } 37 38 // WriteCorpusFileWithPrefix writes data to a corpus file in directory path. 39 // In many fuzzers, the first n bytes are used to control. 40 // This function prepends n zero-bytes to the data. 41 func WriteCorpusFileWithPrefix(path string, data []byte, n int) error { 42 return WriteCorpusFile(path, append(make([]byte, n), data...)) 43 } 44 45 // GenerateCertificate generates a self-signed certificate. 46 // It returns the certificate and a x509.CertPool containing that certificate. 47 func GenerateCertificate(priv crypto.Signer) (*tls.Certificate, *x509.CertPool, error) { 48 template := x509.Certificate{ 49 SerialNumber: big.NewInt(1), 50 Subject: pkix.Name{Organization: []string{"quic-go fuzzer"}}, 51 NotBefore: time.Now().Add(-24 * time.Hour), 52 NotAfter: time.Now().Add(30 * 24 * time.Hour), 53 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 54 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 55 DNSNames: []string{"localhost"}, 56 BasicConstraintsValid: true, 57 } 58 derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv) 59 if err != nil { 60 return nil, nil, err 61 } 62 cert, err := x509.ParseCertificate(derBytes) 63 if err != nil { 64 return nil, nil, err 65 } 66 certPool := x509.NewCertPool() 67 certPool.AddCert(cert) 68 return &tls.Certificate{ 69 Certificate: [][]byte{derBytes}, 70 PrivateKey: priv, 71 }, certPool, nil 72 }