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 (m *UnrecognizedWithInner_Inner) 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: Inner: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Inner: 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) } var v uint32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint32(b&0x7F) << shift if b < 0x80 { break } } m.Field1 = &v 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 } 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 *CustomContainer) 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: CustomContainer: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CustomContainer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CustomStruct", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.CustomStruct.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex 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 (AppModuleBasic) ConsensusVersion() uint64 { return 1 }
0
Go
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
appendMessage = func(targetOffset uint32) bool { for _, f := range frags { if f.handshakeHeader.FragmentOffset == targetOffset { fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength) if fragmentEnd != f.handshakeHeader.Length && f.handshakeHeader.FragmentLength != 0 { if !appendMessage(fragmentEnd) { return false } } rawMessage = append(f.data, rawMessage...) return true } } return false }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (h *Handle) StartAsPamUser() error { if _, err := security.UserKeyringID(h.PamUser, true); err != nil { log.Printf("Setting up keyrings in PAM: %v", err) } userPrivs, err := security.UserPrivileges(h.PamUser) if err != nil { return err } if h.origPrivs, err = security.ProcessPrivileges(); err != nil { return err } return security.SetProcessPrivileges(userPrivs) }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (m *Unrecognized) 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: Unrecognized: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Unrecognized: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } 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 ErrInvalidLengthThetest } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) m.Field1 = &s iNdEx = postIndex 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 } 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 ReadWriteProtocolTest(t *testing.T, protocolFactory ProtocolFactory) { buf := bytes.NewBuffer(make([]byte, 0, 1024)) l := HTTPClientSetupForTest(t) defer l.Close() transports := []TransportFactory{ NewMemoryBufferTransportFactory(1024), NewStreamTransportFactory(buf, buf, true), NewFramedTransportFactory(NewMemoryBufferTransportFactory(1024)), NewHTTPPostClientTransportFactory("http://" + l.Addr().String()), } doForAllTransports := func(protTest protocolTest) { for _, tf := range transports { trans := tf.GetTransport(nil) p := protocolFactory.GetProtocol(trans) protTest(t, p, trans) trans.Close() } } doForAllTransports(ReadWriteBool) doForAllTransports(ReadWriteByte) doForAllTransports(ReadWriteI16) doForAllTransports(ReadWriteI32) doForAllTransports(ReadWriteI64) doForAllTransports(ReadWriteDouble) doForAllTransports(ReadWriteFloat) doForAllTransports(ReadWriteString) doForAllTransports(ReadWriteBinary) doForAllTransports(ReadWriteStruct) // perform set of many sequenced reads and writes doForAllTransports(func(t testing.TB, p Protocol, trans Transport) { ReadWriteI64(t, p, trans) ReadWriteDouble(t, p, trans) ReadWriteFloat(t, p, trans) ReadWriteBinary(t, p, trans) ReadWriteByte(t, p, trans) ReadWriteStruct(t, p, trans) }) }
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 (mr *MockAuthorizeRequesterMockRecorder) GetSession() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSession", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetSession)) }
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 validateAndCreateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) { c.Data["Webhook"] = w if c.HasError() { c.Success(orCtx.TmplNew) return } field, msg, ok := validateWebhook(c.Locale, w) if !ok { c.FormErr(field) c.RenderWithErr(msg, orCtx.TmplNew, nil) return } if err := w.UpdateEvent(); err != nil { c.Error(err, "update event") return } else if err := db.CreateWebhook(w); err != nil { c.Error(err, "create webhook") return } c.Flash.Success(c.Tr("repo.settings.add_hook_success")) c.Redirect(orCtx.Link + "/settings/hooks") }
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 (mr *MockAccessRequesterMockRecorder) GetGrantedAudience() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGrantedAudience", reflect.TypeOf((*MockAccessRequester)(nil).GetGrantedAudience)) }
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) 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 (x *ListAccountsRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[26] 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 (g DashboardHandler) Append(router *mux.Router) { if g.Assets == nil { log.WithoutContext().Error("No assets for dashboard") return } // Expose dashboard router.Methods(http.MethodGet). Path("/"). HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { http.Redirect(resp, req, safePrefix(req)+"/dashboard/", http.StatusFound) }) router.Methods(http.MethodGet). PathPrefix("/dashboard/"). Handler(http.StripPrefix("/dashboard/", http.FileServer(g.Assets))) }
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 (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte { // Output buffer -- must take care not to mangle plaintext input. ciphertext := make([]byte, len(plaintext)+ctx.Overhead())[:len(plaintext)] copy(ciphertext, plaintext) ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize()) cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce) cbc.CryptBlocks(ciphertext, ciphertext) authtag := ctx.computeAuthTag(data, nonce, ciphertext) ret, out := resize(dst, len(dst)+len(ciphertext)+len(authtag)) copy(out, ciphertext) copy(out[len(ciphertext):], authtag) return ret }
0
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
vulnerable
func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) { alreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) if !alreadyAuthd { // First ensure the user has access to list hosts, then check the specific // host once team_id is loaded. if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return nil, err } } host, err := svc.ds.Host(ctx, id, false) if err != nil { return nil, ctxerr.Wrap(ctx, err, "get host") } if !alreadyAuthd { // Authorize again with team loaded now that we have team_id if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } return svc.getHostDetails(ctx, host) }
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 *MockCoreStrategyMockRecorder) GenerateRefreshToken(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateRefreshToken", reflect.TypeOf((*MockCoreStrategy)(nil).GenerateRefreshToken), 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 *MyType) 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 ErrIntOverflowAsym } 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: MyType: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MyType: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipAsym(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthAsym } if (iNdEx + skippy) < 0 { return ErrInvalidLengthAsym } 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 (mr *MockAccessRequesterMockRecorder) GrantScope(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GrantScope", reflect.TypeOf((*MockAccessRequester)(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 (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { h.L.Warnln("It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.") h.L.Warnln("A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.") t, err := template.New("consent").Parse(` <html> <head> <title>Misconfigured consent/login URL</title> </head> <body> <p> It looks like you forgot to set the consent/login provider url, which can be set using the <code>OAUTH2_CONSENT_URL</code> and <code>OAUTH2_LOGIN_URL</code> environment variable. </p> <p> If you are an administrator, please read <a href="https://www.ory.sh/docs"> the guide</a> to understand what you need to do. If you are a user, please contact the administrator. </p> </body> </html> `) if err != nil { h.H.WriteError(w, r, err) return } if err := t.Execute(w, nil); err != nil { h.H.WriteError(w, r, err) return } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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 p224AlternativeToBig(in *p224FieldElement) *big.Int { ret := new(big.Int) tmp := new(big.Int) for i := len(in) - 1; i >= 0; i-- { ret.Lsh(ret, 28) tmp.SetInt64(int64(in[i])) ret.Add(ret, tmp) } ret.Mod(ret, P224().Params().P) return ret }
1
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
safe
func SearchRepos(ctx *middleware.Context) { opt := models.SearchOption{ Keyword: path.Base(ctx.Query("q")), Uid: com.StrTo(ctx.Query("uid")).MustInt64(), Limit: com.StrTo(ctx.Query("limit")).MustInt(), } if opt.Limit == 0 { opt.Limit = 10 } // Check visibility. if ctx.IsSigned && opt.Uid > 0 { if ctx.User.Id == opt.Uid { opt.Private = true } else { u, err := models.GetUserById(opt.Uid) if err != nil { ctx.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) return } if u.IsOrganization() && u.IsOrgOwner(ctx.User.Id) { opt.Private = true } // FIXME: how about collaborators? } } repos, err := models.SearchRepositoryByName(opt) if err != nil { ctx.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) return } results := make([]*repo, len(repos)) for i := range repos { if err = repos[i].GetOwner(); err != nil { ctx.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) return } results[i] = &repo{ RepoLink: path.Join(repos[i].Owner.Name, repos[i].Name), } } ctx.Render.JSON(200, map[string]interface{}{ "ok": true, "data": results, }) }
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 (svc *Service) RefetchHost(ctx context.Context, id uint) error { if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) { if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return err } host, err := svc.ds.HostLite(ctx, id) if err != nil { return ctxerr.Wrap(ctx, err, "find host for refetch") } // We verify fleet.ActionRead instead of fleet.ActionWrite because we want to allow // observers to be able to refetch hosts. if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return err } } if err := svc.ds.UpdateHostRefetchRequested(ctx, id, true); err != nil { return ctxerr.Wrap(ctx, err, "save host") } return nil }
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 generateHMAC(data []byte, key *[32]byte) []byte { h := hmac.New(sha512.New512_256, key[:]) h.Write(data) return h.Sum(nil) }
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 (svc *Service) GlobalScheduleQuery(ctx context.Context, sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) { if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil { return nil, err } gp, err := svc.ds.EnsureGlobalPack(ctx) if err != nil { return nil, err } sq.PackID = gp.ID return svc.ScheduleQuery(ctx, sq) }
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 checkVersion() { // Templates. data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION")) if err != nil { log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err) } if string(data) != setting.AppVer { log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?") } // Check dependency version. macaronVer := git.MustParseVersion(strings.Join(strings.Split(macaron.Version(), ".")[:3], ".")) if macaronVer.LessThan(git.MustParseVersion("0.2.3")) { log.Fatal(4, "Package macaron version is too old, did you forget to update?(github.com/Unknwon/macaron)") } i18nVer := git.MustParseVersion(i18n.Version()) if i18nVer.LessThan(git.MustParseVersion("0.0.2")) { log.Fatal(4, "Package i18n version is too old, did you forget to update?(github.com/macaron-contrib/i18n)") } sessionVer := git.MustParseVersion(session.Version()) if sessionVer.LessThan(git.MustParseVersion("0.0.5")) { log.Fatal(4, "Package session version is too old, did you forget to update?(github.com/macaron-contrib/session)") } }
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 *MockCoreStorageMockRecorder) CreateAuthorizeCodeSession(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAuthorizeCodeSession", reflect.TypeOf((*MockCoreStorage)(nil).CreateAuthorizeCodeSession), 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 (x *WalletLedger) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[42] 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 MakeEmailPrimary(userID int64, email *EmailAddress) error { has, err := x.Get(email) if err != nil { return err } else if !has { return errors.EmailNotFound{Email: email.Email} } if email.UID != userID { return errors.New("not the owner of the 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() }
1
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
safe
func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error { // First get a list of a all tmpfs mounts tmpfs := []string{} for _, m := range mounts { switch m.Device { case "tmpfs": tmpfs = append(tmpfs, m.Destination) } } // Now go through all mounts and create the mountpoints // if the mountpoints are not on a tmpfs, as CRIU will // restore the complete tmpfs content from its checkpoint. umounts := []string{} defer func() { for _, u := range umounts { if e := unix.Unmount(u, unix.MNT_DETACH); e != nil { if e != unix.EINVAL { // Ignore EINVAL as it means 'target is not a mount point.' // It probably has already been unmounted. logrus.Warnf("Error during cleanup unmounting of %q (%v)", u, e) } } } }() for _, m := range mounts { if !isPathInPrefixList(m.Destination, tmpfs) { if err := c.makeCriuRestoreMountpoints(m); err != nil { return err } // If the mount point is a bind mount, we need to mount // it now so that runc can create the necessary mount // points for mounts in bind mounts. // This also happens during initial container creation. // Without this CRIU restore will fail // See: https://github.com/opencontainers/runc/issues/2748 // It is also not necessary to order the mount points // because during initial container creation mounts are // set up in the order they are configured. if m.Device == "bind" { if err := unix.Mount(m.Source, m.Destination, "", unix.MS_BIND|unix.MS_REC, ""); err != nil { return errorsf.Wrapf(err, "unable to bind mount %q to %q", m.Source, m.Destination) } umounts = append(umounts, m.Destination) } } } 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 (*WalletLedgerList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{43} }
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 Test_requireProxyProtocol(t *testing.T) { b := New("local-grpc", "local-http", nil, nil) t.Run("required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: true, InsecureServer: true, }}) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, `[ { "name": "envoy.filters.listener.proxy_protocol", "typedConfig": { "@type": "type.googleapis.com/envoy.extensions.filters.listener.proxy_protocol.v3.ProxyProtocol" } } ]`, li.GetListenerFilters()) }) t.Run("not required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: false, InsecureServer: true, }}) require.NoError(t, err) assert.Len(t, li.GetListenerFilters(), 0) }) }
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 (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{29} }
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 (mgr *MetricsManager) OnConfigChange(ctx context.Context, cfg *Config) { mgr.mu.Lock() defer mgr.mu.Unlock() mgr.updateInfo(cfg) mgr.updateServer(cfg) }
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 (m *MockRequester) AppendRequestedScope(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "AppendRequestedScope", 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 *MockAuthorizeRequesterMockRecorder) GetRequestedScopes() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedScopes", reflect.TypeOf((*MockAuthorizeRequester)(nil).GetRequestedScopes)) }
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 *Nil) 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: Nil: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Nil: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { 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 *MockResourceOwnerPasswordCredentialsGrantStorage) DeleteAccessTokenSession(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteAccessTokenSession", arg0, arg1) 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) GetGrantedAudience() fosite.Arguments { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetGrantedAudience") 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 (*Config) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{14} }
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 *StatusList_Status) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[49] 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 TestHostKeyCheck(t *testing.T) { for _, tt := range []struct { name string wantError string key PublicKey }{ {"no callback", "must specify HostKeyCallback", nil}, {"correct key", "", testSigners["rsa"].PublicKey()}, {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, } { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) clientConf := ClientConfig{ User: "user", } if tt.key != nil { clientConf.HostKeyCallback = FixedHostKey(tt.key) } _, _, _, err = NewClientConn(c2, "", &clientConf) if err != nil { if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { t.Errorf("%s: got error %q, missing %q", err.Error(), tt.wantError) } } else if tt.wantError != "" { t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) } } }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (m *MockCoreStorage) DeleteAccessTokenSession(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteAccessTokenSession", arg0, arg1) 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) GetGrantedScopes() fosite.Arguments { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetGrantedScopes") 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 TestAddEvidenceFromConsensus(t *testing.T) { var height int64 = 10 pool, val := defaultTestPool(height) ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, val, evidenceChainID) require.NoError(t, pool.AddEvidenceFromConsensus(ev)) // evidence from consensus should not be added immediately but reside in the consensus buffer evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes) require.Empty(t, evList) require.Zero(t, evSize) next := pool.EvidenceFront() require.Nil(t, next) // move to next height and update state and evidence pool state := pool.State() state.LastBlockHeight++ pool.Update(state, []types.Evidence{}) // should be able to retrieve evidence from pool evList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes) require.Equal(t, []types.Evidence{ev}, evList) // shouldn't be able to submit the same evidence twice require.NoError(t, pool.AddEvidenceFromConsensus(ev)) state = pool.State() state.LastBlockHeight++ pool.Update(state, []types.Evidence{}) evList2, _ := pool.PendingEvidence(defaultEvidenceMaxBytes) require.Equal(t, evList, evList2) }
0
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
vulnerable
func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error { hashes := make([][]byte, len(evList)) for idx, ev := range evList { ok := evpool.fastCheck(ev) if !ok { // check that the evidence isn't already committed if evpool.isCommitted(ev) { return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")} } err := evpool.verify(ev) if err != nil { return &types.ErrInvalidEvidence{Evidence: ev, Reason: err} } if err := evpool.addPendingEvidence(ev); err != nil { // Something went wrong with adding the evidence but we already know it is valid // hence we log an error and continue evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev) } evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev) } // check for duplicate evidence. We cache hashes so we don't have to work them out again. hashes[idx] = ev.Hash() for i := idx - 1; i >= 0; i-- { if bytes.Equal(hashes[i], hashes[idx]) { return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")} } } } return nil }
0
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
vulnerable
func (mr *MockRequesterMockRecorder) GetRequestedAudience() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedAudience", reflect.TypeOf((*MockRequester)(nil).GetRequestedAudience)) }
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 (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error { switch m.Device { case "cgroup": // No mount point(s) need to be created: // // * for v1, mount points are saved by CRIU because // /sys/fs/cgroup is a tmpfs mount // // * for v2, /sys/fs/cgroup is a real mount, but // the mountpoint appears as soon as /sys is mounted return nil case "bind": // The prepareBindMount() function checks if source // exists. So it cannot be used for other filesystem types. if err := prepareBindMount(m, c.config.Rootfs); err != nil { return err } default: // for all other filesystems just create the mountpoints dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination) if err != nil { return err } if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil { return err } m.Destination = dest if err := os.MkdirAll(dest, 0755); 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 (mr *MockTokenRevocationStorageMockRecorder) RevokeRefreshToken(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RevokeRefreshToken", reflect.TypeOf((*MockTokenRevocationStorage)(nil).RevokeRefreshToken), 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 (mr *MockOpenIDConnectRequestStorageMockRecorder) DeleteOpenIDConnectSession(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOpenIDConnectSession", reflect.TypeOf((*MockOpenIDConnectRequestStorage)(nil).DeleteOpenIDConnectSession), 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 TestListActivities(t *testing.T) { ds := new(mock.Store) svc := newTestService(t, ds, nil, nil) ds.ListActivitiesFunc = func(ctx context.Context, opts fleet.ListOptions) ([]*fleet.Activity, error) { return []*fleet.Activity{ {ID: 1}, {ID: 2}, }, nil } // admin user activities, err := svc.ListActivities(test.UserContext(test.UserAdmin), fleet.ListOptions{}) require.NoError(t, err) require.Len(t, activities, 2) // anyone can read activities activities, err = svc.ListActivities(test.UserContext(test.UserNoRoles), fleet.ListOptions{}) require.NoError(t, err) require.Len(t, activities, 2) // no user in context _, err = svc.ListActivities(context.Background(), fleet.ListOptions{}) require.Error(t, err) require.Contains(t, err.Error(), authz.ForbiddenErrorMessage) }
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
useNotRoot := func(user string) bool { if user == "" || user == "root" || user == "0" { return false } return true }
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 (x *DeleteWalletLedgerRequest) Reset() { *x = DeleteWalletLedgerRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[22] 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 TestDoesPolicySignatureMatch(t *testing.T) { credentialTemplate := "%s/%s/%s/s3/aws4_request" now := UTCNow() accessKey := globalActiveCred.AccessKey testCases := []struct { form http.Header expected APIErrorCode }{ // (0) It should fail if 'X-Amz-Credential' is missing. { form: http.Header{}, expected: ErrCredMalformed, }, // (1) It should fail if the access key is incorrect. { form: http.Header{ "X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, "EXAMPLEINVALIDEXAMPL", now.Format(yyyymmdd), globalMinioDefaultRegion)}, }, expected: ErrInvalidAccessKeyID, }, // (2) It should fail with a bad signature. { form: http.Header{ "X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion)}, "X-Amz-Date": []string{now.Format(iso8601Format)}, "X-Amz-Signature": []string{"invalidsignature"}, "Policy": []string{"policy"}, }, expected: ErrSignatureDoesNotMatch, }, // (3) It should succeed if everything is correct. { form: http.Header{ "X-Amz-Credential": []string{ fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion), }, "X-Amz-Date": []string{now.Format(iso8601Format)}, "X-Amz-Signature": []string{ getSignature(getSigningKey(globalActiveCred.SecretKey, now, globalMinioDefaultRegion, serviceS3), "policy"), }, "Policy": []string{"policy"}, }, expected: ErrNone, }, } // Run each test case individually. for i, testCase := range testCases { _, code := doesPolicySignatureMatch(testCase.form) if code != testCase.expected { t.Errorf("(%d) expected to get %s, instead got %s", i, niceError(testCase.expected), niceError(code)) } } }
1
Go
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
safe
func (m *Object) 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 ErrIntOverflowIssue330 } 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: Object: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Object: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } m.Type = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue330 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Type |= TypeIdentifier(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipIssue330(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthIssue330 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthIssue330 } 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 validateWebhook(l macaron.Locale, w *db.Webhook) (field, msg string, ok bool) { // 🚨 SECURITY: Local addresses must not be allowed by non-admins to prevent SSRF, // see https://github.com/gogs/gogs/issues/5366 for details. payloadURL, err := url.Parse(w.URL) if err != nil { return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), false } if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { return "PayloadURL", l.Tr("repo.settings.webhook.url_resolved_to_blocked_local_address"), false } return "", "", true }
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 MigratePost(c *context.Context, f form.MigrateRepo) { c.Data["Title"] = c.Tr("new_migrate") ctxUser := checkContextUser(c, f.Uid) if c.Written() { return } c.Data["ContextUser"] = ctxUser if c.HasError() { c.Success(MIGRATE) return } remoteAddr, err := f.ParseRemoteAddr(c.User) if err != nil { if db.IsErrInvalidCloneAddr(err) { c.Data["Err_CloneAddr"] = true addrErr := err.(db.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f) case addrErr.IsPermissionDenied: c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f) case addrErr.IsInvalidPath: c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f) default: c.Error(err, "unexpected error") } } else { c.Error(err, "parse remote address") } return } repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{ Name: f.RepoName, Description: f.Description, IsPrivate: f.Private || conf.Repository.ForcePrivate, IsUnlisted: f.Unlisted, IsMirror: f.Mirror, RemoteAddr: remoteAddr, }) if err == nil { log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName) c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + f.RepoName) return } if repo != nil { if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil { log.Error("DeleteRepository: %v", errDelete) } } if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), "could not read Username") { c.Data["Err_Auth"] = true c.RenderWithErr(c.Tr("form.auth_failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } else if strings.Contains(err.Error(), "fatal:") { c.Data["Err_CloneAddr"] = true c.RenderWithErr(c.Tr("repo.migrate.failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f) }
0
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
vulnerable
func (x *Config_Warning) Reset() { *x = Config_Warning{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[46] 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 TestValidatePluginData(t *testing.T) { for i, item := range []struct { pass bool plug *Plugin }{ {true, mockPlugin("abcdefghijklmnopqrstuvwxyz0123456789_-ABC")}, {true, mockPlugin("foo-bar-FOO-BAR_1234")}, {false, mockPlugin("foo -bar")}, {false, mockPlugin("$foo -bar")}, // Test leading chars {false, mockPlugin("foo -bar ")}, // Test trailing chars {false, mockPlugin("foo\nbar")}, // Test newline } { err := validatePluginData(item.plug, fmt.Sprintf("test-%d", i)) if item.pass && err != nil { t.Errorf("failed to validate case %d: %s", i, err) } else if !item.pass && err == nil { t.Errorf("expected case %d to fail", i) } } }
1
Go
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
func (m *UnrecognizedWithEmbed_Embedded) 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: Embedded: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Embedded: 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) } var v uint32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= uint32(b&0x7F) << shift if b < 0x80 { break } } m.Field1 = &v 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 } 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 (*UpdateGroupUserStateRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{19} }
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
squareMatchesBigInt := func(a, out p224FieldElement) bool { var tmp p224LargeFieldElement p224Square(&out, &a, &tmp) exp := p224AlternativeToBig(&a) exp.Mul(exp, exp) exp.Mod(exp, P224().Params().P) got := p224AlternativeToBig(&out) if exp.Cmp(got) != 0 || !isInBounds(&out) { t.Logf("a = %x", a) t.Logf("p224Square(a, b) = %x = %v", out, got) t.Logf("a * a = %v", exp) return false } return true }
1
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
safe
func (mr *MockAuthorizeEndpointHandlerMockRecorder) HandleAuthorizeEndpointRequest(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleAuthorizeEndpointRequest", reflect.TypeOf((*MockAuthorizeEndpointHandler)(nil).HandleAuthorizeEndpointRequest), 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 Skip(self Protocol, fieldType Type, maxDepth int) (err error) { if maxDepth <= 0 { return NewProtocolExceptionWithType(DEPTH_LIMIT, errors.New("Depth limit exceeded")) } switch fieldType { case BOOL: _, err = self.ReadBool() return case BYTE: _, err = self.ReadByte() return case I16: _, err = self.ReadI16() return case I32: _, err = self.ReadI32() return case I64: _, err = self.ReadI64() return case DOUBLE: _, err = self.ReadDouble() return case FLOAT: _, err = self.ReadFloat() return case STRING: _, err = self.ReadString() return case STRUCT: if _, err = self.ReadStructBegin(); err != nil { return err } for { _, typeId, _, _ := self.ReadFieldBegin() if typeId == STOP { break } err := Skip(self, typeId, maxDepth-1) if err != nil { return err } self.ReadFieldEnd() } return self.ReadStructEnd() case MAP: keyType, valueType, size, err := self.ReadMapBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, keyType, maxDepth-1) if err != nil { return err } self.Skip(valueType) } return self.ReadMapEnd() case SET: elemType, size, err := self.ReadSetBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, elemType, maxDepth-1) if err != nil { return err } } return self.ReadSetEnd() case LIST: elemType, size, err := self.ReadListBegin() if err != nil { return err } for i := 0; i < size; i++ { err := Skip(self, elemType, maxDepth-1) if err != nil { return err } } return self.ReadListEnd() default: return fmt.Errorf("unable to skip over unknown type id %d", fieldType) } }
1
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
safe
func (m *MockAccessTokenStrategy) AccessTokenSignature(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AccessTokenSignature", arg0) 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 (m *NinRepNonByteCustomType) 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: NinRepNonByteCustomType: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: NinRepNonByteCustomType: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } m.Field1 = append(m.Field1, T{}) if err := m.Field1[len(m.Field1)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex 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 (f *Fosite) WriteRevocationResponse(rw http.ResponseWriter, err error) { rw.Header().Set("Cache-Control", "no-store") rw.Header().Set("Pragma", "no-cache") if err == nil { rw.WriteHeader(http.StatusOK) return } if errors.Is(err, ErrInvalidRequest) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(ErrInvalidRequest) if err != nil { http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError) return } rw.WriteHeader(ErrInvalidRequest.Code) rw.Write(js) } else if errors.Is(err, ErrInvalidClient) { rw.Header().Set("Content-Type", "application/json;charset=UTF-8") js, err := json.Marshal(ErrInvalidClient) if err != nil { http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError) return } rw.WriteHeader(ErrInvalidClient.Code) rw.Write(js) } else { // 200 OK rw.WriteHeader(http.StatusOK) } }
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 (m *MockAuthorizeRequester) GetRequestedScopes() fosite.Arguments { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetRequestedScopes") 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(ctx etreeutils.NSContext, signedInfo *etree.Element) error { detachedSignedInfo, err := etreeutils.NSDetatch(ctx, signedInfo) if err != nil { return err } c14NMethod, err := etreeutils.NSFindOneChildCtx(ctx, detachedSignedInfo, Namespace, CanonicalizationMethodTag) if err != nil { return err } if c14NMethod == nil { return errors.New("missing CanonicalizationMethod on Signature") } c14NAlgorithm := c14NMethod.SelectAttrValue(AlgorithmAttr, "") var canonicalSignedInfo *etree.Element switch AlgorithmID(c14NAlgorithm) { case CanonicalXML10ExclusiveAlgorithmId: err := etreeutils.TransformExcC14n(detachedSignedInfo, "") if err != nil { return err } // NOTE: TransformExcC14n transforms the element in-place, // while canonicalPrep isn't meant to. Once we standardize // this behavior we can drop this, as well as the adding and // removing of elements below. canonicalSignedInfo = detachedSignedInfo case CanonicalXML11AlgorithmId: canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{}) case CanonicalXML10RecAlgorithmId: canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{}) case CanonicalXML10CommentAlgorithmId: canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{}) default: return fmt.Errorf("invalid CanonicalizationMethod on Signature: %s", c14NAlgorithm) } signatureEl.RemoveChild(signedInfo) signatureEl.AddChild(canonicalSignedInfo) found = true return etreeutils.ErrTraversalHalted })
1
Go
CWE-347
Improper Verification of Cryptographic Signature
The software does not verify, or incorrectly verifies, the cryptographic signature for data.
https://cwe.mitre.org/data/definitions/347.html
safe
func (mr *MockAuthorizeRequesterMockRecorder) IsRedirectURIValid() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsRedirectURIValid", reflect.TypeOf((*MockAuthorizeRequester)(nil).IsRedirectURIValid)) }
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 Test_bindConfig(t *testing.T) { ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10) defer clearTimeout() b := New("local-grpc", "local-http", filemgr.NewManager(), nil) t.Run("no bind config", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{}, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) assert.Nil(t, cluster.UpstreamBindConfig) }) t.Run("freebind", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{ EnvoyBindConfigFreebind: null.BoolFrom(true), }, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "freebind": true, "sourceAddress": { "address": "0.0.0.0", "portValue": 0 } } `, cluster.UpstreamBindConfig) }) t.Run("source address", func(t *testing.T) { cluster, err := b.buildPolicyCluster(ctx, &config.Options{ EnvoyBindConfigSourceAddress: "192.168.0.1", }, &config.Policy{ From: "https://from.example.com", To: mustParseWeightedURLs(t, "https://to.example.com"), }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "sourceAddress": { "address": "192.168.0.1", "portValue": 0 } } `, cluster.UpstreamBindConfig) }) }
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 *Config) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[14] 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 (x *Username) Reset() { *x = Username{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[38] 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 (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) { raw, err := r.signatureVerifier.VerifySignature(ctx, tokenStr) if err != nil { return nil, err } claimsRaw := map[string]interface{}{} if err = json.Unmarshal(raw, &claimsRaw); err != nil { return nil, fmt.Errorf("failed to unmarshal user info claim into UserInfo type. Error: %w", err) } return verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), claimsRaw) }
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 *DeleteFriendRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[16] 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 *MockAuthorizeCodeStorage) InvalidateAuthorizeCodeSession(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InvalidateAuthorizeCodeSession", arg0, arg1) 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 (s *FositeSQLStore) setClientAssertionJWT(ctx context.Context, jti *blacklistedJTI) error { db := s.db(ctx) _, err := db.ExecContext(ctx, db.Rebind(fmt.Sprintf("INSERT INTO hydra_oauth2_%s (signature, expires_at) VALUES (?, ?)", sqlTableBlacklistedJTI)), jti.Signature, jti.Expiry) return sqlcon.HandleError(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 Test_isRepositoryGitPath(t *testing.T) { tests := []struct { path string wantVal bool }{ {path: ".git", wantVal: true}, {path: "./.git", wantVal: true}, {path: ".git/hooks/pre-commit", wantVal: true}, {path: ".git/hooks", wantVal: true}, {path: "dir/.git", wantVal: true}, {path: ".gitignore", wantVal: false}, {path: "dir/.gitkeep", wantVal: false}, // Windows-specific {path: `.git\`, wantVal: true}, {path: `.git\hooks\pre-commit`, wantVal: true}, {path: `.git\hooks`, wantVal: true}, {path: `dir\.git`, wantVal: true}, {path: `.\.git.`, wantVal: true}, {path: `.\.git.\`, wantVal: true}, {path: `.git.\hooks\pre-commit`, wantVal: true}, {path: `.git.\hooks`, wantVal: true}, {path: `dir\.git.`, wantVal: true}, {path: "./.git.", wantVal: true}, {path: "./.git./", wantVal: true}, {path: ".git./hooks/pre-commit", wantVal: true}, {path: ".git./hooks", wantVal: true}, {path: "dir/.git.", wantVal: true}, {path: `dir\.gitkeep`, wantVal: false}, } for _, test := range tests { t.Run(test.path, func(t *testing.T) { assert.Equal(t, test.wantVal, isRepositoryGitPath(test.path)) }) } }
1
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
safe
func (x *ListGroupsRequest) Reset() { *x = ListGroupsRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[27] 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 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{} 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() }
0
Go
NVD-CWE-noinfo
null
null
null
vulnerable
func (EmptyEvidencePool) AddEvidence(types.Evidence) error { return 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 (m *MockClient) GetResponseTypes() fosite.Arguments { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetResponseTypes") 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 (m *MockAccessRequester) AppendRequestedScope(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "AppendRequestedScope", 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 validateAndUpdateWebhook(c *context.Context, orCtx *orgRepoContext, w *db.Webhook) { c.Data["Webhook"] = w if c.HasError() { c.Success(orCtx.TmplNew) return } field, msg, ok := validateWebhook(c.Locale, w) if !ok { c.FormErr(field) c.RenderWithErr(msg, orCtx.TmplNew, nil) return } if err := w.UpdateEvent(); err != nil { c.Error(err, "update event") return } else if err := db.UpdateWebhook(w); err != nil { c.Error(err, "update webhook") return } c.Flash.Success(c.Tr("repo.settings.update_hook_success")) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) }
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 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 TestUnsafeAllowPrivateRanges (t *testing.T) { a := assert.New(t) conf := NewConfig() a.NoError(conf.SetDenyRanges([]string {"192.168.0.0/24", "10.0.0.0/8"})) conf.ConnectTimeout = 10 * time.Second conf.ExitTimeout = 10 * time.Second conf.AdditionalErrorMessageOnDeny = "Proxy denied" conf.UnsafeAllowPrivateRanges = true testIPs := []testCase{ testCase{"8.8.8.8", 1, ipAllowDefault}, // Specific blocked networks testCase{"10.0.0.1", 1, ipDenyUserConfigured}, testCase{"10.0.0.1", 321, ipDenyUserConfigured}, testCase{"10.0.1.1", 1, ipDenyUserConfigured}, testCase{"172.16.0.1", 1, ipAllowDefault}, testCase{"172.16.1.1", 1, ipAllowDefault}, testCase{"192.168.0.1", 1, ipDenyUserConfigured}, testCase{"192.168.1.1", 1, ipAllowDefault}, // localhost testCase{"127.0.0.1", 1, ipDenyNotGlobalUnicast}, testCase{"127.255.255.255", 1, ipDenyNotGlobalUnicast}, testCase{"::1", 1, ipDenyNotGlobalUnicast}, // ec2 metadata endpoint testCase{"169.254.169.254", 1, ipDenyNotGlobalUnicast}, // Broadcast addresses testCase{"255.255.255.255", 1, ipDenyNotGlobalUnicast}, testCase{"ff02:0:0:0:0:0:0:2", 1, ipDenyNotGlobalUnicast}, } for _, test := range testIPs { localIP := net.ParseIP(test.ip) if localIP == nil { t.Errorf("Could not parse IP from string: %s", test.ip) continue } localAddr := net.TCPAddr{ IP: localIP, Port: test.port, } got := classifyAddr(conf, &localAddr) if got != test.expected { t.Errorf("Misclassified IP (%s): should be %s, but is instead %s.", localIP, test.expected, got) } } }
0
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
vulnerable
func TestBuilder_BuildBootstrapLayeredRuntime(t *testing.T) { b := New("localhost:1111", "localhost:2222", filemgr.NewManager(), nil) staticCfg, err := b.BuildBootstrapLayeredRuntime() assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "layers": [{ "name": "static_layer_0", "staticLayer": { "overload": { "global_downstream_max_connections": 50000 } } }] } `, staticCfg) }
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 (mr *MockAccessResponderMockRecorder) SetExpiresIn(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetExpiresIn", reflect.TypeOf((*MockAccessResponder)(nil).SetExpiresIn), 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 bindMountDeviceNode(dest string, node *devices.Device) error { f, err := os.Create(dest) if err != nil && !os.IsExist(err) { return err } if f != nil { f.Close() } return unix.Mount(node.Path, dest, "bind", unix.MS_BIND, "") }
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 (EmptyEvidencePool) AddEvidenceFromConsensus(evidence types.Evidence) error { return nil }
0
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
vulnerable
func (*WalletLedger) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{42} }
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 *DeleteGroupUserRequest) Reset() { *x = DeleteGroupUserRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[18] 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 (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte { buffer := make([]byte, len(aad)+len(nonce)+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] }
0
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
vulnerable
func (x *UserList_User) Reset() { *x = UserList_User{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[48] 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 (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 } var timestamp time.Time if voteErr.VoteA.Height == cs.state.InitialHeight { timestamp = cs.state.LastBlockTime // genesis time } else { timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators) } // form duplicate vote evidence from the conflicting votes and send it across to the // evidence pool ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators) evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev) if evidenceErr != nil { cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr) } else { cs.Logger.Debug("Added evidence to the evidence pool", "ev", ev) } 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 }
0
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
vulnerable
func isLoopbackURI(requested *url.URL, registeredURI string) bool { registered, err := url.Parse(registeredURI) if err != nil { return false } if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) { return false } if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path { return true } return false }
0
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
vulnerable
func (x *UpdateGroupUserStateRequest) Reset() { *x = UpdateGroupUserStateRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[19] 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 makeStreamDistributedQueryCampaignResultsHandler(svc kolide.Service, jwtKey string, logger kitlog.Logger) http.Handler { opt := sockjs.DefaultOptions opt.Websocket = true opt.RawWebsocket = true return sockjs.NewHandler("/api/v1/kolide/results", opt, func(session sockjs.Session) { defer session.Close(0, "none") conn := &websocket.Conn{Session: session} // Receive the auth bearer token token, err := conn.ReadAuthToken() if err != nil { logger.Log("err", err, "msg", "failed to read auth token") return } // Authenticate with the token vc, err := authViewer(context.Background(), jwtKey, token, svc) if err != nil || !vc.CanPerformActions() { logger.Log("err", err, "msg", "unauthorized viewer") conn.WriteJSONError("unauthorized") return } ctx := viewer.NewContext(context.Background(), *vc) msg, err := conn.ReadJSONMessage() if err != nil { logger.Log("err", err, "msg", "reading select_campaign JSON") conn.WriteJSONError("error reading select_campaign") return } if msg.Type != "select_campaign" { logger.Log("err", "unexpected msg type, expected select_campaign", "msg-type", msg.Type) conn.WriteJSONError("expected select_campaign") return } var info struct { CampaignID uint `json:"campaign_id"` } err = json.Unmarshal(*(msg.Data.(*json.RawMessage)), &info) if err != nil { logger.Log("err", err, "msg", "unmarshaling select_campaign data") conn.WriteJSONError("error unmarshaling select_campaign data") return } if info.CampaignID == 0 { logger.Log("err", "campaign ID not set") conn.WriteJSONError("0 is not a valid campaign ID") return } svc.StreamCampaignResults(ctx, conn, info.CampaignID) }) }
0
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
vulnerable
func TestIsLocalHostname(t *testing.T) { tests := []struct { hostname string allowlist []string want bool }{ {hostname: "localhost", want: true}, // #00 {hostname: "127.0.0.1", want: true}, // #01 {hostname: "::1", want: true}, // #02 {hostname: "0:0:0:0:0:0:0:1", want: true}, // #03 {hostname: "fuf.me", want: true}, // #04 {hostname: "127.0.0.95", want: true}, // #05 {hostname: "0.0.0.0", want: true}, // #06 {hostname: "192.168.123.45", want: true}, // #07 {hostname: "gogs.io", want: false}, // #08 {hostname: "google.com", want: false}, // #09 {hostname: "165.232.140.255", want: false}, // #10 {hostname: "192.168.123.45", allowlist: []string{"10.0.0.17"}, want: true}, // #11 {hostname: "gogs.local", allowlist: []string{"gogs.local"}, want: false}, // #12 } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.want, IsBlockedLocalHostname(test.hostname, test.allowlist)) }) } }
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 TestStripRoot(t *testing.T) { for _, test := range []struct { root, path, out string }{ // Works with multiple components. {"/a/b", "/a/b/c", "/c"}, {"/hello/world", "/hello/world/the/quick-brown/fox", "/the/quick-brown/fox"}, // '/' must be a no-op. {"/", "/a/b/c", "/a/b/c"}, // Must be the correct order. {"/a/b", "/a/c/b", "/a/c/b"}, // Must be at start. {"/abc/def", "/foo/abc/def/bar", "/foo/abc/def/bar"}, // Must be a lexical parent. {"/foo/bar", "/foo/barSAMECOMPONENT", "/foo/barSAMECOMPONENT"}, // Must only strip the root once. {"/foo/bar", "/foo/bar/foo/bar/baz", "/foo/bar/baz"}, // Deal with .. in a fairly sane way. {"/foo/bar", "/foo/bar/../baz", "/foo/baz"}, {"/foo/bar", "../../../../../../foo/bar/baz", "/baz"}, {"/foo/bar", "/../../../../../../foo/bar/baz", "/baz"}, {"/foo/bar/../baz", "/foo/baz/bar", "/bar"}, {"/foo/bar/../baz", "/foo/baz/../bar/../baz/./foo", "/foo"}, // All paths are made absolute before stripping. {"foo/bar", "/foo/bar/baz/bee", "/baz/bee"}, {"/foo/bar", "foo/bar/baz/beef", "/baz/beef"}, {"foo/bar", "foo/bar/baz/beets", "/baz/beets"}, } { got := stripRoot(test.root, test.path) if got != test.out { t.Errorf("stripRoot(%q, %q) -- got %q, expected %q", test.root, test.path, got, test.out) } } }
1
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
safe
func (mr *MockAccessRequesterMockRecorder) GetRequestForm() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestForm", reflect.TypeOf((*MockAccessRequester)(nil).GetRequestForm)) }
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