code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
func Test_nativeHelmChart_ExtractChart(t *testing.T) {
client := NewClient("https://argoproj.github.io/argo-helm", Creds{}, false, "")
path, closer, err := client.ExtractChart("argo-cd", "0.7.1", false, math.MaxInt64, true)
assert.NoError(t, err)
defer io.Close(closer)
info, err := os.Stat(path)
assert.NoError(t, err)
assert.True(t, info.IsDir())
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func Test_nativeHelmChart_ExtractChart_insecure(t *testing.T) {
client := NewClient("https://argoproj.github.io/argo-helm", Creds{InsecureSkipVerify: true}, false, "")
path, closer, err := client.ExtractChart("argo-cd", "0.7.1", false, math.MaxInt64, true)
assert.NoError(t, err)
defer io.Close(closer)
info, err := os.Stat(path)
assert.NoError(t, err)
assert.True(t, info.IsDir())
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func Test_nativeHelmChart_ExtractChartWithLimiter(t *testing.T) {
client := NewClient("https://argoproj.github.io/argo-helm", Creds{}, false, "")
_, _, err := client.ExtractChart("argo-cd", "0.7.1", false, 100, false)
assert.Error(t, err, "error while iterating on tar reader: unexpected EOF")
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func clusterToSecret(c *appv1.Cluster, secret *apiv1.Secret) error {
data := make(map[string][]byte)
data["server"] = []byte(strings.TrimRight(c.Server, "/"))
if c.Name == "" {
data["name"] = []byte(c.Server)
} else {
data["name"] = []byte(c.Name)
}
if len(c.Namespaces) != 0 {
data["namespaces"] = []byte(strings.Join(c.Namespaces, ","))
}
configBytes, err := json.Marshal(c.Config)
if err != nil {
return err
}
data["config"] = configBytes
if c.Shard != nil {
data["shard"] = []byte(strconv.Itoa(int(*c.Shard)))
}
if c.ClusterResources {
data["clusterResources"] = []byte("true")
}
if c.Project != "" {
data["project"] = []byte(c.Project)
}
secret.Data = data
secret.Labels = c.Labels
if c.Annotations != nil && c.Annotations[apiv1.LastAppliedConfigAnnotation] != "" {
return status.Errorf(codes.InvalidArgument, "annotation %s cannot be set", apiv1.LastAppliedConfigAnnotation)
}
secret.Annotations = c.Annotations
if secret.Annotations == nil {
secret.Annotations = make(map[string]string)
}
if c.RefreshRequestedAt != nil {
secret.Annotations[appv1.AnnotationKeyRefresh] = c.RefreshRequestedAt.Format(time.RFC3339)
} else {
delete(secret.Annotations, appv1.AnnotationKeyRefresh)
}
addSecretMetadata(secret, common.LabelValueSecretTypeCluster)
return nil
} | 1 | Go | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
func TestClusterToSecret_LastAppliedConfigurationRejected(t *testing.T) {
cluster := &appv1.Cluster{
Server: "server",
Annotations: map[string]string{v1.LastAppliedConfigAnnotation: "val2"},
Name: "test",
Config: v1alpha1.ClusterConfig{},
Project: "project",
Namespaces: []string{"default"},
}
s := &v1.Secret{}
err := clusterToSecret(cluster, s)
require.Error(t, err)
require.Equal(t, codes.InvalidArgument, status.Code(err))
} | 1 | Go | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
func Test_secretToCluster_LastAppliedConfigurationDropped(t *testing.T) {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "mycluster",
Namespace: fakeNamespace,
Annotations: map[string]string{v1.LastAppliedConfigAnnotation: "val2"},
},
Data: map[string][]byte{
"name": []byte("test"),
"server": []byte("http://mycluster"),
"config": []byte("{\"username\":\"foo\"}"),
},
}
cluster, err := SecretToCluster(secret)
require.NoError(t, err)
assert.Len(t, cluster.Annotations, 0)
} | 1 | Go | CWE-532 | Insertion of Sensitive Information into Log File | Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. | https://cwe.mitre.org/data/definitions/532.html | safe |
func TestScalarMult(t *testing.T) {
t.Run("P224", func(t *testing.T) {
testScalarMult(t, nistec.NewP224Point, elliptic.P224())
})
t.Run("P256", func(t *testing.T) {
testScalarMult(t, nistec.NewP256Point, elliptic.P256())
})
t.Run("P384", func(t *testing.T) {
testScalarMult(t, nistec.NewP384Point, elliptic.P384())
})
t.Run("P521", func(t *testing.T) {
testScalarMult(t, nistec.NewP521Point, elliptic.P521())
})
} | 1 | Go | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | safe |
func fatalIfErr(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
} | 1 | Go | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | safe |
func p256SelectAffine(res *p256AffinePoint, table *p256AffineTable, idx int)
// Point addition with an affine point and constant time conditions.
// If zero is 0, sets res = in2. If sel is 0, sets res = in1.
// If sign is not 0, sets res = in1 + -in2. Otherwise, sets res = in1 + in2
//
//go:noescape
func p256PointAddAffineAsm(res, in1 *P256Point, in2 *p256AffinePoint, sign, sel, zero int)
// Point addition. Sets res = in1 + in2. Returns one if the two input points
// were equal and zero otherwise. If in1 or in2 are the point at infinity, res
// and the return value are undefined.
//
//go:noescape
func p256PointAddAsm(res, in1, in2 *P256Point) int
// Point doubling. Sets res = in + in. in can be the point at infinity.
//
//go:noescape
func p256PointDoubleAsm(res, in *P256Point)
// p256OrdElement is a P-256 scalar field element in [0, ord(G)-1] in the
// Montgomery domain (with R 2²⁵⁶) as four uint64 limbs in little-endian order.
type p256OrdElement [4]uint64
// p256OrdReduce ensures s is in the range [0, ord(G)-1].
func p256OrdReduce(s *p256OrdElement) {
// Since 2 * ord(G) > 2²⁵⁶, we can just conditionally subtract ord(G),
// keeping the result if it doesn't underflow.
t0, b := bits.Sub64(s[0], 0xf3b9cac2fc632551, 0)
t1, b := bits.Sub64(s[1], 0xbce6faada7179e84, b)
t2, b := bits.Sub64(s[2], 0xffffffffffffffff, b)
t3, b := bits.Sub64(s[3], 0xffffffff00000000, b)
tMask := b - 1 // zero if subtraction underflowed
s[0] ^= (t0 ^ s[0]) & tMask
s[1] ^= (t1 ^ s[1]) & tMask
s[2] ^= (t2 ^ s[2]) & tMask
s[3] ^= (t3 ^ s[3]) & tMask
} | 1 | Go | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | safe |
func (r *P256Point) ScalarMult(q *P256Point, scalar []byte) (*P256Point, error) {
if len(scalar) != 32 {
return nil, errors.New("invalid scalar length")
}
scalarReversed := new(p256OrdElement)
p256OrdBigToLittle(scalarReversed, (*[32]byte)(scalar))
p256OrdReduce(scalarReversed)
r.Set(q).p256ScalarMult(scalarReversed)
return r, nil
} | 1 | Go | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | safe |
func (r *P256Point) ScalarBaseMult(scalar []byte) (*P256Point, error) {
if len(scalar) != 32 {
return nil, errors.New("invalid scalar length")
}
scalarReversed := new(p256OrdElement)
p256OrdBigToLittle(scalarReversed, (*[32]byte)(scalar))
p256OrdReduce(scalarReversed)
r.p256BaseMult(scalarReversed)
return r, nil
} | 1 | Go | CWE-682 | Incorrect Calculation | The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. | https://cwe.mitre.org/data/definitions/682.html | safe |
func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {
c := basicConfig()
for _, opt := range opts {
opt(c)
}
host, port, err := net.SplitHostPort(hostport)
if err != nil {
return "", err
}
ip := net.ParseIP(host)
if ip != nil {
if ip.IsUnspecified() || (ip.To4() != nil && c.isIPForbidden(ip)) {
return "", fmt.Errorf("bad ip is detected: %v", ip)
}
return net.JoinHostPort(ip.String(), port), nil
}
if c.isHostForbidden(host) {
return "", fmt.Errorf("bad host is detected: %v", host)
}
r := resolver
if r == nil {
r = net.DefaultResolver
}
addrs, err := r.LookupIPAddr(ctx, host)
if err != nil || len(addrs) <= 0 {
return "", err
}
safeAddrs := make([]net.IPAddr, 0, len(addrs))
for _, addr := range addrs {
// only support IPv4 address
if addr.IP.To4() == nil {
continue
}
if c.isIPForbidden(addr.IP) {
return "", fmt.Errorf("bad ip is detected: %v", addr.IP)
}
safeAddrs = append(safeAddrs, addr)
}
if len(safeAddrs) == 0 {
return "", fmt.Errorf("fail to lookup ip addr: %v", host)
}
return net.JoinHostPort(safeAddrs[0].IP.String(), port), nil
} | 1 | Go | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
func TestRequest(t *testing.T) {
resp, err := DefaultClient.Get("http://www.example.org")
if err != nil && resp.StatusCode == 200 {
t.Error("The request with an ordinal url should be successful")
}
resp, err = DefaultClient.Get("http://localhost")
if err == nil {
t.Errorf("The request for localhost should be fail")
}
if _, err := DefaultClient.Get("http://192.168.0.1"); err == nil {
t.Errorf("The request for localhost should be fail")
}
if _, err := DefaultClient.Get("http://[::]"); err == nil {
t.Errorf("The request for IPv6 unspecified address should be fail")
}
} | 1 | Go | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
func (fs *Filesystem) Writefile(p string, r io.Reader) error {
cleaned, err := fs.SafePath(p)
if err != nil {
return err
}
var currentSize int64
// If the file does not exist on the system already go ahead and create the pathway
// to it and an empty file. We'll then write to it later on after this completes.
stat, err := os.Stat(cleaned)
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "server/filesystem: writefile: failed to stat file")
} else if err == nil {
if stat.IsDir() {
return errors.WithStack(&Error{code: ErrCodeIsDirectory, resolved: cleaned})
}
currentSize = stat.Size()
}
br := bufio.NewReader(r)
// Check that the new size we're writing to the disk can fit. If there is currently
// a file we'll subtract that current file size from the size of the buffer to determine
// the amount of new data we're writing (or amount we're removing if smaller).
if err := fs.HasSpaceFor(int64(br.Size()) - currentSize); err != nil {
return err
}
// Touch the file and return the handle to it at this point. This will create the file,
// any necessary directories, and set the proper owner of the file.
file, err := fs.Touch(cleaned, os.O_RDWR|os.O_CREATE|os.O_TRUNC)
if err != nil {
return err
}
defer file.Close()
buf := make([]byte, 1024*4)
sz, err := io.CopyBuffer(file, r, buf)
// Adjust the disk usage to account for the old size and the new size of the file.
fs.addDisk(sz - currentSize)
return fs.unsafeChown(cleaned)
} | 1 | Go | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | safe |
func (fs *Filesystem) Chown(path string) error {
cleaned, err := fs.SafePath(path)
if err != nil {
return err
}
return fs.unsafeChown(cleaned)
} | 1 | Go | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | safe |
func (fs *Filesystem) SafePath(p string) (string, error) {
// Start with a cleaned up path before checking the more complex bits.
r := fs.unsafeFilePath(p)
// At the same time, evaluate the symlink status and determine where this file or folder
// is truly pointing to.
ep, err := filepath.EvalSymlinks(r)
if err != nil && !os.IsNotExist(err) {
return "", errors.Wrap(err, "server/filesystem: failed to evaluate symlink")
} else if os.IsNotExist(err) {
// The target of one of the symlinks (EvalSymlinks is recursive) does not exist.
// So we get what target path does not exist and check if it's within the data
// directory. If it is, we return the original path, otherwise we return an error.
pErr, ok := err.(*iofs.PathError)
if !ok {
return "", errors.Wrap(err, "server/filesystem: failed to evaluate symlink")
}
ep = pErr.Path
}
// If the requested directory from EvalSymlinks begins with the server root directory go
// ahead and return it. If not we'll return an error which will block any further action
// on the file.
if fs.unsafeIsInDataDirectory(ep) {
// Returning the original path here instead of the resolved path ensures that
// whatever the user is trying to do will work as expected. If we returned the
// resolved path, the user would be unable to know that it is in fact a symlink.
return r, nil
}
return "", NewBadPathResolution(p, r)
} | 1 | Go | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | safe |
func MaxQueuedWantlistEntriesPerPeer(count uint) Option {
return Option{server.MaxQueuedWantlistEntriesPerPeer(count)}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) PeerDisconnected(p peer.ID) {
e.peerRequestQueue.Clear(p)
e.lock.Lock()
defer e.lock.Unlock()
e.peerLedger.PeerDisconnected(p)
e.scoreLedger.PeerDisconnected(p)
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) NotifyNewBlocks(blks []blocks.Block) {
if len(blks) == 0 {
return
}
// Get the size of each block
blockSizes := make(map[cid.Cid]int, len(blks))
for _, blk := range blks {
blockSizes[blk.Cid()] = len(blk.RawData())
}
// Check each peer to see if it wants one of the blocks we received
var work bool
for _, b := range blks {
k := b.Cid()
e.lock.RLock()
peers := e.peerLedger.Peers(k)
e.lock.RUnlock()
for _, entry := range peers {
work = true
blockSize := blockSizes[k]
isWantBlock := e.sendAsBlock(entry.WantType, blockSize)
entrySize := blockSize
if !isWantBlock {
entrySize = bsmsg.BlockPresenceSize(k)
}
e.peerRequestQueue.PushTasksTruncated(e.maxQueuedWantlistEntriesPerPeer, entry.Peer, peertask.Task{
Topic: k,
Priority: int(entry.Priority),
Work: entrySize,
Data: &taskData{
BlockSize: blockSize,
HaveBlock: true,
IsWantBlock: isWantBlock,
SendDontHave: false,
},
})
e.updateMetrics()
}
}
if work {
e.signalNewWork()
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func WithMaxQueuedWantlistEntriesPerPeer(count uint) Option {
return func(e *Engine) {
e.maxQueuedWantlistEntriesPerPeer = count
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) MessageSent(p peer.ID, m bsmsg.BitSwapMessage) {
e.lock.Lock()
defer e.lock.Unlock()
// Remove sent blocks from the want list for the peer
for _, block := range m.Blocks() {
e.scoreLedger.AddToSentBytes(p, len(block.RawData()))
e.peerLedger.CancelWantWithType(p, block.Cid(), pb.Message_Wantlist_Block)
}
// Remove sent block presences from the want list for the peer
for _, bp := range m.BlockPresences() {
// Don't record sent data. We reserve that for data blocks.
if bp.Type == pb.Message_Have {
e.peerLedger.CancelWantWithType(p, bp.Cid, pb.Message_Wantlist_Have)
}
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) Peers() []peer.ID {
e.lock.RLock()
defer e.lock.RUnlock()
return e.peerLedger.CollectPeerIDs()
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) WantlistForPeer(p peer.ID) []wl.Entry {
e.lock.RLock()
defer e.lock.RUnlock()
return e.peerLedger.WantlistForPeer(p)
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (e *Engine) ReceivedBlocks(from peer.ID, blks []blocks.Block) {
if len(blks) == 0 {
return
}
// Record how many bytes were received in the ledger
for _, blk := range blks {
log.Debugw("Bitswap engine <- block", "local", e.self, "from", from, "cid", blk.Cid(), "size", len(blk.RawData()))
e.scoreLedger.AddToReceivedBytes(from, len(blk.RawData()))
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func TestPeerIsAddedToPeersWhenMessageSent(t *testing.T) {
test.Flaky(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sanfrancisco := newTestEngine(ctx, "sf")
seattle := newTestEngine(ctx, "sea")
m := message.New(true)
// We need to request something for it to add us as partner.
m.AddEntry(blocks.NewBlock([]byte("Hæ")).Cid(), 0, pb.Message_Wantlist_Block, true)
seattle.Engine.MessageReceived(ctx, sanfrancisco.Peer, m)
if seattle.Peer == sanfrancisco.Peer {
t.Fatal("Sanity Check: Peers have same Key!")
}
if !peerIsPartner(sanfrancisco.Peer, seattle.Engine) {
t.Fatal("Peer wasn't added as a Partner")
}
seattle.Engine.PeerDisconnected(sanfrancisco.Peer)
if peerIsPartner(sanfrancisco.Peer, seattle.Engine) {
t.Fatal("expected peer to be removed")
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) CancelWant(p peer.ID, k cid.Cid) bool {
wants, ok := l.peers[p]
if !ok {
return false
}
delete(wants, k)
if len(wants) == 0 {
delete(l.peers, p)
}
l.removePeerFromCid(p, k)
return true
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) ClearPeerWantlist(p peer.ID) {
cids, ok := l.peers[p]
if !ok {
return
}
for c := range cids {
l.removePeerFromCid(p, c)
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) WantlistSizeForPeer(p peer.ID) int {
return len(l.peers[p])
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) Wants(p peer.ID, e wl.Entry) {
cids, ok := l.peers[p]
if !ok {
cids = make(map[cid.Cid]entry)
l.peers[p] = cids
}
cids[e.Cid] = entry{e.Priority, e.WantType}
m, ok := l.cids[e.Cid]
if !ok {
m = make(map[peer.ID]entry)
l.cids[e.Cid] = m
}
m[p] = entry{e.Priority, e.WantType}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) CancelWantWithType(p peer.ID, k cid.Cid, typ pb.Message_Wantlist_WantType) {
wants, ok := l.peers[p]
if !ok {
return
}
e, ok := wants[k]
if !ok {
return
}
if typ == pb.Message_Wantlist_Have && e.WantType == pb.Message_Wantlist_Block {
return
}
delete(wants, k)
if len(wants) == 0 {
delete(l.peers, p)
}
l.removePeerFromCid(p, k)
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) WantlistForPeer(p peer.ID) []wl.Entry {
cids, ok := l.peers[p]
if !ok {
return nil
}
entries := make([]wl.Entry, 0, len(l.cids))
for c, e := range cids {
entries = append(entries, wl.Entry{
Cid: c,
Priority: e.Priority,
WantType: e.WantType,
})
}
return entries
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func newPeerLedger() *peerLedger {
return &peerLedger{
peers: make(map[peer.ID]map[cid.Cid]entry),
cids: make(map[cid.Cid]map[peer.ID]entry),
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) CollectPeerIDs() []peer.ID {
peers := make([]peer.ID, 0, len(l.peers))
for p := range l.peers {
peers = append(peers, p)
}
return peers
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) Peers(k cid.Cid) []entryForPeer {
m, ok := l.cids[k]
if !ok {
return nil
}
peers := make([]entryForPeer, 0, len(m))
for p, e := range m {
peers = append(peers, entryForPeer{p, e})
}
return peers
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) removePeerFromCid(p peer.ID, k cid.Cid) {
m, ok := l.cids[k]
if !ok {
return
}
delete(m, p)
if len(m) == 0 {
delete(l.cids, k)
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (l *peerLedger) PeerDisconnected(p peer.ID) {
l.ClearPeerWantlist(p)
delete(l.peers, p)
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func MaxCidSize(n uint) Option {
return Option{server.MaxCidSize(n)}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func WithMaxCidSize(n uint) Option {
return func(e *Engine) {
e.maxCidSize = n
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func isRequestPostPolicySignatureV4(r *http.Request) bool {
mediaType, _, err := mime.ParseMediaType(r.Header.Get(xhttp.ContentType))
if err != nil {
return false
}
return mediaType == "multipart/form-data" && r.Method == http.MethodPost
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func hasBadPathComponent(path string) bool {
path = filepath.ToSlash(strings.TrimSpace(path)) // For windows '\' must be converted to '/'
for _, p := range strings.Split(path, SlashSeparator) {
switch strings.TrimSpace(p) {
case dotdotComponent:
return true
case dotComponent:
return true
}
}
return false
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func TestObjectNewMultipartUpload(t *testing.T) {
if runtime.GOOS == globalWindowsOSName {
t.Skip()
}
ExecObjectLayerTest(t, testObjectNewMultipartUpload)
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func testObjectAbortMultipartUpload(obj ObjectLayer, instanceType string, t TestErrHandler) {
bucket := "minio-bucket"
object := "minio-object"
opts := ObjectOptions{}
// Create bucket before intiating NewMultipartUpload.
err := obj.MakeBucket(context.Background(), bucket, MakeBucketOptions{})
if err != nil {
// failed to create newbucket, abort.
t.Fatalf("%s : %s", instanceType, err.Error())
}
res, err := obj.NewMultipartUpload(context.Background(), bucket, object, opts)
if err != nil {
t.Fatalf("%s : %s", instanceType, err.Error())
}
uploadID := res.UploadID
abortTestCases := []struct {
bucketName string
objName string
uploadID string
expectedErrType error
}{
{"--", object, uploadID, BucketNotFound{}},
{"foo", object, uploadID, BucketNotFound{}},
{bucket, object, "foo-foo", InvalidUploadID{}},
{bucket, object, uploadID, nil},
}
if runtime.GOOS != globalWindowsOSName {
abortTestCases = append(abortTestCases, struct {
bucketName string
objName string
uploadID string
expectedErrType error
}{bucket, "\\", uploadID, InvalidUploadID{}})
}
// Iterating over creatPartCases to generate multipart chunks.
for i, testCase := range abortTestCases {
err = obj.AbortMultipartUpload(context.Background(), testCase.bucketName, testCase.objName, testCase.uploadID, opts)
if testCase.expectedErrType == nil && err != nil {
t.Errorf("Test %d, unexpected err is received: %v, expected:%v\n", i+1, err, testCase.expectedErrType)
}
if testCase.expectedErrType != nil && !isSameType(err, testCase.expectedErrType) {
t.Errorf("Test %d, unexpected err is received: %v, expected:%v\n", i+1, err, testCase.expectedErrType)
}
}
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func testPathTraversalExploit(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
credentials auth.Credentials, t *testing.T,
) {
if err := newTestConfig(globalMinioDefaultRegion, obj); err != nil {
t.Fatalf("Initializing config.json failed")
}
objectName := `\../.minio.sys/config/hello.txt`
// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.
rec := httptest.NewRecorder()
// construct HTTP request for Get Object end point.
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, objectName),
int64(5), bytes.NewReader([]byte("hello")), credentials.AccessKey, credentials.SecretKey, map[string]string{})
if err != nil {
t.Fatalf("failed to create HTTP request for Put Object: <ERROR> %v", err)
}
// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.
// Call the ServeHTTP to execute the handler.
apiRouter.ServeHTTP(rec, req)
ctx, cancel := context.WithCancel(GlobalContext)
defer cancel()
// Now check if we actually wrote to backend (regardless of the response
// returned by the server).
z := obj.(*erasureServerPools)
xl := z.serverPools[0].sets[0]
erasureDisks := xl.getDisks()
parts, errs := readAllFileInfo(ctx, erasureDisks, bucketName, objectName, "", false)
for i := range parts {
if errs[i] == nil {
if parts[i].Name == objectName {
t.Errorf("path traversal allowed to allow writing to minioMetaBucket: %s", instanceType)
}
}
}
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func TestPathTraversalExploit(t *testing.T) {
if runtime.GOOS != globalWindowsOSName {
t.Skip()
}
defer DetectTestLeak(t)()
ExecExtendedObjectLayerAPITest(t, testPathTraversalExploit, []string{"PutObject"})
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (t *Teler) checkCommonWebAttack(r *http.Request) error {
// Decode the URL-encoded and unescape HTML entities request URI of the URL
uri := stringDeUnescape(r.URL.RequestURI())
// Declare byte slice for request body.
var body string
// Initialize buffer to hold request body.
buf := &bytes.Buffer{}
// Use io.Copy to copy the request body to the buffer.
_, err := io.Copy(buf, r.Body)
if err == nil {
// If the read not fails, replace the request body
// with a new io.ReadCloser that reads from the buffer.
r.Body = io.NopCloser(buf)
// Convert the buffer to a string.
body = buf.String()
}
// Decode the URL-encoded and unescape HTML entities of body
body = stringDeUnescape(body)
// Iterate over the filters in the CommonWebAttack data stored in the t.threat.cwa.Filters field
for _, filter := range t.threat.cwa.Filters {
// Initialize a variable to track whether a match is found
var match bool
// Check the type of the filter's pattern
switch pattern := filter.pattern.(type) {
case *regexp.Regexp: // If the pattern is a regex
match = pattern.MatchString(uri) || pattern.MatchString(body)
case *pcre.Matcher: // If the pattern is a PCRE expr
match = pattern.MatchString(uri, 0) || pattern.MatchString(body, 0)
default: // If the pattern is of an unknown type, skip to the next iteration
continue
}
// If the pattern matches the request URI or body, return an error indicating a common web attack has been detected
if match {
return errors.New(filter.Description)
}
}
// Return nil if no match is found
return nil
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func unescapeHTML(s string) string {
return html.UnescapeString(s)
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func stringDeUnescape(s string) string {
s = toURLDecode(s)
return unescapeHTML(s)
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func Unzip(archive, targetDir string) (err error) {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
if err = os.MkdirAll(targetDir, DefaultDirPerm); err != nil {
return
}
for _, file := range reader.File {
if strings.Contains(file.Name, "..") {
return fmt.Errorf("illegal file path in zip: %v", file.Name)
}
fullPath := filepath.Join(targetDir, file.Name)
if file.FileInfo().IsDir() {
err = os.MkdirAll(fullPath, file.Mode())
if err != nil {
return err
}
continue
}
fileReader, err := file.Open()
if err != nil {
return err
}
targetFile, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
_ = fileReader.Close()
return err
}
_, err = io.Copy(targetFile, fileReader)
// close all
_ = fileReader.Close()
targetFile.Close()
if err != nil {
return err
}
}
return
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func (ea *ExternalAuth) AuthPlain(username, password string) error {
accountName, ok := auth.CheckDomainAuth(username, ea.perDomain, ea.domains)
if !ok {
return module.ErrUnknownCredentials
}
return AuthUsingHelper(ea.helperPath, accountName, password)
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (a *Auth) AuthPlain(username, password string) error {
if a.useHelper {
if err := external.AuthUsingHelper(a.helperPath, username, password); err != nil {
return err
}
}
err := runPAMAuth(username, password)
if err != nil {
return err
}
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (a *Auth) AuthPlain(username, password string) error {
ok := len(a.userTbls) == 0
for _, tbl := range a.userTbls {
_, tblOk, err := tbl.Lookup(username)
if err != nil {
return err
}
if tblOk {
ok = true
break
}
}
if !ok {
return errors.New("user not found in tables")
}
var lastErr error
for _, p := range a.passwd {
if err := p.AuthPlain(username, password); err != nil {
lastErr = err
continue
}
return nil
}
return lastErr
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func TestPlainSplit_NoUser(t *testing.T) {
a := Auth{
passwd: []module.PlainAuth{
mockAuth{
db: map[string]bool{
"user1": true,
},
},
},
}
err := a.AuthPlain("user1", "aaa")
if err != nil {
t.Fatal("Unexpected error:", err)
}
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func TestPlainSplit_NoUser_MultiPass(t *testing.T) {
a := Auth{
passwd: []module.PlainAuth{
mockAuth{
db: map[string]bool{
"user2": true,
},
},
mockAuth{
db: map[string]bool{
"user1": true,
},
},
},
}
err := a.AuthPlain("user1", "aaa")
if err != nil {
t.Fatal("Unexpected error:", err)
}
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func TestPlainSplit_MultiUser_Pass(t *testing.T) {
a := Auth{
userTbls: []module.Table{
mockTable{
db: map[string]string{
"userWH": "",
},
},
mockTable{
db: map[string]string{
"user1": "",
},
},
},
passwd: []module.PlainAuth{
mockAuth{
db: map[string]bool{
"user2": true,
},
},
mockAuth{
db: map[string]bool{
"user1": true,
},
},
},
}
err := a.AuthPlain("user1", "aaa")
if err != nil {
t.Fatal("Unexpected error:", err)
}
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (m mockAuth) AuthPlain(username, _ string) error {
ok := m.db[username]
if !ok {
return errors.New("invalid creds")
}
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func TestPlainSplit_UserPass(t *testing.T) {
a := Auth{
userTbls: []module.Table{
mockTable{
db: map[string]string{
"user1": "",
},
},
},
passwd: []module.PlainAuth{
mockAuth{
db: map[string]bool{
"user2": true,
},
},
mockAuth{
db: map[string]bool{
"user1": true,
},
},
},
}
err := a.AuthPlain("user1", "aaa")
if err != nil {
t.Fatal("Unexpected error:", err)
}
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
return sasl.NewLoginServer(func(username, password string) error {
err := s.AuthPlain(username, password)
if err != nil {
s.Log.Error("authentication failed", err, "username", username, "src_ip", remoteAddr)
return errors.New("auth: invalid credentials")
}
return successCb(username)
}) | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (s *SASLAuth) AuthPlain(username, password string) error {
if len(s.Plain) == 0 {
return ErrUnsupportedMech
}
var lastErr error
for _, p := range s.Plain {
err := p.AuthPlain(username, password)
if err == nil {
return nil
}
if err != nil {
lastErr = err
continue
}
}
return fmt.Errorf("no auth. provider accepted creds, last err: %w", lastErr)
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
srv := a.CreateSASL("XWHATEVER", &net.TCPAddr{}, func(string) error { return nil }) | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (m mockAuth) AuthPlain(username, _ string) error {
ok := m.db[username]
if !ok {
return errors.New("invalid creds")
}
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
srv := a.CreateSASL("PLAIN", &net.TCPAddr{}, func(id string) error {
if id != "user1" {
t.Fatal("Wrong auth. identities passed to callback:", id)
}
return nil
}) | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (a *Auth) AuthPlain(username, password string) error {
if a.useHelper {
return external.AuthUsingHelper(a.helperPath, username, password)
}
ent, err := Lookup(username)
if err != nil {
return err
}
if !ent.IsAccountValid() {
return fmt.Errorf("shadow: account is expired")
}
if !ent.IsPasswordValid() {
return fmt.Errorf("shadow: password is expired")
}
if err := ent.VerifyPassword(password); err != nil {
if err == ErrWrongPassword {
return module.ErrUnknownCredentials
}
return err
}
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (d *Dummy) AuthPlain(username, _ string) error {
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (store *Storage) AuthPlain(username, password string) error {
// TODO: Pass session context there.
defer trace.StartRegion(context.Background(), "sql/AuthPlain").End()
accountName, err := prepareUsername(username)
if err != nil {
return err
}
password, err = precis.OpaqueString.CompareKey(password)
if err != nil {
return err
}
// TODO: Make go-imap-sql CheckPlain return an actual error.
if !store.Back.CheckPlain(accountName, password) {
return module.ErrUnknownCredentials
}
return nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func BytesToFile(path string, data []byte) error {
exist, _ := IsExist(path)
if !exist {
if err := CreateFile(path); err != nil {
return err
}
}
return ioutil.WriteFile(path, data, 0644)
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func IsExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func ClearFile(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
if err != nil {
return err
}
defer f.Close()
return nil
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func IsShortcut(path string) bool {
ext := filepath.Ext(path)
if ext == ".lnk" {
return true
}
return false
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func Create(path string) (*os.File, error) {
exist, err := IsExist(path)
if err != nil {
return nil, err
}
if exist {
return os.Create(path)
}
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
return nil, err
}
return os.Create(path)
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func RemoveFile(path string) error {
return os.Remove(path)
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
func unzipFile(file *zip.File, dstDir string) error {
// Prevent path traversal vulnerability.
// Such as if the file name is "../../../path/to/file.txt" which will be cleaned to "path/to/file.txt".
name := strings.TrimPrefix(filepath.Join(string(filepath.Separator), file.Name), string(filepath.Separator))
filePath := path.Join(dstDir, name)
// Create the directory of file.
if file.FileInfo().IsDir() {
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
return err
}
return nil
}
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return err
}
// Open the file.
r, err := file.Open()
if err != nil {
return err
}
defer r.Close()
// Create the file.
w, err := os.Create(filePath)
if err != nil {
return err
}
defer w.Close()
// Save the decompressed file content.
_, err = io.Copy(w, r)
return err
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
corsHandler := gh.CORS(gh.AllowCredentials(), gh.AllowedHeaders([]string{"x-requested-with", "content-type"}), gh.AllowedMethods([]string{"GET", "POST", "HEAD", "DELETE"}), gh.AllowedOriginValidator(func(origin string) bool {
if strings.Contains(origin, "localhost") ||
strings.HasSuffix(origin, ".play-with-docker.com") ||
strings.HasSuffix(origin, ".play-with-kubernetes.com") ||
strings.HasSuffix(origin, ".docker.com") ||
strings.HasSuffix(origin, ".play-with-go.dev") {
return true
}
return false
}), gh.AllowedOrigins([]string{})) | 1 | Go | CWE-639 | Authorization Bypass Through User-Controlled Key | The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data. | https://cwe.mitre.org/data/definitions/639.html | safe |
func (r *saferFlateReader) Close() error {
return r.r.Close()
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func newSaferFlateReader(r io.Reader) io.ReadCloser {
return &saferFlateReader{r: flate.NewReader(r)}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (r *saferFlateReader) Read(p []byte) (n int, err error) {
if r.count+len(p) > flateUncompressLimit {
return 0, fmt.Errorf("flate: uncompress limit exceeded (%d bytes)", flateUncompressLimit)
}
n, err = r.r.Read(p)
r.count += n
return n, err
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func NewIdpAuthnRequest(idp *IdentityProvider, r *http.Request) (*IdpAuthnRequest, error) {
req := &IdpAuthnRequest{
IDP: idp,
HTTPRequest: r,
Now: TimeNow(),
}
switch r.Method {
case "GET":
compressedRequest, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("SAMLRequest"))
if err != nil {
return nil, fmt.Errorf("cannot decode request: %s", err)
}
req.RequestBuffer, err = ioutil.ReadAll(newSaferFlateReader(bytes.NewReader(compressedRequest)))
if err != nil {
return nil, fmt.Errorf("cannot decompress request: %s", err)
}
req.RelayState = r.URL.Query().Get("RelayState")
case "POST":
if err := r.ParseForm(); err != nil {
return nil, err
}
var err error
req.RequestBuffer, err = base64.StdEncoding.DecodeString(r.PostForm.Get("SAMLRequest"))
if err != nil {
return nil, err
}
req.RelayState = r.PostForm.Get("RelayState")
default:
return nil, fmt.Errorf("method not allowed")
}
return req, nil
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
GetSessionFunc: func(w http.ResponseWriter, r *http.Request, req *IdpAuthnRequest) *Session {
fmt.Fprintf(w, "RelayState: %s\nSAMLRequest: %s",
req.RelayState, req.RequestBuffer)
return nil
},
}
//w := httptest.NewRecorder()
data := bytes.Repeat([]byte("a"), 768*1024*1024)
var compressed bytes.Buffer
w, _ := flate.NewWriter(&compressed, flate.BestCompression)
w.Write(data)
w.Close()
encoded := base64.StdEncoding.EncodeToString(compressed.Bytes())
r, _ := http.NewRequest("GET", "/dontcare?"+url.Values{
"SAMLRequest": {encoded},
}.Encode(), nil)
_, err := NewIdpAuthnRequest(&test.IDP, r)
assert.Error(t, err, "cannot decompress request: flate: uncompress limit exceeded (10485760 bytes)")
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (sp *ServiceProvider) ValidateLogoutResponseRedirect(queryParameterData string) error {
retErr := &InvalidResponseError{
Now: TimeNow(),
}
rawResponseBuf, err := base64.StdEncoding.DecodeString(queryParameterData)
if err != nil {
retErr.PrivateErr = fmt.Errorf("unable to parse base64: %s", err)
return retErr
}
retErr.Response = string(rawResponseBuf)
gr, err := ioutil.ReadAll(newSaferFlateReader(bytes.NewBuffer(rawResponseBuf)))
if err != nil {
retErr.PrivateErr = err
return retErr
}
if err := xrv.Validate(bytes.NewReader(gr)); err != nil {
return err
}
doc := etree.NewDocument()
if err := doc.ReadFromBytes(rawResponseBuf); err != nil {
retErr.PrivateErr = err
return retErr
}
if err := sp.validateSignature(doc.Root()); err != nil {
retErr.PrivateErr = err
return retErr
}
var resp LogoutResponse
if err := unmarshalElement(doc.Root(), &resp); err != nil {
retErr.PrivateErr = err
return retErr
}
if err := sp.validateLogoutResponse(&resp); err != nil {
return err
}
return nil
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (m *Endpoint) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type Alias Endpoint
aux := &struct {
*Alias
}{
Alias: (*Alias)(m),
}
if err := d.DecodeElement(aux, &start); err != nil {
return err
}
var err error
m.Location, err = checkEndpointLocation(m.Binding, m.Location)
if err != nil {
return err
}
if m.ResponseLocation != "" {
m.ResponseLocation, err = checkEndpointLocation(m.Binding, m.ResponseLocation)
if err != nil {
return err
}
}
return nil
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func checkEndpointLocation(binding string, location string) (string, error) {
// Within the SAML standard, the complex type EndpointType describes a
// SAML protocol binding endpoint at which a SAML entity can be sent
// protocol messages. In particular, the location of an endpoint type is
// defined as follows in the Metadata for the OASIS Security Assertion
// Markup Language (SAML) V2.0 - 2.2.2 Complex Type EndpointType:
//
// Location [Required] A required URI attribute that specifies the
// location of the endpoint. The allowable syntax of this URI depends
// on the protocol binding.
switch binding {
case HTTPPostBinding,
HTTPRedirectBinding,
HTTPArtifactBinding,
SOAPBinding,
SOAPBindingV1:
locationURL, err := url.Parse(location)
if err != nil {
return "", fmt.Errorf("invalid url %q: %w", location, err)
}
switch locationURL.Scheme {
case "http", "https":
// ok
default:
return "", fmt.Errorf("invalid url scheme %q for binding %q",
locationURL.Scheme, binding)
}
default:
// We don't know what form location should take, but the protocol
// requires that we validate its syntax.
//
// In practice, lots of metadata contains random bindings, for example
// "urn:mace:shibboleth:1.0:profiles:AuthnRequest" from our own test suite.
//
// We can't fail, but we also can't allow a location parameter whose syntax we
// cannot verify. The least-bad course of action here is to set location to
// and empty string, and hope the caller doesn't care need it.
location = ""
}
return location, nil
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func (m *IndexedEndpoint) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type Alias IndexedEndpoint
aux := &struct {
*Alias
}{
Alias: (*Alias)(m),
}
if err := d.DecodeElement(aux, &start); err != nil {
return err
}
var err error
m.Location, err = checkEndpointLocation(m.Binding, m.Location)
if err != nil {
return err
}
if m.ResponseLocation != nil {
responseLocation, err := checkEndpointLocation(m.Binding, *m.ResponseLocation)
if err != nil {
return err
}
if responseLocation != "" {
m.ResponseLocation = &responseLocation
} else {
m.ResponseLocation = nil
}
}
return nil
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func TestMetadataValidatesUrlSchemeForProtocolBinding(t *testing.T) {
buf := golden.Get(t, "TestMetadataValidatesUrlSchemeForProtocolBinding_metadata.xml")
metadata := EntityDescriptor{}
err := xml.Unmarshal(buf, &metadata)
assert.Error(t, err, "invalid url scheme \"javascript\" for binding \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"")
} | 1 | Go | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
func findUnusedUIDGID(t *testing.T, not ...int) int {
for i := 1000; i < 65535; i++ {
if maybeValidUID(i) || maybeValidGID(i) {
continue
}
// Skip IDs that we're avoiding
if slices.Contains(not, i) {
continue
}
// Not a valid ID, not one we're avoiding... all good!
return i
}
t.Fatalf("unable to find an unused UID/GID pair")
return -1
} | 1 | Go | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
func findUnusedUID(t *testing.T, not ...int) int {
for i := 1000; i < 65535; i++ {
// Skip UIDs that might be valid
if maybeValidUID(i) {
continue
}
// Skip UIDs that we're avoiding
if slices.Contains(not, i) {
continue
}
// Not a valid UID, not one we're avoiding... all good!
return i
}
t.Fatalf("unable to find an unused UID")
return -1
} | 1 | Go | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
func findUnusedGID(t *testing.T, not ...int) int {
for i := 1000; i < 65535; i++ {
if maybeValidGID(i) {
continue
}
// Skip GIDs that we're avoiding
if slices.Contains(not, i) {
continue
}
// Not a valid GID, not one we're avoiding... all good!
return i
}
t.Fatalf("unable to find an unused GID")
return -1
} | 1 | Go | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
func maybeValidUID(id int) bool {
_, err := user.LookupId(strconv.Itoa(id))
if err == nil {
return true
}
var u1 user.UnknownUserIdError
if errors.As(err, &u1) {
return false
}
var u2 user.UnknownUserError
if errors.As(err, &u2) {
return false
}
// Some other error; might be valid
return true
} | 1 | Go | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
func maybeValidGID(id int) bool {
_, err := user.LookupGroupId(strconv.Itoa(id))
if err == nil {
return true
}
var u1 user.UnknownGroupIdError
if errors.As(err, &u1) {
return false
}
var u2 user.UnknownGroupError
if errors.As(err, &u2) {
return false
}
// Some other error; might be valid
return true
} | 1 | Go | CWE-269 | Improper Privilege Management | The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | safe |
func authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ok := authenticationHandler(w, r)
if ok {
next.ServeHTTP(w, r)
}
})
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func authenticationWithStore(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
store := helpers.Store(r)
var ok bool
db.StoreSession(store, r.URL.String(), func() {
ok = authenticationHandler(w, r)
})
if ok {
next.ServeHTTP(w, r)
}
})
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func TestAlpineMetadataSize(t *testing.T) {
os.Setenv("MAX_APK_METADATA_SIZE", "10")
viper.AutomaticEnv()
inputArchive, err := os.Open("tests/test_alpine.apk")
if err != nil {
t.Fatalf("could not open archive %v", err)
}
p := Package{}
err = p.Unmarshal(inputArchive)
if err == nil {
t.Fatal("expecting metadata too large err")
}
if !strings.Contains(err.Error(), "exceeds max allowed size 10") {
t.Fatalf("unexpected error %v", err)
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func TestAlpinePackage(t *testing.T) {
inputArchive, err := os.Open("tests/test_alpine.apk")
if err != nil {
t.Fatalf("could not open archive %v", err)
}
p := Package{}
err = p.Unmarshal(inputArchive)
if err != nil {
t.Fatalf("unmarshal error: %v", err)
}
pubKey, err := os.Open("tests/test_alpine.pub")
if err != nil {
t.Fatalf("could not open archive %v", err)
}
pub, err := x509.NewPublicKey(pubKey)
if err != nil {
t.Fatalf("failed to parse public key: %v", err)
}
if err = p.VerifySignature(pub.CryptoPubKey()); err != nil {
t.Fatalf("signature verification failed: %v", err)
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func TestJarMetadataSize(t *testing.T) {
type TestCase struct {
caseDesc string
entry V001Entry
expectUnmarshalSuccess bool
expectCanonicalizeSuccess bool
expectedVerifierSuccess bool
}
jarBytes, _ := os.ReadFile("tests/test.jar")
os.Setenv("MAX_JAR_METADATA_SIZE", "10")
viper.AutomaticEnv()
v := V001Entry{
JARModel: models.JarV001Schema{
Archive: &models.JarV001SchemaArchive{
Content: strfmt.Base64(jarBytes),
},
},
}
r := models.Jar{
APIVersion: swag.String(v.APIVersion()),
Spec: v.JARModel,
}
if err := v.Unmarshal(&r); err != nil {
t.Errorf("unexpected unmarshal failure: %v", err)
}
_, err := v.Canonicalize(context.TODO())
if err == nil {
t.Fatal("expecting metadata too large err")
}
if !strings.Contains(err.Error(), "exceeds max allowed size 10") {
t.Fatalf("unexpected error %v", err)
}
} | 1 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
func (m *IntotoV002SchemaContentEnvelopeSignaturesItems0) validateSig(formats strfmt.Registry) error {
if err := validate.Required("sig", "body", m.Sig); err != nil {
return err
}
return nil
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (m *IntotoV002SchemaContentEnvelopeSignaturesItems0) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validatePublicKey(formats); err != nil {
res = append(res, err)
}
if err := m.validateSig(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (m *IntotoV002SchemaContentEnvelopeSignaturesItems0) validatePublicKey(formats strfmt.Registry) error {
if err := validate.Required("publicKey", "body", m.PublicKey); err != nil {
return err
}
return nil
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (v *V002Entry) Unmarshal(pe models.ProposedEntry) error {
it, ok := pe.(*models.Intoto)
if !ok {
return errors.New("cannot unmarshal non Intoto v0.0.2 type")
}
var err error
if err := types.DecodeEntry(it.Spec, &v.IntotoObj); err != nil {
return err
}
// field validation
if err := v.IntotoObj.Validate(strfmt.Default); err != nil {
return err
}
if string(v.IntotoObj.Content.Envelope.Payload) == "" {
return nil
}
env := &dsse.Envelope{
Payload: string(v.IntotoObj.Content.Envelope.Payload),
PayloadType: *v.IntotoObj.Content.Envelope.PayloadType,
}
allPubKeyBytes := make([][]byte, 0)
for i, sig := range v.IntotoObj.Content.Envelope.Signatures {
if sig == nil {
v.IntotoObj.Content.Envelope.Signatures = slices.Delete(v.IntotoObj.Content.Envelope.Signatures, i, i)
continue
}
env.Signatures = append(env.Signatures, dsse.Signature{
KeyID: sig.Keyid,
Sig: string(*sig.Sig),
})
allPubKeyBytes = append(allPubKeyBytes, *sig.PublicKey)
}
if _, err := verifyEnvelope(allPubKeyBytes, env); err != nil {
return err
}
v.env = *env
decodedPayload, err := base64.StdEncoding.DecodeString(string(v.IntotoObj.Content.Envelope.Payload))
if err != nil {
return fmt.Errorf("could not decode envelope payload: %w", err)
}
h := sha256.Sum256(decodedPayload)
v.IntotoObj.Content.PayloadHash = &models.IntotoV002SchemaContentPayloadHash{
Algorithm: swag.String(models.IntotoV002SchemaContentPayloadHashAlgorithmSha256),
Value: swag.String(hex.EncodeToString(h[:])),
}
return nil
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (v V002Entry) Verifier() (pki.PublicKey, error) {
if v.IntotoObj.Content == nil || v.IntotoObj.Content.Envelope == nil {
return nil, errors.New("intoto v0.0.2 entry not initialized")
}
sigs := v.IntotoObj.Content.Envelope.Signatures
if len(sigs) == 0 {
return nil, errors.New("no signatures found on intoto entry")
}
return x509.NewPublicKey(bytes.NewReader(*v.IntotoObj.Content.Envelope.Signatures[0].PublicKey))
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (v V002Entry) Insertable() (bool, error) {
if v.IntotoObj.Content == nil {
return false, errors.New("missing content property")
}
if v.IntotoObj.Content.Envelope == nil {
return false, errors.New("missing envelope property")
}
if len(v.IntotoObj.Content.Envelope.Payload) == 0 {
return false, errors.New("missing envelope content")
}
if v.IntotoObj.Content.Envelope.PayloadType == nil || len(*v.IntotoObj.Content.Envelope.PayloadType) == 0 {
return false, errors.New("missing payloadType content")
}
if len(v.IntotoObj.Content.Envelope.Signatures) == 0 {
return false, errors.New("missing signatures content")
}
for _, sig := range v.IntotoObj.Content.Envelope.Signatures {
if sig == nil {
return false, errors.New("missing signature entry")
}
if sig.Sig == nil || len(*sig.Sig) == 0 {
return false, errors.New("missing signature content")
}
if sig.PublicKey == nil || len(*sig.PublicKey) == 0 {
return false, errors.New("missing publicKey content")
}
}
if v.env.Payload == "" || v.env.PayloadType == "" || len(v.env.Signatures) == 0 {
return false, errors.New("invalid DSSE envelope")
}
return true, nil
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func createRekorEnvelope(dsseEnv *dsse.Envelope, pub [][]byte) *models.IntotoV002SchemaContentEnvelope {
env := &models.IntotoV002SchemaContentEnvelope{}
b64 := strfmt.Base64([]byte(dsseEnv.Payload))
env.Payload = b64
env.PayloadType = &dsseEnv.PayloadType
for i, sig := range dsseEnv.Signatures {
keyBytes := strfmt.Base64(pub[i])
sigBytes := strfmt.Base64([]byte(sig.Sig))
env.Signatures = append(env.Signatures, &models.IntotoV002SchemaContentEnvelopeSignaturesItems0{
Keyid: sig.KeyID,
Sig: &sigBytes,
PublicKey: &keyBytes,
})
}
return env
} | 1 | Go | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
func (*FailedEventsManagerT) SaveFailedRecordIDs(taskRunIDFailedEventsMap map[string][]*FailedEventRowT, txn *sql.Tx) {
if !failedKeysEnabled {
return
}
for taskRunID, failedEvents := range taskRunIDFailedEventsMap {
table := getSqlSafeTablename(taskRunID)
sqlStatement := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
destination_id TEXT NOT NULL,
record_id JSONB NOT NULL,
created_at TIMESTAMP NOT NULL);`, table)
_, err := txn.Exec(sqlStatement)
if err != nil {
_ = txn.Rollback()
panic(err)
}
insertQuery := fmt.Sprintf(`INSERT INTO %s VALUES($1, $2, $3);`, table)
stmt, err := txn.Prepare(insertQuery)
if err != nil {
_ = txn.Rollback()
panic(err)
}
createdAt := time.Now()
for _, failedEvent := range failedEvents {
if len(failedEvent.RecordID) == 0 || !json.Valid(failedEvent.RecordID) {
pkgLogger.Infof("skipped adding invalid recordId: %s, to failed keys table: %s", failedEvent.RecordID, table)
continue
}
_, err = stmt.Exec(failedEvent.DestinationID, failedEvent.RecordID, createdAt)
if err != nil {
panic(err)
}
}
stmt.Close()
}
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.