code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
func (*DeleteWalletLedgerRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{22} }
CWE-613
7
func (*DeleteFriendRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{16} }
CWE-613
7
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) }
CWE-613
7
func (*RuntimeInfo_ModuleInfo) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{41, 0} }
CWE-613
7
func Render(tmpl string, s *types.Step) (types.StepSlice, error) { buffer := new(bytes.Buffer) config := new(types.Build) velaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)} templateFuncMap := map[string]interface{}{ "vela": velaFuncs.returnPlatformVar, } // parse the template with Masterminds/sprig functions // // https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap t, err := template.New(s.Name).Funcs(sprig.TxtFuncMap()).Funcs(templateFuncMap).Parse(tmpl) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to parse template %s: %v", s.Template.Name, err) } // apply the variables to the parsed template err = t.Execute(buffer, s.Template.Variables) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to execute template %s: %v", s.Template.Name, err) } // unmarshal the template to the pipeline err = yaml.Unmarshal(buffer.Bytes(), config) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to unmarshal yaml: %v", err) } // ensure all templated steps have template prefix for index, newStep := range config.Steps { config.Steps[index].Name = fmt.Sprintf("%s_%s", s.Name, newStep.Name) } return config.Steps, nil }
CWE-78
6
func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) { plugin, exists := hs.pluginStore.Plugin(ctx, pluginId) if !exists { return nil, plugins.NotFoundError{PluginID: pluginId} } // nolint:gosec // We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based // on plugin the folder structure on disk and not user input. path := filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToUpper(name))) exists, err := fs.Exists(path) if err != nil { return nil, err } if !exists { path = filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToLower(name))) } exists, err = fs.Exists(path) if err != nil { return nil, err } if !exists { return make([]byte, 0), nil } // nolint:gosec // We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based // on plugin the folder structure on disk and not user input. data, err := ioutil.ReadFile(path) if err != nil { return nil, err } return data, nil }
CWE-22
2
func checkAuth(ctx context.Context, config Config, auth string) (context.Context, bool) { const basicPrefix = "Basic " const bearerPrefix = "Bearer " if strings.HasPrefix(auth, basicPrefix) { // Basic authentication. username, password, ok := parseBasicAuth(auth) if !ok { return ctx, false } if username != config.GetConsole().Username || password != config.GetConsole().Password { // Username and/or password do not match. return ctx, false } ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, console.UserRole_USER_ROLE_ADMIN), ctxConsoleUsernameKey{}, username), ctxConsoleEmailKey{}, "") // Basic authentication successful. return ctx, true } else if strings.HasPrefix(auth, bearerPrefix) { // Bearer token authentication. token, err := jwt.Parse(auth[len(bearerPrefix):], func(token *jwt.Token) (interface{}, error) { if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(config.GetConsole().SigningKey), nil }) if err != nil { // Token verification failed. return ctx, false } uname, email, role, exp, ok := parseConsoleToken([]byte(config.GetConsole().SigningKey), auth[len(bearerPrefix):]) if !ok || !token.Valid { // The token or its claims are invalid. return ctx, false } if !ok { // Expiry time claim is invalid. return ctx, false } if exp <= time.Now().UTC().Unix() { // Token expired. return ctx, false } ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, role), ctxConsoleUsernameKey{}, uname), ctxConsoleEmailKey{}, email) return ctx, true } return ctx, false }
CWE-613
7
func (x *DeleteGroupUserRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[18] 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 (s *SMTP) GetDialer() (mailer.Dialer, error) { // Setup the message and dial hp := strings.Split(s.Host, ":") if len(hp) < 2 { hp = append(hp, "25") } host := hp[0] // Any issues should have been caught in validation, but we'll // double check here. port, err := strconv.Atoi(hp[1]) if err != nil { log.Error(err) return nil, err } d := gomail.NewDialer(host, port, s.Username, s.Password) d.TLSConfig = &tls.Config{ ServerName: host, InsecureSkipVerify: s.IgnoreCertErrors, } hostname, err := os.Hostname() if err != nil { log.Error(err) hostname = "localhost" } d.LocalName = hostname return &Dialer{d}, err }
CWE-918
16
func (err ErrInvalidCloneAddr) Error() string { return fmt.Sprintf("invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v]", err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied) }
CWE-918
16
func (p *CompactProtocol) ReadBinary() (value []byte, err error) { length, e := p.readVarint32() if e != nil { return nil, NewProtocolException(e) } if length == 0 { return []byte{}, nil } if length < 0 { return nil, invalidDataLength } if uint64(length) > p.trans.RemainingBytes() { return nil, invalidDataLength } buf := make([]byte, length) _, e = io.ReadFull(p.trans, buf) return buf, NewProtocolException(e) }
CWE-770
37
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) } }
CWE-613
7
func main() { hostPtr := flag.String("host", "localhost:9159", "the hostname that the server should listen on.") tokenPtr := flag.String("token", "", "the Proxy Access Token used to restrict access to the server.") allowedOriginsPtr := flag.String("allowed-origins", "*", "a comma separated list of allowed origins.") bannedOutputsPtr := flag.String("banned-outputs", "", "a comma separated list of banned outputs.") flag.Parse() finished := make(chan bool) libproxy.Initialize(*tokenPtr, *hostPtr, *allowedOriginsPtr, *bannedOutputsPtr, onProxyStateChangeServer, false, finished) <-finished }
CWE-918
16
func (p *HTTPClient) Read(buf []byte) (int, error) { if p.response == nil { return 0, NewTransportException(NOT_OPEN, "Response buffer is empty, no request.") } n, err := p.response.Body.Read(buf) if n > 0 && (err == nil || err == io.EOF) { return n, nil } return n, NewTransportExceptionFromError(err) }
CWE-770
37
func (*ListStorageRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{30} }
CWE-613
7
func (x *Leaderboard) Reset() { *x = Leaderboard{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (s *Server) CheckDeletionToken(deletionToken, token, filename string) error { s.Lock(token, filename) defer s.Unlock(token, filename) var metadata Metadata r, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename)) if s.storage.IsNotExist(err) { return nil } else if err != nil { return err } defer r.Close() if err := json.NewDecoder(r).Decode(&metadata); err != nil { return err } else if metadata.DeletionToken != deletionToken { return errors.New("Deletion token doesn't match.") } return nil }
CWE-79
1
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-178
40
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) } } }
CWE-918
16
func TestClean(t *testing.T) { tests := []struct { path string expVal string }{ { path: "../../../readme.txt", expVal: "readme.txt", }, { path: "a/../../../readme.txt", expVal: "readme.txt", }, { path: "/../a/b/../c/../readme.txt", expVal: "a/readme.txt", }, { path: "/a/readme.txt", expVal: "a/readme.txt", }, { path: "/", expVal: "", }, { path: "/a/b/c/readme.txt", expVal: "a/b/c/readme.txt", }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expVal, Clean(test.path)) }) } }
CWE-22
2
func createDefaultConfigFileIfNotExists() error { defaultFilePath := GetDefaultConfigFilePath() if isExists(defaultFilePath) { return nil } folderPath := filepath.Dir(defaultFilePath) if !isExists(folderPath) { err := os.Mkdir(folderPath, folderPermission) if err != nil { return err } } f, err := os.Create(defaultFilePath) if err != nil { return err } return f.Close() }
CWE-276
45
func IsLocalHostname(hostname string, allowlist []string) bool { for _, allow := range allowlist { if hostname == allow { return false } } ips, err := net.LookupIP(hostname) if err != nil { return true } for _, ip := range ips { for _, cidr := range localCIDRs { if cidr.Contains(ip) { return true } } } return false }
CWE-918
16
func (*Username) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{38} }
CWE-613
7
func (p *CompactProtocol) ReadFieldBegin() (name string, typeId Type, id int16, err error) { t, err := p.readByteDirect() if err != nil { return } // if it's a stop, then we can return immediately, as the struct is over. if (t & 0x0f) == STOP { return "", STOP, 0, nil } // mask off the 4 MSB of the type header. it could contain a field id delta. modifier := int16((t & 0xf0) >> 4) if modifier == 0 { // not a delta. look ahead for the zigzag varint field id. id, err = p.ReadI16() if err != nil { return } } else { // has a delta. add the delta to the last read field id. id = int16(p.lastFieldIDRead) + modifier } typeId, e := p.getType(compactType(t & 0x0f)) if e != nil { err = NewProtocolException(e) return } // if this happens to be a boolean field, the value is encoded in the type if p.isBoolType(t) { // save the boolean value in a special instance variable. p.boolValue = (byte(t)&0x0f == COMPACT_BOOLEAN_TRUE) p.boolValueIsNotNull = true } // push the new field onto the field stack so we can keep the deltas going. p.lastFieldIDRead = int(id) return }
CWE-770
37
func ServeData(ctx *context.Context, name string, size int64, reader io.Reader) error { buf := make([]byte, 1024) n, err := util.ReadAtMost(reader, buf) if err != nil { return err } if n >= 0 { buf = buf[:n] } ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400") if size >= 0 { ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", size)) } else { log.Error("ServeData called to serve data: %s with size < 0: %d", name, size) } name = path.Base(name) // Google Chrome dislike commas in filenames, so let's change it to a space name = strings.ReplaceAll(name, ",", " ") st := typesniffer.DetectContentType(buf) mappedMimeType := "" if setting.MimeTypeMap.Enabled { fileExtension := strings.ToLower(filepath.Ext(name)) mappedMimeType = setting.MimeTypeMap.Map[fileExtension] } if st.IsText() || ctx.FormBool("render") { cs, err := charset.DetectEncoding(buf) if err != nil { log.Error("Detect raw file %s charset failed: %v, using by default utf-8", name, err) cs = "utf-8" } if mappedMimeType == "" { mappedMimeType = "text/plain" } ctx.Resp.Header().Set("Content-Type", mappedMimeType+"; charset="+strings.ToLower(cs)) } else { ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition") if mappedMimeType != "" { ctx.Resp.Header().Set("Content-Type", mappedMimeType) } if (st.IsImage() || st.IsPDF()) && (setting.UI.SVG.Enabled || !st.IsSvgImage()) { ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name)) if st.IsSvgImage() { ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox") ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff") ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType) } } else { ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name)) } } _, err = ctx.Resp.Write(buf) if err != nil { return err } _, err = io.Copy(ctx.Resp, reader) return err }
CWE-79
1
func handleConnect(config *Config, pctx *goproxy.ProxyCtx) error { sctx := pctx.UserData.(*smokescreenContext) // Check if requesting role is allowed to talk to remote sctx.decision, sctx.lookupTime, pctx.Error = checkIfRequestShouldBeProxied(config, pctx.Req, pctx.Req.Host) if pctx.Error != nil { return pctx.Error } if !sctx.decision.allow { return denyError{errors.New(sctx.decision.reason)} } return nil }
CWE-918
16
func (p *Profile) writeConfWgQuick(data *WgConf) (pth string, err error) { allowedIps := []string{} if data.Routes != nil { for _, route := range data.Routes { allowedIps = append(allowedIps, route.Network) } } if data.Routes6 != nil { for _, route := range data.Routes6 { allowedIps = append(allowedIps, route.Network) } } addr := data.Address if data.Address6 != "" { addr += "," + data.Address6 } templData := WgConfData{ Address: addr, PrivateKey: p.PrivateKeyWg, PublicKey: data.PublicKey, AllowedIps: strings.Join(allowedIps, ","), Endpoint: fmt.Sprintf("%s:%d", data.Hostname, data.Port), } if data.DnsServers != nil && len(data.DnsServers) > 0 { templData.HasDns = true templData.DnsServers = strings.Join(data.DnsServers, ",") } output := &bytes.Buffer{} err = WgConfTempl.Execute(output, templData) if err != nil { err = &errortypes.ParseError{ errors.Wrap(err, "profile: Failed to exec wg template"), } return } rootDir := "" switch runtime.GOOS { case "linux": rootDir = WgLinuxConfPath err = os.MkdirAll(WgLinuxConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } case "darwin": rootDir = WgMacConfPath err = os.MkdirAll(WgMacConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } default: rootDir, err = utils.GetTempDir() if err != nil { return } } pth = filepath.Join(rootDir, p.Iface+".conf") os.Remove(pth) err = ioutil.WriteFile( pth, []byte(output.String()), os.FileMode(0600), ) if err != nil { err = &WriteError{ errors.Wrap(err, "profile: Failed to write wg conf"), } return } return }
CWE-59
36
func (*CallApiEndpointRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{12} }
CWE-613
7
func WriteCode(id string, code string) { memory.Code[id] = code }
CWE-305
92
func (x *DeleteFriendRequest) Reset() { *x = DeleteFriendRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (p *BinaryProtocol) ReadBinary() ([]byte, error) { size, e := p.ReadI32() if e != nil { return nil, e } if size < 0 { return nil, invalidDataLength } if uint64(size) > p.trans.RemainingBytes() { return nil, invalidDataLength } isize := int(size) buf := make([]byte, isize) _, err := io.ReadFull(p.trans, buf) return buf, NewProtocolException(err) }
CWE-770
37
func (*DeleteStorageObjectRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{21} }
CWE-613
7
func (*Config_Warning) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{14, 0} }
CWE-613
7
func (*DeleteGroupUserRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{18} }
CWE-613
7
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.3")) { log.Fatal(4, "Package session version is too old, did you forget to update?(github.com/macaron-contrib/session)") } }
CWE-89
0
func (x *ListAccountsRequest) Reset() { *x = ListAccountsRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (p *HTTPClient) RemainingBytes() (num_bytes uint64) { len := p.response.ContentLength if len >= 0 { return uint64(len) } return UnknownRemaining // the truth is, we just don't know unless framed is used }
CWE-770
37
func (x *StorageList) Reset() { *x = StorageList{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *WalletLedgerList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[43] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
CWE-613
7
func (*ListGroupsRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{27} }
CWE-613
7
func TestReadMIMEHeaderNonCompliant(t *testing.T) { // Invalid HTTP response header as sent by an Axis security // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) r := reader("Foo: bar\r\n" + "Content-Language: en\r\n" + "SID : 0\r\n" + "Audio Mode : None\r\n" + "Privilege : 127\r\n\r\n") m, err := r.ReadMIMEHeader() want := MIMEHeader{ "Foo": {"bar"}, "Content-Language": {"en"}, "Sid": {"0"}, "Audio-Mode": {"None"}, "Privilege": {"127"}, } if !reflect.DeepEqual(m, want) || err != nil { t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) } }
CWE-444
41
func TestInvalidPaddingOpen(t *testing.T) { key := make([]byte, 32) nonce := make([]byte, 16) // Plaintext with invalid padding plaintext := padBuffer(make([]byte, 28), aes.BlockSize) plaintext[len(plaintext)-1] = 0xFF io.ReadFull(rand.Reader, key) io.ReadFull(rand.Reader, nonce) block, _ := aes.NewCipher(key) cbc := cipher.NewCBCEncrypter(block, nonce) buffer := append([]byte{}, plaintext...) cbc.CryptBlocks(buffer, buffer) aead, _ := NewCBCHMAC(key, aes.NewCipher) ctx := aead.(*cbcAEAD) // Mutated ciphertext, but with correct auth tag size := len(buffer) ciphertext, tail := resize(buffer, size+(len(key)/2)) copy(tail, ctx.computeAuthTag(nil, nonce, ciphertext[:size])) // Open should fail (b/c of invalid padding, even though tag matches) _, err := aead.Open(nil, nonce, ciphertext, nil) if err == nil || !strings.Contains(err.Error(), "invalid padding") { t.Error("no or unexpected error on open with invalid padding:", err) } }
CWE-190
19
func (*WalletLedgerList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{43} }
CWE-613
7
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 (x *StatusList) Reset() { *x = StatusList{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *ListStorageRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[30] 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 (s *ConsoleServer) lookupConsoleUser(ctx context.Context, unameOrEmail, password string) (id uuid.UUID, uname string, email string, role console.UserRole, err error) { role = console.UserRole_USER_ROLE_UNKNOWN query := "SELECT id, username, email, role, password, disable_time FROM console_user WHERE username = $1 OR email = $1" var dbPassword []byte var dbDisableTime pgtype.Timestamptz err = s.db.QueryRowContext(ctx, query, unameOrEmail).Scan(&id, &uname, &email, &role, &dbPassword, &dbDisableTime) if err != nil { if err == sql.ErrNoRows { err = nil } return } // Check if it's disabled. if dbDisableTime.Status == pgtype.Present && dbDisableTime.Time.Unix() != 0 { s.logger.Info("Console user account is disabled.", zap.String("username", unameOrEmail)) err = status.Error(codes.PermissionDenied, "Invalid credentials.") return } // Check password err = bcrypt.CompareHashAndPassword(dbPassword, []byte(password)) if err != nil { err = status.Error(codes.Unauthenticated, "Invalid credentials.") return } return }
CWE-307
26
func GetCode(id string) string { return memory.Code[id] }
CWE-305
92
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) }) }
CWE-770
37
s := strings.Map(func(c rune) rune { switch c { case ' ', '\t', '\n', '\f', '\r': return c } return -1 }, p.tok.Data) if s != "" { p.addText(s) } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Frameset: p.addElement() case a.Frame: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() case a.Noframes: return inHeadIM(p) case a.Template: // TODO: remove this divergence from the HTML5 spec. // // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 return inTemplateIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Frameset: if p.oe.top().DataAtom != a.Html { p.oe.pop() if p.oe.top().DataAtom != a.Frameset { p.im = afterFramesetIM return true } } } default: // Ignore the token. }
CWE-476
46
func (x *Leaderboard) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[23] 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 *CallApiEndpointResponse) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[13] 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 TestNewOAuth2ResourceServer(t *testing.T) { newMockResourceServer(t) }
CWE-613
7
func (x *DeleteGroupRequest) Reset() { *x = DeleteGroupRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (rarFormat) Read(input io.Reader, destination string) error { rr, err := rardecode.NewReader(input, "") if err != nil { return fmt.Errorf("read: failed to create reader: %v", err) } for { header, err := rr.Next() if err == io.EOF { break } else if err != nil { return err } if header.IsDir { err = mkdir(filepath.Join(destination, header.Name)) if err != nil { return err } continue } // if files come before their containing folders, then we must // create their folders before writing the file err = mkdir(filepath.Dir(filepath.Join(destination, header.Name))) if err != nil { return err } err = writeNewFile(filepath.Join(destination, header.Name), rr, header.Mode()) if err != nil { return err } } return nil }
CWE-22
2
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-601
11
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) } }
CWE-613
7
func (*UpdateGroupRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{37} }
CWE-613
7
func resize(in []byte, n int) (head, tail []byte) { if cap(in) >= n { head = in[:n] } else { head = make([]byte, n) copy(head, in) } tail = head[len(in):] return }
CWE-190
19
func (x *StatusList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[40] 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 *DeleteWalletLedgerRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[22] 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 *DeleteLeaderboardRecordRequest) Reset() { *x = DeleteLeaderboardRecordRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, fifoFd, logFd int) (initer, error) { var config *initConfig if err := json.NewDecoder(pipe).Decode(&config); err != nil { return nil, err } if err := populateProcessEnvironment(config.Env); err != nil { return nil, err } switch t { case initSetns: return &linuxSetnsInit{ pipe: pipe, consoleSocket: consoleSocket, config: config, logFd: logFd, }, nil case initStandard: return &linuxStandardInit{ pipe: pipe, consoleSocket: consoleSocket, parentPid: unix.Getppid(), config: config, fifoFd: fifoFd, logFd: logFd, }, nil } return nil, fmt.Errorf("unknown init type %q", t) }
CWE-190
19
func parseConsoleToken(hmacSecretByte []byte, tokenString string) (username, email string, role console.UserRole, exp int64, ok bool) { token, err := jwt.ParseWithClaims(tokenString, &ConsoleTokenClaims{}, func(token *jwt.Token) (interface{}, error) { if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return hmacSecretByte, nil }) if err != nil { return } claims, ok := token.Claims.(*ConsoleTokenClaims) if !ok || !token.Valid { return } return claims.Username, claims.Email, claims.Role, claims.ExpiresAt, true }
CWE-613
7
func (x *StorageList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[33] 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 *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) }
CWE-613
7
func (*LeaderboardList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{24} }
CWE-613
7
func (x *WalletLedgerList) Reset() { *x = WalletLedgerList{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *LeaderboardRequest) Reset() { *x = LeaderboardRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func doTmpfsCopyUp(m *configs.Mount, rootfs, mountLabel string) (Err error) { // Set up a scratch dir for the tmpfs on the host. tmpdir, err := prepareTmp("/tmp") if err != nil { return fmt.Errorf("tmpcopyup: failed to setup tmpdir: %w", err) } defer cleanupTmp(tmpdir) tmpDir, err := ioutil.TempDir(tmpdir, "runctmpdir") if err != nil { return fmt.Errorf("tmpcopyup: failed to create tmpdir: %w", err) } defer os.RemoveAll(tmpDir) // Configure the *host* tmpdir as if it's the container mount. We change // m.Destination since we are going to mount *on the host*. oldDest := m.Destination m.Destination = tmpDir err = mountPropagate(m, "/", mountLabel) m.Destination = oldDest if err != nil { return err } defer func() { if Err != nil { if err := unmount(tmpDir, unix.MNT_DETACH); err != nil { logrus.Warnf("tmpcopyup: %v", err) } } }() return utils.WithProcfd(rootfs, m.Destination, func(procfd string) (Err error) { // Copy the container data to the host tmpdir. We append "/" to force // CopyDirectory to resolve the symlink rather than trying to copy the // symlink itself. if err := fileutils.CopyDirectory(procfd+"/", tmpDir); err != nil { return fmt.Errorf("tmpcopyup: failed to copy %s to %s (%s): %w", m.Destination, procfd, tmpDir, err) } // Now move the mount into the container. if err := mount(tmpDir, m.Destination, procfd, "", unix.MS_MOVE, ""); err != nil { return fmt.Errorf("tmpcopyup: failed to move mount: %w", err) } return nil }) }
CWE-190
19
func cmdGet(args *docopt.Args, client *tuf.Client) error { if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) { return err } target := util.NormalizeTarget(args.String["<target>"]) file, err := ioutil.TempFile("", "go-tuf") if err != nil { return err } tmp := tmpFile{file} if err := client.Download(target, &tmp); err != nil { return err } defer tmp.Delete() if _, err := tmp.Seek(0, io.SeekStart); err != nil { return err } _, err = io.Copy(os.Stdout, file) return err }
CWE-354
82
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) } }
CWE-613
7
func TestGetDynamic(t *testing.T) { savedServices := services savedGetVCSDirFn := getVCSDirFn defer func() { services = savedServices getVCSDirFn = savedGetVCSDirFn }() services = []*service{{pattern: regexp.MustCompile(".*"), get: testGet}} getVCSDirFn = testGet client := &http.Client{Transport: testTransport(testWeb)} for _, tt := range getDynamicTests { dir, err := getDynamic(context.Background(), client, tt.importPath, "") if tt.dir == nil { if err == nil { t.Errorf("getDynamic(client, %q, etag) did not return expected error", tt.importPath) } continue } if err != nil { t.Errorf("getDynamic(client, %q, etag) return unexpected error: %v", tt.importPath, err) continue } if !cmp.Equal(dir, tt.dir) { t.Errorf("getDynamic(client, %q, etag) =\n %+v,\nwant %+v", tt.importPath, dir, tt.dir) for i, f := range dir.Files { var want *File if i < len(tt.dir.Files) { want = tt.dir.Files[i] } t.Errorf("file %d = %+v, want %+v", i, f, want) } } } }
CWE-22
2
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) } }
CWE-613
7
func (x *MatchStateRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[32] 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_ModuleInfo) Reset() { *x = RuntimeInfo_ModuleInfo{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *ConsoleSession) Reset() { *x = ConsoleSession{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
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) }
CWE-613
7
func (o *casaService) GetServerAppInfo(id, t string) model.ServerAppList { head := make(map[string]string) head["Authorization"] = GetToken() infoS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/info/"+id+"?t="+t, head) info := model.ServerAppList{} json2.Unmarshal([]byte(gjson.Get(infoS, "data").String()), &info) return info }
CWE-78
6
func (*RuntimeInfo) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{41} }
CWE-613
7
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) { // Logic based on response type or status if noBodyExpected(requestMethod) { return 0, nil } if status/100 == 1 { return 0, nil } switch status { case 204, 304: return 0, nil } // Logic based on Transfer-Encoding if chunked(te) { return -1, nil } // Logic based on Content-Length cl := strings.TrimSpace(header.get("Content-Length")) if cl != "" { n, err := parseContentLength(cl) if err != nil { return -1, err } return n, nil } else { header.Del("Content-Length") } if !isResponse && requestMethod == "GET" { // RFC 2616 doesn't explicitly permit nor forbid an // entity-body on a GET request so we permit one if // declared, but we default to 0 here (not -1 below) // if there's no mention of a body. return 0, nil } // Body-EOF logic based on other methods (like closing, or chunked coding) return -1, nil }
CWE-444
41
func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) { // Prevent SQL inject. opt.Keyword = strings.TrimSpace(opt.Keyword) if len(opt.Keyword) == 0 { return repos, nil } opt.Keyword = strings.Split(opt.Keyword, " ")[0] 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) } sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos) return repos, err }
CWE-89
0
func (x *Username) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[38] 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 (*Provider) Render(ctx *provider.Context, config, data string) string { result := blackfriday.Run([]byte(data)) return string(result) }
CWE-79
1
func (c Criteria) OrderBy() string { if c.Sort == "" { c.Sort = "title" } f := fieldMap[strings.ToLower(c.Sort)] var mapped string if f == nil { log.Error("Invalid field in 'sort' field", "field", c.Sort) mapped = c.Sort } else { if f.order == "" { mapped = f.field } else { mapped = f.order } } if c.Order != "" { mapped = mapped + " " + c.Order } return mapped }
CWE-89
0
func (*Config) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{14} }
CWE-613
7
func SettingsEmailPost(c *context.Context, f form.AddEmail) { c.Title("settings.emails") c.PageIs("SettingsEmails") // Make emailaddress primary. if c.Query("_method") == "PRIMARY" { if err := db.MakeEmailPrimary(&db.EmailAddress{ID: c.QueryInt64("id")}); err != nil { c.ServerError("MakeEmailPrimary", err) return } c.SubURLRedirect("/user/settings/email") return } // Add Email address. emails, err := db.GetEmailAddresses(c.User.ID) if err != nil { c.ServerError("GetEmailAddresses", err) return } c.Data["Emails"] = emails if c.HasError() { c.Success(SETTINGS_EMAILS) return } emailAddr := &db.EmailAddress{ UID: c.User.ID, Email: f.Email, IsActivated: !conf.Auth.RequireEmailConfirmation, } if err := db.AddEmailAddress(emailAddr); err != nil { if db.IsErrEmailAlreadyUsed(err) { c.RenderWithErr(c.Tr("form.email_been_used"), SETTINGS_EMAILS, &f) } else { c.ServerError("AddEmailAddress", err) } return } // Send confirmation email if conf.Auth.RequireEmailConfirmation { email.SendActivateEmailMail(c.Context, db.NewMailerUser(c.User), emailAddr.Email) if err := c.Cache.Put("MailResendLimit_"+c.User.LowerName, c.User.LowerName, 180); err != nil { log.Error("Set cache 'MailResendLimit' failed: %v", err) } c.Flash.Info(c.Tr("settings.add_email_confirmation_sent", emailAddr.Email, conf.Auth.ActivateCodeLives/60)) } else { c.Flash.Success(c.Tr("settings.add_email_success")) } c.SubURLRedirect("/user/settings/email") }
CWE-281
93
func (*UpdateGroupUserStateRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{19} }
CWE-613
7
func (x *ListSubscriptionsRequest) Reset() { *x = ListSubscriptionsRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *ListPurchasesRequest) Reset() { *x = ListPurchasesRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (x *UnlinkDeviceRequest) Reset() { *x = UnlinkDeviceRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
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) }
CWE-918
16
func (*StorageList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{33} }
CWE-613
7
func (x *UpdateGroupRequest) Reset() { *x = UpdateGroupRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func (*StatusList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{40} }
CWE-613
7
func (x *RuntimeInfo_ModuleInfo) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[50] 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 *OAuthProxy) IsValidRedirect(redirect string) bool { switch { case redirect == "": // The user didn't specify a redirect, should fallback to `/` return false case strings.HasPrefix(redirect, "/") && !strings.HasPrefix(redirect, "//") && !invalidRedirectRegex.MatchString(redirect): return true case strings.HasPrefix(redirect, "http://") || strings.HasPrefix(redirect, "https://"): redirectURL, err := url.Parse(redirect) if err != nil { logger.Printf("Rejecting invalid redirect %q: scheme unsupported or missing", redirect) return false } redirectHostname := redirectURL.Hostname() for _, domain := range p.whitelistDomains { domainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, ".")) if domainHostname == "" { continue } if (redirectHostname == domainHostname) || (strings.HasPrefix(domain, ".") && strings.HasSuffix(redirectHostname, domainHostname)) { // the domain names match, now validate the ports // if the whitelisted domain's port is '*', allow all ports // if the whitelisted domain contains a specific port, only allow that port // if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https redirectPort := redirectURL.Port() if (domainPort == "*") || (domainPort == redirectPort) || (domainPort == "" && redirectPort == "") { return true } } } logger.Printf("Rejecting invalid redirect %q: domain / port not in whitelist", redirect) return false default: logger.Printf("Rejecting invalid redirect %q: not an absolute or relative URL", redirect) return false } }
CWE-601
11
func (x *DeleteStorageObjectRequest) Reset() { *x = DeleteStorageObjectRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
CWE-613
7
func UnpackTar(filename string, destination string, verbosityLevel int) (err error) { Verbose = verbosityLevel f, err := os.Stat(destination) if os.IsNotExist(err) { return fmt.Errorf("destination directory '%s' does not exist", destination) } filemode := f.Mode() if !filemode.IsDir() { return fmt.Errorf("destination '%s' is not a directory", destination) } if !validSuffix(filename) { return fmt.Errorf("unrecognized archive suffix") } var file *os.File // #nosec G304 if file, err = os.Open(filename); err != nil { return err } defer file.Close() err = os.Chdir(destination) if err != nil { return errors.Wrapf(err, "error changing directory to %s", destination) } var fileReader io.Reader = file var decompressor *gzip.Reader if strings.HasSuffix(filename, globals.GzExt) { if decompressor, err = gzip.NewReader(file); err != nil { return err } defer decompressor.Close() } var reader *tar.Reader if decompressor != nil { reader = tar.NewReader(decompressor) } else { reader = tar.NewReader(fileReader) } return unpackTarFiles(reader) }
CWE-59
36
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 }
CWE-190
19