code
stringlengths 12
2.05k
| label
int64 0
1
| programming_language
stringclasses 9
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
103
⌀ | description
stringlengths 36
1.23k
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
func (svc *Service) User(ctx context.Context, id uint) (*fleet.User, error) {
if err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionRead); err != nil {
return nil, err
}
return svc.ds.UserByID(ctx, id)
} | 0 | Go | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func (mr *MockCoreStorageMockRecorder) GetAuthorizeCodeSession(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAuthorizeCodeSession", reflect.TypeOf((*MockCoreStorage)(nil).GetAuthorizeCodeSession), arg0, arg1, arg2)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockRequester) GetRequestedAudience() fosite.Arguments {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRequestedAudience")
ret0, _ := ret[0].(fosite.Arguments)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {
r := &envoy_config_route_v3.Route{
Name: "pomerium-path-" + path,
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: httpCluster,
},
},
},
}
if !protected {
r.TypedPerFilterConfig = map[string]*any.Any{
"envoy.filters.http.ext_authz": disableExtAuthz,
}
}
return r, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func Test_safePrefix(t *testing.T) {
testCases := []struct {
desc string
value string
expected string
}{
{
desc: "host",
value: "https://example.com",
expected: "",
},
{
desc: "host with path",
value: "https://example.com/foo/bar?test",
expected: "",
},
{
desc: "path",
value: "/foo/bar",
expected: "/foo/bar",
},
{
desc: "path without leading slash",
value: "foo/bar",
expected: "foo/bar",
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "http://localhost", nil)
require.NoError(t, err)
req.Header.Set("X-Forwarded-Prefix", test.value)
prefix := safePrefix(req)
assert.Equal(t, test.expected, prefix)
})
}
} | 1 | Go | CWE-601 | URL Redirection to Untrusted Site ('Open Redirect') | A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. | https://cwe.mitre.org/data/definitions/601.html | safe |
func (m *MockTokenRevocationStorage) CreateRefreshTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Requester) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateRefreshTokenSession", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockClientCredentialsGrantStorage) CreateAccessTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Requester) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateAccessTokenSession", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAuthorizeCodeStrategy) GenerateAuthorizeCode(arg0 context.Context, arg1 fosite.Requester) (string, string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GenerateAuthorizeCode", arg0, arg1)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(string)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *StringValue) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StringValue: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StringValue: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthWrappers
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthWrappers
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipWrappers(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func (m *MockAccessResponder) GetAccessToken() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAccessToken")
ret0, _ := ret[0].(string)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func testExternalNameServiceTLS(namespace string) {
Specify("external name services work over https", func() {
t := f.T()
f.Certs.CreateSelfSignedCert(namespace, "backend-server-cert", "backend-server-cert", "echo")
f.Fixtures.EchoSecure.Deploy(namespace, "echo-tls")
externalNameService := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: "external-name-service-tls",
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeExternalName,
ExternalName: "echo-tls." + namespace,
Ports: []corev1.ServicePort{
{
Name: "https",
Port: 443,
Protocol: corev1.ProtocolTCP,
},
},
},
}
require.NoError(t, f.Client.Create(context.TODO(), externalNameService))
p := &contourv1.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: "external-name-proxy-tls",
},
Spec: contourv1.HTTPProxySpec{
VirtualHost: &contourv1.VirtualHost{
Fqdn: "tls.externalnameservice.projectcontour.io",
},
Routes: []contourv1.Route{
{
Services: []contourv1.Service{
{
Name: externalNameService.Name,
Port: 443,
Protocol: stringPtr("tls"),
},
},
RequestHeadersPolicy: &contourv1.HeadersPolicy{
Set: []contourv1.HeaderValue{
{
Name: "Host",
Value: externalNameService.Spec.ExternalName,
},
},
},
},
},
},
}
f.CreateHTTPProxyAndWaitFor(p, httpProxyValid)
res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{
Host: p.Spec.VirtualHost.Fqdn,
Condition: e2e.HasStatusCode(200),
})
require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode)
})
} | 0 | Go | CWE-610 | Externally Controlled Reference to a Resource in Another Sphere | The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/610.html | vulnerable |
func (m *MockAccessRequester) SetRequestedAudience(arg0 fosite.Arguments) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetRequestedAudience", arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {
buffer := make([]byte, uint64(len(aad))+uint64(len(nonce))+uint64(len(ciphertext))+8)
n := 0
n += copy(buffer, aad)
n += copy(buffer[n:], nonce)
n += copy(buffer[n:], ciphertext)
binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad))*8)
// According to documentation, Write() on hash.Hash never fails.
hmac := hmac.New(ctx.hash, ctx.integrityKey)
_, _ = hmac.Write(buffer)
return hmac.Sum(nil)[:ctx.authtagBytes]
} | 1 | Go | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
func IsBlockedLocalHostname(hostname string, allowlist []string) bool {
for _, allow := range allowlist {
if hostname == allow {
return false
}
}
ips, err := net.LookupIP(hostname)
if err != nil {
return true
}
for _, ip := range ips {
for _, cidr := range localCIDRs {
if cidr.Contains(ip) {
return true
}
}
}
return false
} | 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 (o *casaService) GetServerAppInfo(id, t string) model.ServerAppList {
head := make(map[string]string)
head["Authorization"] = GetToken()
infoS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/info/"+id+"?t="+t, head)
info := model.ServerAppList{}
json2.Unmarshal([]byte(gjson.Get(infoS, "data").String()), &info)
return info
} | 0 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
func (m *MockAuthorizeRequester) GetClient() fosite.Client {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetClient")
ret0, _ := ret[0].(fosite.Client)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *FakeMap) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMap
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FakeMap: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FakeMap: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMap
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMap
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMap
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Entries = append(m.Entries, &FakeMapEntry{})
if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipMap(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMap
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMap
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func mountNewCgroup(m *configs.Mount) error {
var (
data = m.Data
source = m.Source
)
if data == "systemd" {
data = cgroups.CgroupNamePrefix + data
source = "systemd"
}
if err := unix.Mount(source, m.Destination, m.Device, uintptr(m.Flags), data); err != nil {
return err
}
return nil
} | 0 | Go | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | vulnerable |
func (f *fragmentBuffer) push(buf []byte) (bool, error) {
if f.size()+len(buf) >= fragmentBufferMaxSize {
return false, errFragmentBufferOverflow
}
frag := new(fragment)
if err := frag.recordLayerHeader.Unmarshal(buf); err != nil {
return false, err
}
// fragment isn't a handshake, we don't need to handle it
if frag.recordLayerHeader.ContentType != protocol.ContentTypeHandshake {
return false, nil
}
for buf = buf[recordlayer.HeaderSize:]; len(buf) != 0; frag = new(fragment) {
if err := frag.handshakeHeader.Unmarshal(buf); err != nil {
return false, err
}
if _, ok := f.cache[frag.handshakeHeader.MessageSequence]; !ok {
f.cache[frag.handshakeHeader.MessageSequence] = []*fragment{}
}
// end index should be the length of handshake header but if the handshake
// was fragmented, we should keep them all
end := int(handshake.HeaderLength + frag.handshakeHeader.Length)
if size := len(buf); end > size {
end = size
}
// Discard all headers, when rebuilding the packet we will re-build
frag.data = append([]byte{}, buf[handshake.HeaderLength:end]...)
f.cache[frag.handshakeHeader.MessageSequence] = append(f.cache[frag.handshakeHeader.MessageSequence], frag)
buf = buf[end:]
}
return true, nil
} | 1 | Go | CWE-120 | Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') | The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. | https://cwe.mitre.org/data/definitions/120.html | safe |
func (p *BinaryProtocol) ReadBinary() ([]byte, error) {
size, e := p.ReadI32()
if e != nil {
return nil, e
}
if size < 0 {
return nil, invalidDataLength
}
if uint64(size) > p.trans.RemainingBytes() {
return nil, invalidDataLength
}
isize := int(size)
buf := make([]byte, isize)
_, err := io.ReadFull(p.trans, buf)
return buf, NewProtocolException(err)
} | 0 | Go | CWE-770 | Allocation of Resources Without Limits or Throttling | The software 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 | vulnerable |
func (*GetWalletLedgerRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{45}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (x *LeaderboardList) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[24]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error {
if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
return err
}
return svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID)
} | 0 | Go | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func ExampleClientAgent() {
// ssh-agent has a UNIX socket under $SSH_AUTH_SOCK
socket := os.Getenv("SSH_AUTH_SOCK")
conn, err := net.Dial("unix", socket)
if err != nil {
log.Fatalf("net.Dial: %v", err)
}
agentClient := agent.NewClient(conn)
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
// Use a callback rather than PublicKeys
// so we only consult the agent once the remote server
// wants it.
ssh.PublicKeysCallback(agentClient.Signers),
},
}
sshc, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatalf("Dial: %v", err)
}
// .. use sshc
sshc.Close()
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
func SearchUserByName(opt SearchOption) (us []*User, err error) {
// Prevent SQL inject.
opt.Keyword = strings.TrimSpace(opt.Keyword)
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.Split(opt.Keyword, " ")[0]
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.ToLower(opt.Keyword)
us = make([]*User, 0, opt.Limit)
err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
return us, err
} | 0 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software 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 | vulnerable |
func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) CreateAccessTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAccessTokenSession", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).CreateAccessTokenSession), arg0, arg1, arg2)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *Nested) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTheproto3
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Nested: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Nested: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Bunny", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTheproto3
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTheproto3
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTheproto3
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Bunny = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTheproto3(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthTheproto3
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthTheproto3
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func (m *MockClient) IsPublic() bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsPublic")
ret0, _ := ret[0].(bool)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAccessRequester) GrantAudience(arg0 string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "GrantAudience", arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func main() {
if len(os.Args) < 3 {
fatal(usage)
}
cmd, filename := os.Args[1], os.Args[2]
ff := archiver.MatchingFormat(filename)
if ff == nil {
fatalf("%s: Unsupported file extension", filename)
}
var err error
switch cmd {
case "make":
if len(os.Args) < 4 {
fatal(usage)
}
err = ff.Make(filename, os.Args[3:])
case "open":
dest, osErr := os.Getwd()
if osErr != nil {
fatal(err)
}
if len(os.Args) == 4 {
dest = os.Args[3]
} else if len(os.Args) > 4 {
fatal(usage)
}
err = ff.Open(filename, dest)
default:
fatal(usage)
}
if err != nil {
fatal(err)
}
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software 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 software 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 (m *NidOptEnum) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NidOptEnum: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NidOptEnum: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
m.Field1 = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Field1 |= TheTestEnum(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func (m *MockCoreStrategy) ValidateRefreshToken(arg0 context.Context, arg1 fosite.Requester, arg2 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ValidateRefreshToken", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAuthorizeRequester) GetRequestForm() url.Values {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRequestForm")
ret0, _ := ret[0].(url.Values)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func TestNewOAuth2ResourceServer(t *testing.T) {
newMockResourceServer(t)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (*StorageCollectionsList) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{34}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (m *MockAuthorizeRequester) SetResponseTypeHandled(arg0 string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetResponseTypeHandled", arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (x *UnlinkDeviceRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[35]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (m *Wilson) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCasttype
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Wilson: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Wilson: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Int64", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowCasttype
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Int64 = &v
default:
iNdEx = preIndex
skippy, err := skipCasttype(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthCasttype
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthCasttype
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func (f *flight4TestMockFlightConn) sessionKey() []byte { return nil } | 1 | Go | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
func NewLocalSessionCache(config Config) SessionCache {
ctx, ctxCancelFn := context.WithCancel(context.Background())
s := &LocalSessionCache{
config: config,
ctx: ctx,
ctxCancelFn: ctxCancelFn,
cache: make(map[uuid.UUID]*sessionCacheUser),
}
go func() {
ticker := time.NewTicker(2 * time.Duration(config.GetSession().TokenExpirySec) * time.Second)
for {
select {
case <-s.ctx.Done():
ticker.Stop()
return
case t := <-ticker.C:
tMs := t.UTC().Unix()
s.Lock()
for userID, cache := range s.cache {
for token, exp := range cache.sessionTokens {
if exp <= tMs {
delete(cache.sessionTokens, token)
}
}
for token, exp := range cache.refreshTokens {
if exp <= tMs {
delete(cache.refreshTokens, token)
}
}
if len(cache.sessionTokens) == 0 && len(cache.refreshTokens) == 0 {
delete(s.cache, userID)
}
}
s.Unlock()
}
}
}()
return s
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (b *Builder) buildMetricsHTTPConnectionManagerFilter() (*envoy_config_listener_v3.Filter, error) {
rc, err := b.buildRouteConfiguration("metrics", []*envoy_config_route_v3.VirtualHost{{
Name: "metrics",
Domains: []string{"*"},
Routes: []*envoy_config_route_v3.Route{{
Name: "metrics",
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: "/"},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: "pomerium-control-plane-http",
},
},
},
}},
}})
if err != nil {
return nil, err
}
tc := marshalAny(&envoy_http_connection_manager.HttpConnectionManager{
CodecType: envoy_http_connection_manager.HttpConnectionManager_AUTO,
StatPrefix: "metrics",
RouteSpecifier: &envoy_http_connection_manager.HttpConnectionManager_RouteConfig{
RouteConfig: rc,
},
HttpFilters: []*envoy_http_connection_manager.HttpFilter{{
Name: "envoy.filters.http.router",
}},
})
return &envoy_config_listener_v3.Filter{
Name: "envoy.filters.network.http_connection_manager",
ConfigType: &envoy_config_listener_v3.Filter_TypedConfig{
TypedConfig: tc,
},
}, nil
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func InstallNps() {
path := common.GetInstallPath()
if common.FileExists(path) {
log.Fatalf("the path %s has exist, does not support install", path)
}
MkidrDirAll(path, "conf", "web/static", "web/views")
//复制文件到对应目录
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil {
log.Fatalln(err)
}
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil {
log.Fatalln(err)
}
if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
log.Fatalln(err)
}
if !common.IsWindows() {
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/bin/nps"); err != nil {
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil {
log.Fatalln(err)
} else {
os.Chmod("/usr/local/bin/nps", 0755)
log.Println("Executable files have been copied to", "/usr/local/bin/nps")
}
} else {
os.Chmod("/usr/bin/nps", 0755)
log.Println("Executable files have been copied to", "/usr/bin/nps")
}
}
log.Println("install ok!")
log.Println("Static files and configuration files in the current directory will be useless")
log.Println("The new configuration file is located in", path, "you can edit them")
if !common.IsWindows() {
log.Println("You can start with nps test|start|stop|restart|status anywhere")
} else {
log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status")
}
} | 1 | Go | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | safe |
func TestSetupForwardAgent(t *testing.T) {
a, b, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer a.Close()
defer b.Close()
_, socket, cleanup := startAgent(t)
defer cleanup()
serverConf := ssh.ServerConfig{
NoClientAuth: true,
}
serverConf.AddHostKey(testSigners["rsa"])
incoming := make(chan *ssh.ServerConn, 1)
go func() {
conn, _, _, err := ssh.NewServerConn(a, &serverConf)
if err != nil {
t.Fatalf("Server: %v", err)
}
incoming <- conn
}()
conf := ssh.ClientConfig{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, chans, reqs, err := ssh.NewClientConn(b, "", &conf)
if err != nil {
t.Fatalf("NewClientConn: %v", err)
}
client := ssh.NewClient(conn, chans, reqs)
if err := ForwardToRemote(client, socket); err != nil {
t.Fatalf("SetupForwardAgent: %v", err)
}
server := <-incoming
ch, reqs, err := server.OpenChannel(channelType, nil)
if err != nil {
t.Fatalf("OpenChannel(%q): %v", channelType, err)
}
go ssh.DiscardRequests(reqs)
agentClient := NewClient(ch)
testAgentInterface(t, agentClient, testPrivateKeys["rsa"], nil, 0)
conn.Close()
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (x *UpdateGroupRequest) Reset() {
*x = UpdateGroupRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[37]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (m *UnorderedFields) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowIssue42
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: UnorderedFields: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: UnorderedFields: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field B", wireType)
}
var v uint64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
iNdEx += 8
m.B = &v
case 10:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field A", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowIssue42
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.A = &v
default:
iNdEx = preIndex
skippy, err := skipIssue42(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthIssue42
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthIssue42
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func (svc Service) TeamScheduleQuery(ctx context.Context, teamID uint, q *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
return nil, err
}
gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
if err != nil {
return nil, err
}
q.PackID = gp.ID
return svc.unauthorizedScheduleQuery(ctx, q)
} | 0 | Go | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string {
token := responder.GetAccessToken()
buffer := bytes.NewBufferString(token)
hash := sha256.New()
hash.Write(buffer.Bytes())
hashBuf := bytes.NewBuffer(hash.Sum([]byte{}))
len := hashBuf.Len()
return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:len/2])
} | 0 | Go | CWE-755 | Improper Handling of Exceptional Conditions | The software does not handle or incorrectly handles an exceptional condition. | https://cwe.mitre.org/data/definitions/755.html | vulnerable |
func (x *WalletLedgerList) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[43]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func canonicalMIMEHeaderKey(a []byte) string {
// See if a looks like a header key. If not, return it unchanged.
for _, c := range a {
if validHeaderFieldByte(c) {
continue
}
// Don't canonicalize.
return string(a)
}
upper := true
for i, c := range a {
// Canonicalize: first letter upper case
// and upper case after each dash.
// (Host, User-Agent, If-Modified-Since).
// MIME headers are ASCII only, so no Unicode issues.
if upper && 'a' <= c && c <= 'z' {
c -= toLower
} else if !upper && 'A' <= c && c <= 'Z' {
c += toLower
}
a[i] = c
upper = c == '-' // for next time
}
// The compiler recognizes m[string(byteSlice)] as a special
// case, so a copy of a's bytes into a new string does not
// happen in this map lookup:
if v := commonHeader[string(a)]; v != "" {
return v
}
return string(a)
} | 1 | Go | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
func TestXXMigrations(t *testing.T) {
if testing.Short() {
t.SkipNow()
return
}
migratest.RunPackrMigrationTests(
t,
migratest.MigrationSchemas{client.Migrations, consent.Migrations, oauth2.Migrations},
migratest.MigrationSchemas{nil, nil, dbal.FindMatchingTestMigrations("migrations/sql/tests/", oauth2.Migrations, oauth2.AssetNames(), oauth2.Asset)},
x.CleanSQL,
x.CleanSQL,
func(t *testing.T, dbName string, db *sqlx.DB, m, k, steps int) {
t.Run(fmt.Sprintf("poll=%d", k), func(t *testing.T) {
conf := internal.NewConfigurationWithDefaults()
reg := internal.NewRegistrySQL(conf, db)
if m != 2 {
t.Skip("Skipping polling unless it's the last migration schema")
return
}
s := reg.OAuth2Storage().(*oauth2.FositeSQLStore)
if dbName == "cockroach" {
k += 8
}
sig := fmt.Sprintf("%d-sig", k+1)
if k < 8 {
// With migration 8, all previous test data has been removed because the client is non-existent.
_, err := s.GetAccessTokenSession(context.Background(), sig, oauth2.NewSession(""))
require.Error(t, err)
return
}
_, err := s.GetAccessTokenSession(context.Background(), sig, oauth2.NewSession(""))
require.NoError(t, err)
_, err = s.GetRefreshTokenSession(context.Background(), sig, oauth2.NewSession(""))
require.NoError(t, err)
_, err = s.GetAuthorizeCodeSession(context.Background(), sig, oauth2.NewSession(""))
require.NoError(t, err)
_, err = s.GetOpenIDConnectSession(context.Background(), sig, &fosite.Request{Session: oauth2.NewSession("")})
require.NoError(t, err)
if k > 2 {
_, err = s.GetPKCERequestSession(context.Background(), sig, oauth2.NewSession(""))
require.NoError(t, err)
}
if k >= 11 {
require.True(t, errors.Is(s.ClientAssertionJWTValid(context.Background(), sig), fosite.ErrJTIKnown), "%+v", err)
}
})
},
)
} | 1 | Go | CWE-294 | Authentication Bypass by Capture-replay | A capture-replay flaw exists when the design of the software makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes). | https://cwe.mitre.org/data/definitions/294.html | safe |
func doSend(payload []byte, postURL string) error {
res, err := http.Post(postURL, "application/json", bytes.NewBuffer(payload))
if res == nil && err == nil {
err = fmt.Errorf("unknown error")
}
if err == nil && res.StatusCode != http.StatusNoContent {
err = fmt.Errorf("response status code %s", res.Status)
}
if err != nil {
return fmt.Errorf("failed to send discord notification: %v", err)
}
return nil
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
func TestGetDynamic(t *testing.T) {
savedServices := services
savedGetVCSDirFn := getVCSDirFn
defer func() {
services = savedServices
getVCSDirFn = savedGetVCSDirFn
}()
services = []*service{{pattern: regexp.MustCompile(".*"), get: testGet}}
getVCSDirFn = testGet
client := &http.Client{Transport: testTransport(testWeb)}
for _, tt := range getDynamicTests {
dir, err := getDynamic(context.Background(), client, tt.importPath, "")
if tt.dir == nil {
if err == nil {
t.Errorf("getDynamic(client, %q, etag) did not return expected error", tt.importPath)
}
continue
}
if err != nil {
t.Errorf("getDynamic(client, %q, etag) return unexpected error: %v", tt.importPath, err)
continue
}
if !cmp.Equal(dir, tt.dir) {
t.Errorf("getDynamic(client, %q, etag) =\n %+v,\nwant %+v", tt.importPath, dir, tt.dir)
for i, f := range dir.Files {
var want *File
if i < len(tt.dir.Files) {
want = tt.dir.Files[i]
}
t.Errorf("file %d = %+v, want %+v", i, f, want)
}
}
}
} | 0 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software 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 software 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 | vulnerable |
func (m *MockAccessResponder) SetAccessToken(arg0 string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetAccessToken", arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (mr *MockCoreStrategyMockRecorder) GenerateAccessToken(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateAccessToken", reflect.TypeOf((*MockCoreStrategy)(nil).GenerateAccessToken), arg0, arg1)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func ExampleSession_RequestPty() {
var hostKey ssh.PublicKey
// Create client config
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Connect to ssh server
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
log.Fatal("unable to create session: ", err)
}
defer session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 40, 80, modes); err != nil {
log.Fatal("request for pseudo terminal failed: ", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
log.Fatal("failed to start shell: ", err)
}
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (p *GatewayAPIProcessor) validateForwardTo(serviceName *string, port *gatewayapi_v1alpha1.PortNumber, namespace string) (*Service, error) {
// Verify the service is valid
if serviceName == nil {
return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServiceName must be specified")
}
// TODO: Do not require port to be present (#3352).
if port == nil {
return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServicePort must be specified")
}
meta := types.NamespacedName{Name: *serviceName, Namespace: namespace}
// TODO: Refactor EnsureService to take an int32 so conversion to intstr is not needed.
service, err := p.dag.EnsureService(meta, intstr.FromInt(int(*port)), p.source)
if err != nil {
return nil, fmt.Errorf("service %q does not exist", meta.Name)
}
return service, nil
} | 0 | Go | CWE-610 | Externally Controlled Reference to a Resource in Another Sphere | The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/610.html | vulnerable |
func (m *MockClientCredentialsGrantStorage) GetAccessTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Session) (fosite.Requester, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAccessTokenSession", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.Requester)
ret1, _ := ret[1].(error)
return ret0, ret1
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func generateDataset(dest []uint32, epoch uint64, cache []uint32) {
// Print some debug logs to allow analysis on low end devices
logger := log.New("epoch", epoch)
start := time.Now()
defer func() {
elapsed := time.Since(start)
logFn := logger.Debug
if elapsed > 3*time.Second {
logFn = logger.Info
}
logFn("Generated ethash verification cache", "elapsed", common.PrettyDuration(elapsed))
}()
// Figure out whether the bytes need to be swapped for the machine
swapped := !isLittleEndian()
// Convert our destination slice to a byte buffer
header := *(*reflect.SliceHeader)(unsafe.Pointer(&dest))
header.Len *= 4
header.Cap *= 4
dataset := *(*[]byte)(unsafe.Pointer(&header))
// Generate the dataset on many goroutines since it takes a while
threads := runtime.NumCPU()
size := uint64(len(dataset))
var pend sync.WaitGroup
pend.Add(threads)
var progress uint64
for i := 0; i < threads; i++ {
go func(id int) {
defer pend.Done()
// Create a hasher to reuse between invocations
keccak512 := makeHasher(sha3.NewLegacyKeccak512())
// Calculate the data segment this thread should generate
batch := uint32((size + hashBytes*uint64(threads) - 1) / (hashBytes * uint64(threads)))
first := uint32(id) * batch
limit := first + batch
if limit > uint32(size/hashBytes) {
limit = uint32(size / hashBytes)
}
// Calculate the dataset segment
percent := size / hashBytes / 100
for index := first; index < limit; index++ {
item := generateDatasetItem(cache, index, keccak512)
if swapped {
swap(item)
}
copy(dataset[index*hashBytes:], item)
if status := atomic.AddUint64(&progress, 1); status%percent == 0 {
logger.Info("Generating DAG in progress", "percentage", (status*100)/(size/hashBytes), "elapsed", common.PrettyDuration(time.Since(start)))
}
}
}(i)
}
// Wait for all the generators to finish and return
pend.Wait()
} | 0 | Go | CWE-682 | Incorrect Calculation | The software 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 | vulnerable |
func (cr *s3ChunkedReader) readS3ChunkHeader() {
// Read the first chunk line until CRLF.
var hexChunkSize, hexChunkSignature []byte
hexChunkSize, hexChunkSignature, cr.err = readChunkLine(cr.reader)
if cr.err != nil {
return
}
// <hex>;token=value - converts the hex into its uint64 form.
cr.n, cr.err = parseHexUint(hexChunkSize)
if cr.err != nil {
return
}
if cr.n == 0 {
cr.err = io.EOF
}
// Save the incoming chunk signature.
cr.chunkSignature = string(hexChunkSignature)
} | 0 | Go | CWE-924 | Improper Enforcement of Message Integrity During Transmission in a Communication Channel | The software establishes a communication channel with an endpoint and receives a message from that endpoint, but it does not sufficiently ensure that the message was not modified during transmission. | https://cwe.mitre.org/data/definitions/924.html | vulnerable |
func logNamespaceDiagnostics(spec *specs.Spec) {
sawMountNS := false
sawUserNS := false
sawUTSNS := false
for _, ns := range spec.Linux.Namespaces {
switch ns.Type {
case specs.CgroupNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join cgroup namespace, sorry about that")
} else {
logrus.Debugf("unable to create cgroup namespace, sorry about that")
}
case specs.IPCNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join IPC namespace, sorry about that")
} else {
logrus.Debugf("unable to create IPC namespace, sorry about that")
}
case specs.MountNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join mount namespace %q, creating a new one", ns.Path)
}
sawMountNS = true
case specs.NetworkNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join network namespace, sorry about that")
} else {
logrus.Debugf("unable to create network namespace, sorry about that")
}
case specs.PIDNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join PID namespace, sorry about that")
} else {
logrus.Debugf("unable to create PID namespace, sorry about that")
}
case specs.UserNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join user namespace %q, creating a new one", ns.Path)
}
sawUserNS = true
case specs.UTSNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join UTS namespace %q, creating a new one", ns.Path)
}
sawUTSNS = true
}
}
if !sawMountNS {
logrus.Debugf("mount namespace not requested, but creating a new one anyway")
}
if !sawUserNS {
logrus.Debugf("user namespace not requested, but creating a new one anyway")
}
if !sawUTSNS {
logrus.Debugf("UTS namespace not requested, but creating a new one anyway")
}
} | 0 | Go | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
func (x *DeleteStorageObjectRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[21]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (*UserList_User) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{39, 0}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func WithRelabeledContainerMounts(mountLabel string) oci.SpecOpts {
return func(ctx context.Context, client oci.Client, _ *containers.Container, s *runtimespec.Spec) (err error) {
if mountLabel == "" {
return nil
}
for _, m := range s.Mounts {
switch m.Destination {
case etcHosts, etcHostname, resolvConfPath:
if err := label.Relabel(m.Source, mountLabel, false); err != nil {
return err
}
}
}
return nil
}
} | 0 | Go | CWE-281 | Improper Preservation of Permissions | The software does not preserve permissions or incorrectly preserves permissions when copying, restoring, or sharing objects, which can cause them to have less restrictive permissions than intended. | https://cwe.mitre.org/data/definitions/281.html | vulnerable |
func (x *RuntimeInfo) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[41]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func sanitizeExtractPath(filePath string, destination string) error {
// to avoid zip slip (writing outside of the destination), we resolve
// the target path, and make sure it's nested in the intended
// destination, or bail otherwise.
destpath := filepath.Join(destination, filePath)
if !strings.HasPrefix(destpath, destination) {
return fmt.Errorf("%s: illegal file path", filePath)
}
return nil
} | 1 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software 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 software 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 TestSessionID(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverID := make(chan []byte, 1)
clientID := make(chan []byte, 1)
serverConf := &ServerConfig{
NoClientAuth: true,
}
serverConf.AddHostKey(testSigners["ecdsa"])
clientConf := &ClientConfig{
HostKeyCallback: InsecureIgnoreHostKey(),
User: "user",
}
go func() {
conn, chans, reqs, err := NewServerConn(c1, serverConf)
if err != nil {
t.Fatalf("server handshake: %v", err)
}
serverID <- conn.SessionID()
go DiscardRequests(reqs)
for ch := range chans {
ch.Reject(Prohibited, "")
}
}()
go func() {
conn, chans, reqs, err := NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client handshake: %v", err)
}
clientID <- conn.SessionID()
go DiscardRequests(reqs)
for ch := range chans {
ch.Reject(Prohibited, "")
}
}()
s := <-serverID
c := <-clientID
if bytes.Compare(s, c) != 0 {
t.Errorf("server session ID (%x) != client session ID (%x)", s, c)
} else if len(s) == 0 {
t.Errorf("client and server SessionID were empty.")
}
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (m *Duration) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowDuration
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Duration: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Duration: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Seconds", wireType)
}
m.Seconds = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowDuration
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Seconds |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Nanos", wireType)
}
m.Nanos = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowDuration
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Nanos |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipDuration(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthDuration
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthDuration
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | 0 | Go | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
func TestParse_Malformed(t *testing.T) {
data := []byte{
// PROXY protocol v2 magic header
0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
// v2 version, PROXY cmd
0x21,
// TCP, IPv4 (also works with 0x13,0x21,0x22,0x31,0x32)
0x12,
// Length
0x00, 0x00,
// src/dest address data _should_ be here but is omitted.
}
_, err := Parse(
bufio.NewReader(
bytes.NewReader(data)))
assert.Error(t, err)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (f *flight4TestMockCipherSuite) IsInitialized() bool {
f.t.Fatal("IsInitialized called with Certificate but not CertificateVerify")
return true
} | 1 | Go | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | safe |
func validHeaderFieldByte(b byte) bool {
return ('A' <= b && b <= 'Z') ||
('a' <= b && b <= 'z') ||
('0' <= b && b <= '9') ||
b == '-'
} | 1 | Go | CWE-444 | Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') | The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination. | https://cwe.mitre.org/data/definitions/444.html | safe |
func ProcessPrivileges() (*Privileges, error) {
ruid := C.getuid()
euid := C.geteuid()
rgid := C.getgid()
egid := C.getegid()
var groups []C.gid_t
n, err := C.getgroups(0, nil)
if n < 0 {
return nil, err
}
// If n == 0, the user isn't in any groups, so groups == nil is fine.
if n > 0 {
groups = make([]C.gid_t, n)
n, err = C.getgroups(n, &groups[0])
if n < 0 {
return nil, err
}
groups = groups[:n]
}
log.Printf("Current privs (real, effective): uid=(%d,%d) gid=(%d,%d) groups=%v",
ruid, euid, rgid, egid, groups)
return &Privileges{euid, egid, groups}, nil
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) CreateRefreshTokenSession(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRefreshTokenSession", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).CreateRefreshTokenSession), arg0, arg1, arg2)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAuthorizeRequester) GetRequestedAudience() fosite.Arguments {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRequestedAudience")
ret0, _ := ret[0].(fosite.Arguments)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (*WriteStorageObjectRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{44}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
added, err := cs.addVote(vote, peerID)
if err != nil {
// If the vote height is off, we'll just ignore it,
// But if it's a conflicting sig, add it to the cs.evpool.
// If it's otherwise invalid, punish peer.
// nolint: gocritic
if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
if cs.privValidatorPubKey == nil {
return false, errPubKeyIsNotSet
}
if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
cs.Logger.Error(
"Found conflicting vote from ourselves. Did you unsafe_reset a validator?",
"height",
vote.Height,
"round",
vote.Round,
"type",
vote.Type)
return added, err
}
// report conflicting votes to the evidence pool
cs.evpool.ReportConflictingVotes(voteErr.VoteA, voteErr.VoteB)
cs.Logger.Info("Found and sent conflicting votes to the evidence pool",
"VoteA", voteErr.VoteA,
"VoteB", voteErr.VoteB,
)
return added, err
} else if err == types.ErrVoteNonDeterministicSignature {
cs.Logger.Debug("Vote has non-deterministic signature", "err", err)
} else {
// Either
// 1) bad peer OR
// 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
// 3) tmkms use with multiple validators connecting to a single tmkms instance
// (https://github.com/tendermint/tendermint/issues/3839).
cs.Logger.Info("Error attempting to add vote", "err", err)
return added, ErrAddingVote
}
}
return added, nil
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The software 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 (mr *MockAuthorizeRequesterMockRecorder) GrantScope(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GrantScope", reflect.TypeOf((*MockAuthorizeRequester)(nil).GrantScope), arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) {
plugin, exists := hs.pluginStore.Plugin(ctx, pluginId)
if !exists {
return nil, plugins.NotFoundError{PluginID: pluginId}
}
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
// on plugin the folder structure on disk and not user input.
path := filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToUpper(name)))
exists, err := fs.Exists(path)
if err != nil {
return nil, err
}
if !exists {
path = filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToLower(name)))
}
exists, err = fs.Exists(path)
if err != nil {
return nil, err
}
if !exists {
return make([]byte, 0), nil
}
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
// on plugin the folder structure on disk and not user input.
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return data, nil
} | 0 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software 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 software 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 | vulnerable |
func TestCertLogin(t *testing.T) {
s := newServer(t)
defer s.Shutdown()
// Use a key different from the default.
clientKey := testSigners["dsa"]
caAuthKey := testSigners["ecdsa"]
cert := &ssh.Certificate{
Key: clientKey.PublicKey(),
ValidPrincipals: []string{username()},
CertType: ssh.UserCert,
ValidBefore: ssh.CertTimeInfinity,
}
if err := cert.SignCert(rand.Reader, caAuthKey); err != nil {
t.Fatalf("SetSignature: %v", err)
}
certSigner, err := ssh.NewCertSigner(cert, clientKey)
if err != nil {
t.Fatalf("NewCertSigner: %v", err)
}
conf := &ssh.ClientConfig{
User: username(),
}
conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner))
client, err := s.TryDial(conf)
if err != nil {
t.Fatalf("TryDial: %v", err)
}
client.Close()
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
func (mr *MockOpenIDConnectTokenStrategyMockRecorder) GenerateIDToken(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateIDToken", reflect.TypeOf((*MockOpenIDConnectTokenStrategy)(nil).GenerateIDToken), arg0, arg1)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockPKCERequestStorage) GetPKCERequestSession(arg0 context.Context, arg1 string, arg2 fosite.Session) (fosite.Requester, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPKCERequestSession", arg0, arg1, arg2)
ret0, _ := ret[0].(fosite.Requester)
ret1, _ := ret[1].(error)
return ret0, ret1
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (mr *MockAuthorizeRequesterMockRecorder) GetRequestedAt() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedAt", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetRequestedAt))
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (x *DeleteGroupRequest) Reset() {
*x = DeleteGroupRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (m *MockResourceOwnerPasswordCredentialsGrantStorage) CreateRefreshTokenSession(arg0 context.Context, arg1 string, arg2 fosite.Requester) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateRefreshTokenSession", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (*UnlinkDeviceRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{35}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
if len(conds) == 0 {
if err := f.addRuleWrapper(call, action, exact, nil); err != nil {
return err
}
} else {
// We don't support conditional filtering in library version v2.1
if !checkVersionAbove(2, 2, 1) {
return VersionError{
message: "conditional filtering is not supported",
minimum: "2.2.1",
}
}
for _, cond := range conds {
cmpStruct := C.make_struct_arg_cmp(C.uint(cond.Argument), cond.Op.toNative(), C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))
defer C.free(cmpStruct)
if err := f.addRuleWrapper(call, action, exact, C.scmp_cast_t(cmpStruct)); err != nil {
return err
}
}
}
return nil
} | 0 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
func SetProcessPrivileges(privs *Privileges) error {
log.Printf("Setting euid=%d egid=%d groups=%v", privs.euid, privs.egid, privs.groups)
// If setting privs as root, we need to set the euid to 0 first, so that
// we will have the necessary permissions to make the other changes to
// the groups/egid/euid, regardless of our original euid.
C.seteuid(0)
// Seperately handle the case where the user is in no groups.
numGroups := C.size_t(len(privs.groups))
groupsPtr := (*C.gid_t)(nil)
if numGroups > 0 {
groupsPtr = &privs.groups[0]
}
if res, err := C.setgroups(numGroups, groupsPtr); res < 0 {
return errors.Wrapf(err.(syscall.Errno), "setting groups")
}
if res, err := C.setegid(privs.egid); res < 0 {
return errors.Wrapf(err.(syscall.Errno), "setting egid")
}
if res, err := C.seteuid(privs.euid); res < 0 {
return errors.Wrapf(err.(syscall.Errno), "setting euid")
}
ProcessPrivileges()
return nil
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
func (mr *MockAccessRequesterMockRecorder) SetID(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetID", reflect.TypeOf((*MockAccessRequester)(nil).SetID), arg0)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAuthorizeEndpointHandler) HandleAuthorizeEndpointRequest(arg0 context.Context, arg1 fosite.AuthorizeRequester, arg2 fosite.AuthorizeResponder) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HandleAuthorizeEndpointRequest", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (m *MockAccessRequester) GetGrantTypes() fosite.Arguments {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetGrantTypes")
ret0, _ := ret[0].(fosite.Arguments)
return ret0
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func (svc Service) GetTeamScheduledQueries(ctx context.Context, teamID uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionRead); err != nil {
return nil, err
}
gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
if err != nil {
return nil, err
}
return svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)
} | 0 | Go | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func (x *ListPurchasesRequest) Reset() {
*x = ListPurchasesRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[28]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | 0 | Go | CWE-613 | Insufficient Session Expiration | According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." | https://cwe.mitre.org/data/definitions/613.html | vulnerable |
func (mr *MockAuthorizeResponderMockRecorder) GetHeader() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHeader", reflect.TypeOf((*MockAuthorizeResponder)(nil).GetHeader))
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func isAdminOfTheModifiedTeams(currentUser *fleet.User, originalUserTeams, newUserTeams []fleet.UserTeam) bool {
// If the user is of the right global role, then they can modify the teams
if currentUser.GlobalRole != nil && (*currentUser.GlobalRole == fleet.RoleAdmin || *currentUser.GlobalRole == fleet.RoleMaintainer) {
return true
}
// otherwise, gather the resulting teams
resultingTeams := make(map[uint]string)
for _, team := range newUserTeams {
resultingTeams[team.ID] = team.Role
}
// and see which ones were removed or changed from the original
teamsAffected := make(map[uint]struct{})
for _, team := range originalUserTeams {
if resultingTeams[team.ID] != team.Role {
teamsAffected[team.ID] = struct{}{}
}
}
// then gather the teams the current user is admin for
currentUserTeamAdmin := make(map[uint]struct{})
for _, team := range currentUser.Teams {
if team.Role == fleet.RoleAdmin {
currentUserTeamAdmin[team.ID] = struct{}{}
}
}
// and let's check that the teams that were either removed or changed are also teams this user is an admin of
for teamID := range teamsAffected {
if _, ok := currentUserTeamAdmin[teamID]; !ok {
return false
}
}
return true
} | 0 | Go | CWE-863 | Incorrect Authorization | The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | vulnerable |
func SearchUserByName(opt SearchOption) (us []*User, err error) {
opt.Keyword = FilterSQLInject(opt.Keyword)
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.ToLower(opt.Keyword)
us = make([]*User, 0, opt.Limit)
err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
return us, err
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The software 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 |
func (mr *MockOpenIDConnectRequestStorageMockRecorder) GetOpenIDConnectSession(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOpenIDConnectSession", reflect.TypeOf((*MockOpenIDConnectRequestStorage)(nil).GetOpenIDConnectSession), arg0, arg1, arg2)
} | 1 | Go | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
func MakeEmailPrimary(email *EmailAddress) error {
has, err := x.Get(email)
if err != nil {
return err
} else if !has {
return errors.EmailNotFound{Email: email.Email}
}
if !email.IsActivated {
return errors.EmailNotVerified{Email: email.Email}
}
user := &User{ID: email.UID}
has, err = x.Get(user)
if err != nil {
return err
} else if !has {
return errors.UserNotExist{UserID: email.UID}
}
// Make sure the former primary email doesn't disappear.
formerPrimaryEmail := &EmailAddress{Email: user.Email}
has, err = x.Get(formerPrimaryEmail)
if err != nil {
return err
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if !has {
formerPrimaryEmail.UID = user.ID
formerPrimaryEmail.IsActivated = user.IsActive
if _, err = sess.Insert(formerPrimaryEmail); err != nil {
return err
}
}
user.Email = email.Email
if _, err = sess.ID(user.ID).AllCols().Update(user); err != nil {
return err
}
return sess.Commit()
} | 0 | Go | CWE-281 | Improper Preservation of Permissions | The software does not preserve permissions or incorrectly preserves permissions when copying, restoring, or sharing objects, which can cause them to have less restrictive permissions than intended. | https://cwe.mitre.org/data/definitions/281.html | vulnerable |
func (s *ConsoleServer) lookupConsoleUser(ctx context.Context, unameOrEmail, password string) (id uuid.UUID, uname string, email string, role console.UserRole, err error) {
role = console.UserRole_USER_ROLE_UNKNOWN
query := "SELECT id, username, email, role, password, disable_time FROM console_user WHERE username = $1 OR email = $1"
var dbPassword []byte
var dbDisableTime pgtype.Timestamptz
err = s.db.QueryRowContext(ctx, query, unameOrEmail).Scan(&id, &uname, &email, &role, &dbPassword, &dbDisableTime)
if err != nil {
if err == sql.ErrNoRows {
err = nil
}
return
}
// Check if it's disabled.
if dbDisableTime.Status == pgtype.Present && dbDisableTime.Time.Unix() != 0 {
s.logger.Info("Console user account is disabled.", zap.String("username", unameOrEmail))
err = status.Error(codes.PermissionDenied, "Invalid credentials.")
return
}
// Check password
err = bcrypt.CompareHashAndPassword(dbPassword, []byte(password))
if err != nil {
err = status.Error(codes.Unauthenticated, "Invalid credentials.")
return
}
return
} | 0 | Go | CWE-307 | Improper Restriction of Excessive Authentication Attempts | The software does not implement sufficient measures to prevent multiple failed authentication attempts within in a short time frame, making it more susceptible to brute force attacks. | https://cwe.mitre.org/data/definitions/307.html | vulnerable |
func main() {
if len(os.Args) < 3 {
fatal(usage)
}
cmd, filename := os.Args[1], os.Args[2]
ff := archiver.MatchingFormat(filename)
if ff == nil {
fatalf("%s: Unsupported file extension", filename)
}
var err error
switch cmd {
case "make":
if len(os.Args) < 4 {
fatal(usage)
}
err = ff.Make(filename, os.Args[3:])
case "open":
dest := ""
if len(os.Args) == 4 {
dest = os.Args[3]
} else if len(os.Args) > 4 {
fatal(usage)
}
err = ff.Open(filename, dest)
default:
fatal(usage)
}
if err != nil {
fatal(err)
}
} | 0 | Go | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software 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 software 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 | vulnerable |
return utils.WithProcfd(rootfs, m.Destination, func(procfd string) error {
return mount(source, m.Destination, procfd, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "")
}) | 1 | Go | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
func NewHandle(pamh unsafe.Pointer) (*Handle, error) {
var err error
h := &Handle{
handle: (*C.pam_handle_t)(pamh),
status: C.PAM_SUCCESS,
}
var pamUsername *C.char
h.status = C.pam_get_user(h.handle, &pamUsername, nil)
if err = h.err(); err != nil {
return nil, err
}
h.PamUser, err = user.Lookup(C.GoString(pamUsername))
return h, err
} | 1 | Go | NVD-CWE-noinfo | null | null | null | safe |
Subsets and Splits