code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
func TestReadWriteCompactProtocol(t *testing.T) { ReadWriteProtocolTest(t, NewCompactProtocolFactory()) // CompactProtocol is capable of reading and writing in different goroutines. ReadWriteProtocolParallelTest(t, NewCompactProtocolFactory()) transports := []Transport{ NewMemoryBuffer(), NewStreamTransportRW(bytes.NewBuffer(make([]byte, 0, 16384))), NewFramedTransport(NewMemoryBuffer()), } for _, trans := range transports { p := NewCompactProtocol(trans) ReadWriteBool(t, p, trans) p = NewCompactProtocol(trans) ReadWriteByte(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI16(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI32(t, p, trans) p = NewCompactProtocol(trans) ReadWriteI64(t, p, trans) p = NewCompactProtocol(trans) ReadWriteDouble(t, p, trans) p = NewCompactProtocol(trans) ReadWriteFloat(t, p, trans) p = NewCompactProtocol(trans) ReadWriteString(t, p, trans) p = NewCompactProtocol(trans) ReadWriteBinary(t, p, trans) p = NewCompactProtocol(trans) ReadWriteStruct(t, p, trans) trans.Close() } }
CWE-770
37
func (x *ListPurchasesRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[28] 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) }
CWE-613
7
func newMockResourceServer(t testing.TB) ResourceServer { ctx := context.Background() dummy := "" serverURL := &dummy hf := func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/.well-known/oauth-authorization-server" { w.Header().Set("Content-Type", "application/json") _, err := io.WriteString(w, strings.ReplaceAll(`{ "issuer": "https://dev-14186422.okta.com", "authorization_endpoint": "https://example.com/auth", "token_endpoint": "https://example.com/token", "jwks_uri": "URL/keys", "id_token_signing_alg_values_supported": ["RS256"] }`, "URL", *serverURL)) if !assert.NoError(t, err) { t.FailNow() } return } else if r.URL.Path == "/keys" { keys := jwk.NewSet() raw, err := json.Marshal(keys) if err != nil { http.Error(w, err.Error(), 400) return } w.Header().Set("Content-Type", "application/json") _, err = io.WriteString(w, string(raw)) if !assert.NoError(t, err) { t.FailNow() } } http.NotFound(w, r) } s := httptest.NewServer(http.HandlerFunc(hf)) defer s.Close() *serverURL = s.URL http.DefaultClient = s.Client() r, err := NewOAuth2ResourceServer(ctx, authConfig.ExternalAuthorizationServer{ BaseURL: stdlibConfig.URL{URL: *config.MustParseURL(s.URL)}, }, stdlibConfig.URL{}) if !assert.NoError(t, err) { t.FailNow() } return r }
CWE-613
7
func (x *UpdateGroupUserStateRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[19] 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) }
CWE-613
7
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) } el.RemoveChild(signedInfo) el.AddChild(canonicalSignedInfo) found = true return etreeutils.ErrTraversalHalted })
CWE-347
25
func UnpackXzTar(filename string, destination string, verbosityLevel int) (err error) { Verbose = verbosityLevel if !common.FileExists(filename) { return fmt.Errorf("file %s not found", filename) } if !common.DirExists(destination) { return fmt.Errorf("directory %s not found", destination) } filename, err = common.AbsolutePath(filename) if err != nil { return err } err = os.Chdir(destination) if err != nil { return errors.Wrapf(err, "error changing directory to %s", destination) } // #nosec G304 f, err := os.Open(filename) if err != nil { return err } defer f.Close() // Create an xz Reader r, err := xz.NewReader(f, 0) if err != nil { return err } // Create a tar Reader tr := tar.NewReader(r) return unpackTarFiles(tr) }
CWE-59
36
func (db *DB) Verify(s *data.Signed, role string, minVersion int64) error { err := db.VerifyIgnoreExpiredCheck(s, role, minVersion) if err != nil { return err } sm := &signedMeta{} if err := json.Unmarshal(s.Signed, sm); err != nil { return err } if IsExpired(sm.Expires) { return ErrExpired{sm.Expires} } return nil }
CWE-354
82
func ZeroTierLeaveNetwork(c *gin.Context) { networkId := c.Param("id") service.MyService.ZeroTier().ZeroTierLeaveNetwork(networkId) if len(networkId) == 0 { c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)}) return } c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) }
CWE-78
6
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 }
CWE-613
7
func ZeroTierJoinNetwork(c *gin.Context) { networkId := c.Param("id") service.MyService.ZeroTier().ZeroTierJoinNetwork(networkId) if len(networkId) == 0 { c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)}) return } c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) }
CWE-78
6
func SnapshotFileMetaEqual(actual data.SnapshotFileMeta, expected data.SnapshotFileMeta) error { // TUF-1.0 no longer considers the length and hashes to be a required // member of snapshots. However they are considering requiring hashes // for delegated roles to avoid an attack described in Section 5.6 of // the Mercury paper: // https://github.com/theupdateframework/specification/pull/40 if expected.Length != 0 && actual.Length != expected.Length { return ErrWrongLength{expected.Length, actual.Length} } if len(expected.Hashes) != 0 { if err := hashEqual(actual.Hashes, expected.Hashes); err != nil { return err } } if err := versionEqual(actual.Version, expected.Version); err != nil { return err } return nil }
CWE-354
82
func (*StorageCollectionsList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{34} }
CWE-613
7
func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.AuthenticateRequest) (*console.ConsoleSession, error) { role := console.UserRole_USER_ROLE_UNKNOWN var uname string var email string switch in.Username { case s.config.GetConsole().Username: if in.Password == s.config.GetConsole().Password { role = console.UserRole_USER_ROLE_ADMIN uname = in.Username } default: var err error uname, email, role, err = s.lookupConsoleUser(ctx, in.Username, in.Password) if err != nil { return nil, err } } if role == console.UserRole_USER_ROLE_UNKNOWN { return nil, status.Error(codes.Unauthenticated, "Invalid credentials.") } token := jwt.NewWithClaims(jwt.SigningMethodHS256, &ConsoleTokenClaims{ ExpiresAt: time.Now().UTC().Add(time.Duration(s.config.GetConsole().TokenExpirySec) * time.Second).Unix(), Username: uname, Email: email, Role: role, Cookie: s.cookie, }) key := []byte(s.config.GetConsole().SigningKey) signedToken, _ := token.SignedString(key) return &console.ConsoleSession{Token: signedToken}, nil }
CWE-613
7
func padBuffer(buffer []byte, blockSize int) []byte { missing := blockSize - (len(buffer) % blockSize) ret, out := resize(buffer, len(buffer)+missing) padding := bytes.Repeat([]byte{byte(missing)}, missing) copy(out, padding) return ret }
CWE-190
19
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) }
CWE-613
7
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) }
CWE-613
7
func (x *ConsoleSession) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[15] 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) }
CWE-613
7
func (p *CompactProtocol) ReadString() (value string, err error) { length, e := p.readVarint32() if e != nil { return "", NewProtocolException(e) } if length < 0 { return "", invalidDataLength } if uint64(length) > p.trans.RemainingBytes() { return "", invalidDataLength } if length == 0 { return "", nil } var buf []byte if length <= int32(len(p.rBuffer)) { buf = p.rBuffer[0:length] } else { buf = make([]byte, length) } _, e = io.ReadFull(p.trans, buf) return string(buf), NewProtocolException(e) }
CWE-770
37
func NewFositeMemoryStore( r InternalRegistry, c Configuration, ) *FositeMemoryStore { return &FositeMemoryStore{ AuthorizeCodes: make(map[string]authorizeCode), IDSessions: make(map[string]fosite.Requester), AccessTokens: make(map[string]fosite.Requester), PKCES: make(map[string]fosite.Requester), RefreshTokens: make(map[string]fosite.Requester), c: c, r: r, } }
CWE-294
94
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() }
CWE-281
93
func (x *DeleteGroupRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[17] 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) }
CWE-613
7
func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) { remoteAddr := strings.TrimSpace(f.CloneAddr) // Remote address can be HTTP/HTTPS/Git URL or local path. if strings.HasPrefix(remoteAddr, "http://") || strings.HasPrefix(remoteAddr, "https://") || strings.HasPrefix(remoteAddr, "git://") { u, err := url.Parse(remoteAddr) if err != nil { return "", db.ErrInvalidCloneAddr{IsURLError: true} } if netutil.IsLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { return "", db.ErrInvalidCloneAddr{IsURLError: true} } if len(f.AuthUsername)+len(f.AuthPassword) > 0 { u.User = url.UserPassword(f.AuthUsername, f.AuthPassword) } // To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413 if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) { return "", db.ErrInvalidCloneAddr{IsURLError: true} } remoteAddr = u.String() } else if !user.CanImportLocal() { return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true} } else if !com.IsDir(remoteAddr) { return "", db.ErrInvalidCloneAddr{IsInvalidPath: true} } return remoteAddr, nil }
CWE-918
16
func (*Leaderboard) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{23} }
CWE-613
7
func isMatchingRedirectURI(uri string, haystack []string) bool { requested, err := url.Parse(uri) if err != nil { return false } for _, b := range haystack { if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) { return true } } return false }
CWE-601
11
func (x *StorageCollectionsList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[34] 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) }
CWE-613
7
func (d *partialArray) add(key string, val *lazyNode) error { if key == "-" { *d = append(*d, val) return nil } idx, err := strconv.Atoi(key) if err != nil { return err } ary := make([]*lazyNode, len(*d)+1) cur := *d if idx < 0 { idx *= -1 if idx > len(ary) { return fmt.Errorf("Unable to access invalid index: %d", idx) } idx = len(ary) - idx } copy(ary[0:idx], cur[0:idx]) ary[idx] = val copy(ary[idx+1:], cur[idx:]) *d = ary return nil }
CWE-787
24
func (x *WriteStorageObjectRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[44] 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) }
CWE-613
7
func (*StatusList_Status) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{40, 0} }
CWE-613
7
func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified bool) { fmt.Fprintf(os.Stderr, "\nVerification for %s --\n", imgRef) fmt.Fprintln(os.Stderr, "The following checks were performed on each of these signatures:") if co.ClaimVerifier != nil { if co.Annotations != nil { fmt.Fprintln(os.Stderr, " - The specified annotations were verified.") } fmt.Fprintln(os.Stderr, " - The cosign claims were validated") } if bundleVerified { fmt.Fprintln(os.Stderr, " - Existence of the claims in the transparency log was verified offline") } else if co.RekorClient != nil { fmt.Fprintln(os.Stderr, " - The claims were present in the transparency log") fmt.Fprintln(os.Stderr, " - The signatures were integrated into the transparency log when the certificate was valid") } if co.SigVerifier != nil { fmt.Fprintln(os.Stderr, " - The signatures were verified against the specified public key") } fmt.Fprintln(os.Stderr, " - Any certificates were verified against the Fulcio roots.") }
CWE-295
52
func (*WalletLedger) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{42} }
CWE-613
7
func (*UserList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{39} }
CWE-613
7
func cmdList(args *docopt.Args, client *tuf.Client) error { if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) { return err } targets, err := client.Targets() if err != nil { return err } w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0) defer w.Flush() fmt.Fprintln(w, "PATH\tSIZE") for path, meta := range targets { fmt.Fprintf(w, "%s\t%s\n", path, humanize.Bytes(uint64(meta.Length))) } return nil }
CWE-354
82
func (p *HTTPClient) ReadByte() (c byte, err error) { return readByte(p.response.Body) }
CWE-770
37
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 } }
CWE-281
93
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, IsLocalHostname(test.hostname, test.allowlist)) }) } }
CWE-918
16
func (x *CallApiEndpointRequest) Reset() { *x = CallApiEndpointRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
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.User, 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)) }
CWE-918
16
func (x *WriteStorageObjectRequest) Reset() { *x = WriteStorageObjectRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func TestRedactURL(t *testing.T) { cases := []struct { name string url *url.URL want string }{ { name: "non-blank Password", url: &url.URL{ Scheme: "http", Host: "host.tld", Path: "this:that", User: url.UserPassword("user", "password"), }, want: "http://user:[email protected]/this:that", }, { name: "blank Password", url: &url.URL{ Scheme: "http", Host: "host.tld", Path: "this:that", User: url.User("user"), }, want: "http://[email protected]/this:that", }, { name: "nil User", url: &url.URL{ Scheme: "http", Host: "host.tld", Path: "this:that", User: url.UserPassword("", "password"), }, want: "http://:[email protected]/this:that", }, { name: "blank Username, blank Password", url: &url.URL{ Scheme: "http", Host: "host.tld", Path: "this:that", }, want: "http://host.tld/this:that", }, { name: "empty URL", url: &url.URL{}, want: "", }, { name: "nil URL", url: nil, want: "", }, } for _, tt := range cases { t := t t.Run(tt.name, func(t *testing.T) { if g, w := RedactURL(tt.url), tt.want; g != w { t.Fatalf("got: %q\nwant: %q", g, w) } }) } }
CWE-532
28
func (cs chunkState) String() string { stateString := "" switch cs { case readChunkHeader: stateString = "readChunkHeader" case readChunkTrailer: stateString = "readChunkTrailer" case readChunk: stateString = "readChunk" case verifyChunk: stateString = "verifyChunk" case eofChunk: stateString = "eofChunk" } return stateString }
CWE-924
95
func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) { regexps := []*regexp.Regexp{} for _, regexpStr := range regexpStrings { r, err := regexp.Compile(regexpStr) if err != nil { return regexps, err } regexps = append(regexps, r) } return regexps, nil }
CWE-639
9
func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(ciphertext) < ctx.authtagBytes { return nil, errors.New("square/go-jose: invalid ciphertext (too short)") } offset := len(ciphertext) - ctx.authtagBytes expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset]) match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:]) if match != 1 { return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)") } cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce) // Make copy of ciphertext buffer, don't want to modify in place buffer := append([]byte{}, []byte(ciphertext[:offset])...) if len(buffer)%ctx.blockCipher.BlockSize() > 0 { return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)") } cbc.CryptBlocks(buffer, buffer) // Remove padding plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize()) if err != nil { return nil, err } ret, out := resize(dst, len(dst)+len(plaintext)) copy(out, plaintext) return ret, nil }
CWE-190
19
func (x *CallApiEndpointResponse) Reset() { *x = CallApiEndpointResponse{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (voteSet *VoteSet) MakeCommit() *Commit { if voteSet.signedMsgType != tmproto.PrecommitType { panic("Cannot MakeCommit() unless VoteSet.Type is PrecommitType") } voteSet.mtx.Lock() defer voteSet.mtx.Unlock() // Make sure we have a 2/3 majority if voteSet.maj23 == nil { panic("Cannot MakeCommit() unless a blockhash has +2/3") } // For every validator, get the precommit commitSigs := make([]CommitSig, len(voteSet.votes)) for i, v := range voteSet.votes { commitSigs[i] = v.CommitSig() } return NewCommit(voteSet.GetHeight(), voteSet.GetRound(), *voteSet.maj23, commitSigs) }
CWE-347
25
func (x *GetWalletLedgerRequest) Reset() { *x = GetWalletLedgerRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader { buffer := make([]byte, len(algID)+len(ptyUInfo)+len(ptyVInfo)+len(supPubInfo)+len(supPrivInfo)) n := 0 n += copy(buffer, algID) n += copy(buffer[n:], ptyUInfo) n += copy(buffer[n:], ptyVInfo) n += copy(buffer[n:], supPubInfo) copy(buffer[n:], supPrivInfo) hasher := hash.New() return &concatKDF{ z: z, info: buffer, hasher: hasher, cache: []byte{}, i: 1, } }
CWE-190
19
func setCapabilities(spec *specs.Spec, keepCaps ...string) error { currentCaps, err := capability.NewPid2(0) if err != nil { return errors.Wrapf(err, "error reading capabilities of current process") } if err := currentCaps.Load(); err != nil { return errors.Wrapf(err, "error loading capabilities") } caps, err := capability.NewPid2(0) if err != nil { return errors.Wrapf(err, "error reading capabilities of current process") } capMap := map[capability.CapType][]string{ capability.BOUNDING: spec.Process.Capabilities.Bounding, capability.EFFECTIVE: spec.Process.Capabilities.Effective, capability.INHERITABLE: spec.Process.Capabilities.Inheritable, capability.PERMITTED: spec.Process.Capabilities.Permitted, capability.AMBIENT: spec.Process.Capabilities.Ambient, } knownCaps := capability.List() noCap := capability.Cap(-1) for capType, capList := range capMap { for _, capToSet := range capList { cap := noCap for _, c := range knownCaps { if strings.EqualFold("CAP_"+c.String(), capToSet) { cap = c break } } if cap == noCap { return errors.Errorf("error mapping capability %q to a number", capToSet) } caps.Set(capType, cap) } for _, capToSet := range keepCaps { cap := noCap for _, c := range knownCaps { if strings.EqualFold("CAP_"+c.String(), capToSet) { cap = c break } } if cap == noCap { return errors.Errorf("error mapping capability %q to a number", capToSet) } if currentCaps.Get(capType, cap) { caps.Set(capType, cap) } } } if err = caps.Apply(capability.CAPS | capability.BOUNDS | capability.AMBS); err != nil { return errors.Wrapf(err, "error setting capabilities") } return nil }
CWE-276
45
func readUvarint(r io.ByteReader) (x uint64, n int, err error) { var s uint i := 0 for { b, err := r.ReadByte() if err != nil { return x, i, err } i++ if b < 0x80 { if i > 10 || i == 10 && b > 1 { return x, i, errOverflowU64 } return x | uint64(b)<<s, i, nil } x |= uint64(b&0x7f) << s s += 7 } }
CWE-835
42
func (*DeleteLeaderboardRecordRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{20} }
CWE-613
7
func SanitizePath(path string) string { return strings.TrimLeft(path, "./") }
CWE-22
2
func IsLatestSnapshot(err error) bool { _, ok := err.(ErrLatestSnapshot) return ok }
CWE-354
82
func (cf *clientsFactory) UpdateNamespaces(ctx context.Context) error { clients, err := clientsForClusters(cf.clusters.Get()) if err != nil { cf.log.Error(err, "failed to create clients for", "clusters", cf.clusters.Get()) return err } cf.syncCaches() wg := sync.WaitGroup{} for clusterName, c := range clients { wg.Add(1) go func(clusterName string, c client.Client) { defer wg.Done() nsList := &v1.NamespaceList{} if err := c.List(ctx, nsList); err != nil { cf.log.Error(err, "failed listing namespaces", "cluster", clusterName) } cf.clustersNamespaces.Set(clusterName, nsList.Items) }(clusterName, c) } wg.Wait() return nil }
CWE-532
28
func (x *DeleteLeaderboardRecordRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[20] 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) }
CWE-613
7
func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool { if len(origin) == 0 { return false } if len(c.AllowedDomains) == 0 { return true } allowed := false for _, domain := range c.AllowedDomains { if domain == origin { allowed = true break } } if !allowed { if len(c.allowedOriginPatterns) == 0 { // compile allowed domains to allowed origin patterns allowedOriginRegexps, err := compileRegexps(c.AllowedDomains) if err != nil { return false } c.allowedOriginPatterns = allowedOriginRegexps } for _, pattern := range c.allowedOriginPatterns { if allowed = pattern.MatchString(origin); allowed { break } } } return allowed }
CWE-639
9
func (*ConsoleSession) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{15} }
CWE-613
7
func (*WriteStorageObjectRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{44} }
CWE-613
7
func (c *Client) Update() (data.TargetFiles, error) { if err := c.UpdateRoots(); err != nil { if _, ok := err.(verify.ErrExpired); ok { // For backward compatibility, we wrap the ErrExpired inside // ErrDecodeFailed. return nil, ErrDecodeFailed{"root.json", err} } return nil, err } // Get timestamp.json, extract snapshot.json file meta and save the // timestamp.json locally timestampJSON, err := c.downloadMetaUnsafe("timestamp.json", defaultTimestampDownloadLimit) if err != nil { return nil, err } snapshotMeta, err := c.decodeTimestamp(timestampJSON) if err != nil { return nil, err } if err := c.local.SetMeta("timestamp.json", timestampJSON); err != nil { return nil, err } // Get snapshot.json, then extract file metas. // root.json meta should not be stored in the snapshot, if it is, // the root will be checked, re-downloaded snapshotJSON, err := c.downloadMetaFromTimestamp("snapshot.json", snapshotMeta) if err != nil { return nil, err } snapshotMetas, err := c.decodeSnapshot(snapshotJSON) if err != nil { return nil, err } // Save the snapshot.json if err := c.local.SetMeta("snapshot.json", snapshotJSON); err != nil { return nil, err } // If we don't have the targets.json, download it, determine updated // targets and save targets.json in local storage var updatedTargets data.TargetFiles targetsMeta := snapshotMetas["targets.json"] if !c.hasMetaFromSnapshot("targets.json", targetsMeta) { targetsJSON, err := c.downloadMetaFromSnapshot("targets.json", targetsMeta) if err != nil { return nil, err } updatedTargets, err = c.decodeTargets(targetsJSON) if err != nil { return nil, err } if err := c.local.SetMeta("targets.json", targetsJSON); err != nil { return nil, err } } return updatedTargets, nil }
CWE-354
82
func prepareBindMount(m *configs.Mount, rootfs string) error { stat, err := os.Stat(m.Source) if err != nil { // error out if the source of a bind mount does not exist as we will be // unable to bind anything to it. return err } // ensure that the destination of the bind mount is resolved of symlinks at mount time because // any previous mounts can invalidate the next mount's destination. // this can happen when a user specifies mounts within other mounts to cause breakouts or other // evil stuff to try to escape the container's rootfs. var dest string if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil { return err } if err := checkProcMount(rootfs, dest, m.Source); err != nil { return err } if err := createIfNotExists(dest, stat.IsDir()); err != nil { return err } return nil }
CWE-190
19
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) }
CWE-613
7
func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) { // Prevent SQL inject. opt.Keyword = FilterSQLInject(opt.Keyword) if len(opt.Keyword) == 0 { return repos, nil } opt.Keyword = strings.ToLower(opt.Keyword) repos = make([]*Repository, 0, opt.Limit) // Append conditions. sess := x.Limit(opt.Limit) if opt.Uid > 0 { sess.Where("owner_id=?", opt.Uid) } if !opt.Private { sess.And("is_private=false") } sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos) return repos, err }
CWE-89
0
func (*UnlinkDeviceRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{35} }
CWE-613
7
func canonicalMIMEHeaderKey(a []byte) string { 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 c == ' ' { c = '-' } else 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) }
CWE-444
41
func DeleteCode(id string) { delete(memory.Code, id) }
CWE-305
92
func (a *APIs) PostLogin(v *PostLoginReq) *kongchuanhujiao.Response { if v.Code != account.GetCode(v.ID) || v.Code == "" { // FIXME datahub 鉴权 return kongchuanhujiao.GenerateErrResp(1, "验证码有误") } now := time.Now() t, err := jwt.NewTokenWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ "iss": config.GetJWTConf().Iss, "sub": v.ID, "exp": now.AddDate(0, 1, 0).Unix(), "nbf": now.Unix(), "iat": now.Unix(), }).SignedString(config.GetJWTConf().Key) if err != nil { logger.Error("生成 JWT Token 失败", zap.Error(err)) return kongchuanhujiao.DefaultErrResp } return &kongchuanhujiao.Response{Message: t} }
CWE-305
92
func consoleInterceptorFunc(logger *zap.Logger, config Config) func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error) {
CWE-613
7
func (x *StatusList_Status) Reset() { *x = StatusList_Status{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *MatchState) Reset() { *x = MatchState{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (*DeleteGroupRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{17} }
CWE-613
7
func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) { sess := x.Limit(20, (page-1)*20) if rid > 0 { sess.Where("repo_id=?", rid).And("is_closed=?", isClosed) } else { sess.Where("is_closed=?", isClosed) } if uid > 0 { sess.And("assignee_id=?", uid) } else if pid > 0 { sess.And("poster_id=?", pid) } if mid > 0 { sess.And("milestone_id=?", mid) } if len(labelIds) > 0 { for _, label := range strings.Split(labelIds, ",") { sess.And("label_ids like '%$" + label + "|%'") } } switch sortType { case "oldest": sess.Asc("created") case "recentupdate": sess.Desc("updated") case "leastupdate": sess.Asc("updated") case "mostcomment": sess.Desc("num_comments") case "leastcomment": sess.Asc("num_comments") case "priority": sess.Desc("priority") default: sess.Desc("created") } var issues []Issue err := sess.Find(&issues) return issues, err }
CWE-89
0
func (*GetWalletLedgerRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{45} }
CWE-613
7
func (*CallApiEndpointResponse) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{13} }
CWE-613
7
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) }
CWE-924
95
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 }
CWE-178
40
func (*UserList_User) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{39, 0} }
CWE-613
7
func (x *UpdateGroupRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[37] 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) }
CWE-613
7
private HandshakeMessage createClientHandshakeMessage( HandshakeType type, byte[] buffer) { switch (type) { case HandshakeType.ClientHello: return new TlsClientHello(this.context, buffer); case HandshakeType.Certificate: return new TlsClientCertificate(this.context, buffer); case HandshakeType.ClientKeyExchange: return new TlsClientKeyExchange(this.context, buffer); case HandshakeType.CertificateVerify: return new TlsClientCertificateVerify(this.context, buffer); case HandshakeType.Finished: return new TlsClientFinished(this.context, buffer); default: throw new TlsException( AlertDescription.UnexpectedMessage, String.Format(CultureInfo.CurrentUICulture, "Unknown server handshake message received ({0})", type.ToString())); } }
CWE-295
52
return utils.WithProcfd(rootfs, m.Destination, func(procfd string) error { return mount(m.Source, m.Destination, procfd, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "") })
CWE-190
19
func (x *MatchState) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[31] 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) }
CWE-613
7
func RedactURL(u *url.URL) string { if u == nil { return "" } ru := *u if _, has := ru.User.Password(); has { ru.User = url.UserPassword(ru.User.Username(), "xxxxx") } return ru.String() }
CWE-532
28
func fixTransferEncoding(requestMethod string, header Header) ([]string, error) { raw, present := header["Transfer-Encoding"] if !present { return nil, nil } delete(header, "Transfer-Encoding") encodings := strings.Split(raw[0], ",") te := make([]string, 0, len(encodings)) // TODO: Even though we only support "identity" and "chunked" // encodings, the loop below is designed with foresight. One // invariant that must be maintained is that, if present, // chunked encoding must always come first. for _, encoding := range encodings { encoding = strings.ToLower(strings.TrimSpace(encoding)) // "identity" encoding is not recorded if encoding == "identity" { break } if encoding != "chunked" { return nil, &badStringError{"unsupported transfer encoding", encoding} } te = te[0 : len(te)+1] te[len(te)-1] = encoding } if len(te) > 1 { return nil, &badStringError{"too many transfer encodings", strings.Join(te, ",")} } if len(te) > 0 { // Chunked encoding trumps Content-Length. See RFC 2616 // Section 4.4. Currently len(te) > 0 implies chunked // encoding. delete(header, "Content-Length") return te, nil } return nil, nil }
CWE-444
41
func (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{29} }
CWE-613
7
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) }
CWE-613
7
func (x *Config_Warning) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[46] 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) }
CWE-613
7
([ key, value ]) => ({ [key]: exec.bind(null, `git show -s --format=%${value}`) }), ),
CWE-78
6
set escape_for_html(arg:boolean) { this._escape_for_html = arg; }
CWE-79
1
constructor() { // All construction occurs here this.setup_palettes(); this._use_classes = false; this._escape_for_html = true; this.bold = false; this.fg = this.bg = null; this._buffer = ''; this._url_whitelist = { 'http':1, 'https':1 }; }
CWE-79
1
function sendResponse(response1: Response) { try { assert(response1 instanceof ResponseClass); if (message.session) { const counterName = ResponseClass.name.replace("Response", ""); message.session.incrementRequestTotalCounter(counterName); } return channel.send_response("MSG", response1, message); } catch (err) { warningLog(err); // istanbul ignore next if (err instanceof Error) { // istanbul ignore next errorLog( "Internal error in issuing response\nplease contact [email protected]", message.request.toString(), "\n", response1.toString() ); } // istanbul ignore next throw err; } }
CWE-770
37
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, totalHours, }
CWE-79
1
export function createCatalogWriteAction() { return createTemplateAction<{ name?: string; entity: Entity }>({ id: 'catalog:write', description: 'Writes the catalog-info.yaml for your template', schema: { input: { type: 'object', properties: { entity: { title: 'Entity info to write catalog-info.yaml', description: 'You can provide the same values used in the Entity schema.', type: 'object', }, }, }, }, async handler(ctx) { ctx.logStream.write(`Writing catalog-info.yaml`); const { entity } = ctx.input; await fs.writeFile( resolvePath(ctx.workspacePath, 'catalog-info.yaml'), yaml.stringify(entity), ); }, }); }
CWE-22
2
[_sanitize](svg) { return svg.removeAttr('onload'); }
CWE-94
14
const matrix = node.getScreenCTM(); if (res && matrix) { const [x, y, content] = res; const t = tooltip(); t.style.opacity = "1"; t.innerHTML = content; t.style.left = `${window.scrollX + x + matrix.e}px`; t.style.top = `${window.scrollY + y + matrix.f - 15}px`; } else { hide(); } } node.addEventListener("mousemove", mousemove); node.addEventListener("mouseleave", hide); return { destroy: hide, }; }
CWE-79
1
text += ` / ${c.amount(a.budget, a.currency)}`; } text += "<br>"; });
CWE-79
1
export function escape_attribute_value(value) { return typeof value === 'string' ? escape(value, true) : value; }
CWE-79
1
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
CWE-79
1
response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing); } await send_registered_server_request(discoveryServerEndpointUrl, request, check_response); });
CWE-770
37
const unSet = (obj, path, options = {}, tracking = {}) => { let internalPath = path; options = { "transformRead": returnWhatWasGiven, "transformKey": returnWhatWasGiven, "transformWrite": returnWhatWasGiven, ...options }; // No object data if (obj === undefined || obj === null) { return; } // No path string if (!internalPath) { return; } internalPath = clean(internalPath); // Path is not a string, throw error if (typeof internalPath !== "string") { throw new Error("Path argument must be a string"); } if (typeof obj !== "object") { return; } const newObj = decouple(obj, options); // Path has no dot-notation, set key/value if (isNonCompositePath(internalPath)) { if (newObj.hasOwnProperty(unEscape(internalPath))) { delete newObj[options.transformKey(unEscape(internalPath))]; return newObj; } tracking.returnOriginal = true; return obj; } const pathParts = split(internalPath); const pathPart = pathParts.shift(); const transformedPathPart = options.transformKey(unEscape(pathPart)); let childPart = newObj[transformedPathPart]; if (!childPart) { // No child part available, nothing to unset! tracking.returnOriginal = true; return obj; } newObj[transformedPathPart] = unSet(childPart, pathParts.join('.'), options, tracking); if (tracking.returnOriginal) { return obj; } return newObj; };
CWE-915
35
error: err => { reject(err) this.fetching = this.fetching.remove(this.hash(session)) },
CWE-79
1
module.exports = function(key) { key = normalizeKey(key.split('@').pop()); return normalized[key] || false; };
CWE-88
3
getUrl() { return `http://localhost:${this.port}` }
CWE-306
79
__(key) { self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent` The req.__() and res.__() functions are deprecated and do not localize in A3. Use req.t instead. `); return key; }
CWE-613
7