code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
func (fem *FailedEventsManagerT) DropFailedRecordIDs(taskRunID string) {
if !failedKeysEnabled {
return
}
// Drop table
table := getSqlSafeTablename(taskRunID)
sqlStatement := fmt.Sprintf(`DROP TABLE IF EXISTS %s`, table)
_, err := fem.dbHandle.Exec(sqlStatement)
if err != nil {
pkgLogger.Errorf("Failed to drop table %s with error: %v", taskRunID, err)
}
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func getSqlSafeTablename(taskRunID string) string {
return `"` + strings.ReplaceAll(fmt.Sprintf(`%s_%s`, failedKeysTablePrefix, taskRunID), `"`, `""`) + `"`
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (fem *FailedEventsManagerT) FetchFailedRecordIDs(taskRunID string) []*FailedEventRowT {
if !failedKeysEnabled {
return []*FailedEventRowT{}
}
failedEvents := make([]*FailedEventRowT, 0)
var rows *sql.Rows
var err error
table := getSqlSafeTablename(taskRunID)
sqlStatement := fmt.Sprintf(`SELECT %[1]s.destination_id, %[1]s.record_id
FROM %[1]s `, table)
rows, err = fem.dbHandle.Query(sqlStatement)
if err != nil {
pkgLogger.Errorf("Failed to fetch from table %s with error: %v", taskRunID, err)
return failedEvents
}
defer rows.Close()
for rows.Next() {
var failedEvent FailedEventRowT
err := rows.Scan(&failedEvent.DestinationID, &failedEvent.RecordID)
if err != nil {
panic(err)
}
failedEvents = append(failedEvents, &failedEvent)
}
return failedEvents
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func handle() {
// startReaper()
fluid.LogVersion()
if pprofAddr != "" {
newPprofServer(pprofAddr)
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
})
if err != nil {
panic(fmt.Sprintf("csi: unable to create controller manager due to error %v", err))
}
config := config.Config{
NodeId: nodeID,
Endpoint: endpoint,
PruneFs: pruneFs,
PrunePath: prunePath,
KubeletConfigPath: kubeletKubeConfigPath,
}
if err = csi.SetupWithManager(mgr, config); err != nil {
panic(fmt.Sprintf("unable to set up manager due to error %v", err))
}
ctx := ctrl.SetupSignalHandler()
if err = mgr.Start(ctx); err != nil {
panic(fmt.Sprintf("unable to start controller recover due to error %v", err))
}
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func init() {
// Register k8s-native resources and Fluid CRDs
_ = clientgoscheme.AddToScheme(scheme)
_ = datav1alpha1.AddToScheme(scheme)
if err := flag.Set("logtostderr", "true"); err != nil {
fmt.Printf("Failed to flag.set due to %v", err)
os.Exit(1)
}
startCmd.Flags().StringVarP(&nodeID, "nodeid", "", "", "node id")
if err := startCmd.MarkFlagRequired("nodeid"); err != nil {
ErrorAndExit(err)
}
startCmd.Flags().StringVarP(&endpoint, "endpoint", "", "", "CSI endpoint")
if err := startCmd.MarkFlagRequired("endpoint"); err != nil {
ErrorAndExit(err)
}
startCmd.Flags().StringSliceVarP(&pruneFs, "prune-fs", "", []string{"fuse.alluxio-fuse", "fuse.jindofs-fuse", "fuse.juicefs", "fuse.goosefs-fuse", "ossfs"}, "Prune fs to add in /etc/updatedb.conf, separated by comma")
startCmd.Flags().StringVarP(&prunePath, "prune-path", "", "/runtime-mnt", "Prune path to add in /etc/updatedb.conf")
startCmd.Flags().StringVarP(&metricsAddr, "metrics-addr", "", ":8080", "The address the metrics endpoint binds to.")
startCmd.Flags().StringVarP(&pprofAddr, "pprof-addr", "", "", "The address for pprof to use while exporting profiling results")
startCmd.Flags().StringVarP(&kubeletKubeConfigPath, "kubelet-kube-config", "", "/etc/kubernetes/kubelet.conf", "The file path to kubelet kube config")
utilfeature.DefaultMutableFeatureGate.AddFlag(startCmd.Flags())
startCmd.Flags().AddGoFlagSet(flag.CommandLine)
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func NewDriver(nodeID, endpoint string, client client.Client, apiReader client.Reader, nodeAuthorizedClient *kubernetes.Clientset) *driver {
glog.Infof("Driver: %v version: %v", driverName, version)
proto, addr := utils.SplitSchemaAddr(endpoint)
glog.Infof("protocol: %v addr: %v", proto, addr)
if !strings.HasPrefix(addr, "/") {
addr = fmt.Sprintf("/%s", addr)
}
socketDir := filepath.Dir(addr)
err := os.MkdirAll(socketDir, 0755)
if err != nil {
glog.Errorf("failed due to %v", err)
os.Exit(1)
}
csiDriver := csicommon.NewCSIDriver(driverName, version, nodeID)
csiDriver.AddControllerServiceCapabilities([]csi.ControllerServiceCapability_RPC_Type{csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME})
csiDriver.AddVolumeCapabilityAccessModes([]csi.VolumeCapability_AccessMode_Mode{csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER})
return &driver{
nodeId: nodeID,
endpoint: endpoint,
csiDriver: csiDriver,
client: client,
nodeAuthorizedClient: nodeAuthorizedClient,
apiReader: apiReader,
}
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func (d *driver) newNodeServer() *nodeServer {
return &nodeServer{
nodeId: d.nodeId,
DefaultNodeServer: csicommon.NewDefaultNodeServer(d.csiDriver),
client: d.client,
apiReader: d.apiReader,
nodeAuthorizedClient: d.nodeAuthorizedClient,
}
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func (ns *nodeServer) getNode() (node *v1.Node, err error) {
// Default to allow patch stale node info
if envVar, found := os.LookupEnv(AllowPatchStaleNodeEnv); !found || envVar == "true" {
if ns.node != nil {
glog.V(3).Infof("Found cached node %s", ns.node.Name)
return ns.node, nil
}
}
if node, err = ns.nodeAuthorizedClient.CoreV1().Nodes().Get(context.TODO(), ns.nodeId, metav1.GetOptions{}); err != nil {
return nil, err
}
// if node, err = kubeclient.GetNode(ns.apiReader, ns.nodeId); err != nil {
// return nil, err
// }
glog.V(1).Infof("Got node %s from api server", node.Name)
ns.node = node
return ns.node, nil
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func (ns *nodeServer) patchNodeWithLabel(node *v1.Node, labelsToModify common.LabelsToModify) error {
labels := labelsToModify.GetLabels()
labelValuePair := map[string]interface{}{}
for _, labelToModify := range labels {
operationType := labelToModify.GetOperationType()
labelToModifyKey := labelToModify.GetLabelKey()
labelToModifyValue := labelToModify.GetLabelValue()
switch operationType {
case common.AddLabel, common.UpdateLabel:
labelValuePair[labelToModifyKey] = labelToModifyValue
case common.DeleteLabel:
labelValuePair[labelToModifyKey] = nil
default:
err := fmt.Errorf("fail to update the label due to the wrong operation: %s", operationType)
return err
}
}
metadata := map[string]interface{}{
"metadata": map[string]interface{}{
"labels": labelValuePair,
},
}
patchByteData, err := json.Marshal(metadata)
if err != nil {
return err
}
_, err = ns.nodeAuthorizedClient.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, patchByteData, metav1.PatchOptions{})
if err != nil {
return err
}
return nil
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func (ns *nodeServer) prepareSessMgr(workDir string) error {
sessMgrLabelKey := common.SessMgrNodeSelectorKey
var labelsToModify common.LabelsToModify
labelsToModify.Add(sessMgrLabelKey, "true")
node, err := ns.getNode()
if err != nil {
return errors.Wrapf(err, "can't get node %s", ns.nodeId)
}
// _, err = utils.ChangeNodeLabelWithPatchMode(ns.client, node, labelsToModify)
err = ns.patchNodeWithLabel(node, labelsToModify)
if err != nil {
return errors.Wrapf(err, "error when patching labels on node %s", ns.nodeId)
}
// check sessmgrd.sock file existence
sessMgrSockFilePath := filepath.Join(workDir, common.SessMgrSockFile)
glog.Infof("Checking existence of file %s", sessMgrSockFilePath)
retryLimit := 30
var i int
for i = 0; i < retryLimit; i++ {
if _, err := os.Stat(sessMgrSockFilePath); err == nil {
break
}
// err != nil
if !os.IsNotExist(err) {
glog.Errorf("fail to os.Stat sessmgr socket file %s", sessMgrSockFilePath)
}
time.Sleep(1 * time.Second)
}
if i >= retryLimit {
return errors.New("timeout waiting for SessMgr Pod to be ready")
}
return nil
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func Register(mgr manager.Manager, cfg config.Config) error {
client, err := kubelet.InitNodeAuthorizedClient(cfg.KubeletConfigPath)
if err != nil {
return err
}
csiDriver := NewDriver(cfg.NodeId, cfg.Endpoint, mgr.GetClient(), mgr.GetAPIReader(), client)
if err := mgr.Add(csiDriver); err != nil {
return err
}
return nil
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func InitNodeAuthorizedClient(kubeletKubeConfigPath string) (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags("", kubeletKubeConfigPath)
if err != nil {
return nil, errors.Wrapf(err, "fail to build kubelet config")
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, errors.Wrap(err, "fail to build client-go client from kubelet kubeconfig")
}
return client, nil
} | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
func MakeFilterGenerators(serviceInfo *ci.ServiceInfo) ([]FilterGenerator, error) {
return []FilterGenerator{
&filtergen.HeaderSanitizerGenerator{},
filtergen.NewCORSGenerator(serviceInfo),
// Health check filter is behind Path Matcher filter, since Service Control
// filter needs to get the corresponding rule for health check in order to skip Report
filtergen.NewHealthCheckGenerator(serviceInfo),
filtergen.NewCompressorGenerator(serviceInfo, filtergen.GzipCompressor),
filtergen.NewCompressorGenerator(serviceInfo, filtergen.BrotliCompressor),
filtergen.NewJwtAuthnGenerator(serviceInfo),
filtergen.NewServiceControlGenerator(serviceInfo),
// grpc-web filter should be before grpc transcoder filter.
// It converts content-type application/grpc-web to application/grpc and
// grpc transcoder will bypass requests with application/grpc content type.
// Otherwise grpc transcoder will try to transcode a grpc-web request which
// will fail.
filtergen.NewGRPCWebGenerator(serviceInfo),
filtergen.NewGRPCTranscoderGenerator(serviceInfo),
filtergen.NewBackendAuthGenerator(serviceInfo),
filtergen.NewPathRewriteGenerator(serviceInfo),
filtergen.NewGRPCMetadataScrubberGenerator(serviceInfo),
// Add Envoy Router filter so requests are routed upstream.
// Router filter should be the last.
&filtergen.RouterGenerator{},
}, nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (g *HeaderSanitizerGenerator) IsEnabled() bool {
return true
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (g *HeaderSanitizerGenerator) GenFilterConfig(serviceInfo *ci.ServiceInfo) (*hcmpb.HttpFilter, error) {
a, err := ptypes.MarshalAny(&hspb.FilterConfig{})
if err != nil {
return nil, err
}
return &hcmpb.HttpFilter{
Name: g.FilterName(),
ConfigType: &hcmpb.HttpFilter_TypedConfig{TypedConfig: a},
}, nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (g *HeaderSanitizerGenerator) FilterName() string {
return util.HeaderSanitizerScrubber
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func (g *HeaderSanitizerGenerator) GenPerRouteConfig(method *ci.MethodInfo, httpRule *httppattern.Pattern) (*anypb.Any, error) {
return nil, nil
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
func AccountPostLogin(w http.ResponseWriter, r *http.Request) {
account, err := (&models.Account{Context: ctx.Context}).FromBody(r)
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
var a1 = &models.Account{Context: ctx.Context}
a1.FromData(account)
a1, err = a1.Get()
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
account, err = a1.VerifyPassword(account.Password)
if err != nil {
ctx.HandleStatus(w, r, "Invalid username or password!", http.StatusForbidden)
return
}
session, err := (&models.Session{Context: ctx.Context, Unique: account.Unique}).Post()
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
expiry := time.Now().Add(time.Hour * 15) // TODO: Change this once we've implemented refreshing
SetAuthCookie(w, types.CookieSessionID, session.Key.ID.String(), expiry)
SetAuthCookie(w, types.CookieRefreshToken, session.Refresh, expiry)
ctx.HandleJson(w, r, account.CopyPublic(), http.StatusOK)
} | 1 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
} | 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 authenticateDNSToken(tokenString string) bool {
tokens := strings.Split(tokenString, " ")
if len(tokens) < 2 {
return false
}
return len(servercfg.GetDNSKey()) > 0 && tokens[1] == servercfg.GetDNSKey()
} | 1 | Go | CWE-798 | Use of Hard-coded Credentials | The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. | https://cwe.mitre.org/data/definitions/798.html | safe |
func GetDNSKey() string {
key := ""
if os.Getenv("DNS_KEY") != "" {
key = os.Getenv("DNS_KEY")
} else if config.Config.Server.DNSKey != "" {
key = config.Config.Server.DNSKey
}
return key
} | 1 | Go | CWE-798 | Use of Hard-coded Credentials | The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. | https://cwe.mitre.org/data/definitions/798.html | safe |
eg.Go(func() error {
var err error
if req.IsInternal {
policyOutput, err = e.evaluateInternal(ctx, req)
} else {
policyOutput, err = e.evaluatePolicy(ctx, req)
}
return err
}) | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func NewHeadersRequestFromPolicy(policy *config.Policy, hostname string) *HeadersRequest {
input := new(HeadersRequest)
if policy != nil {
input.EnableGoogleCloudServerlessAuthentication = policy.EnableGoogleCloudServerlessAuthentication
input.EnableRoutingKey = policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_RING_HASH ||
policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_MAGLEV
input.Issuer = hostname
input.KubernetesServiceAccountToken = policy.KubernetesServiceAccountToken
for _, wu := range policy.To {
input.ToAudience = "https://" + wu.URL.Hostname()
}
input.PassAccessToken = policy.GetSetAuthorizationHeader() == configpb.Route_ACCESS_TOKEN
input.PassIDToken = policy.GetSetAuthorizationHeader() == configpb.Route_ID_TOKEN
}
return input
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func getCheckRequestURL(req *envoy_service_auth_v3.CheckRequest) url.URL {
h := req.GetAttributes().GetRequest().GetHttp()
u := url.URL{
Scheme: h.GetScheme(),
Host: h.GetHost(),
}
u.Host = urlutil.GetDomainsForURL(&u)[0]
// envoy sends the query string as part of the path
path := h.GetPath()
if idx := strings.Index(path, "?"); idx != -1 {
u.RawPath, u.RawQuery = path[:idx], path[idx+1:]
u.RawQuery = u.Query().Encode()
} else {
u.RawPath = path
}
u.Path, _ = url.PathUnescape(u.RawPath)
return u
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (a *Authorize) getEvaluatorRequestFromCheckRequest(
in *envoy_service_auth_v3.CheckRequest,
sessionState *sessions.State,
) (*evaluator.Request, error) {
requestURL := getCheckRequestURL(in)
req := &evaluator.Request{
IsInternal: envoyconfig.ExtAuthzContextExtensionsIsInternal(in.GetAttributes().GetContextExtensions()),
HTTP: evaluator.NewRequestHTTP(
in.GetAttributes().GetRequest().GetHttp().GetMethod(),
requestURL,
getCheckRequestHeaders(in),
getPeerCertificate(in),
in.GetAttributes().GetSource().GetAddress().GetSocketAddress().GetAddress(),
),
}
if sessionState != nil {
req.Session = evaluator.RequestSession{
ID: sessionState.ID,
}
}
req.Policy = a.getMatchingPolicy(envoyconfig.ExtAuthzContextExtensionsRouteID(in.Attributes.GetContextExtensions()))
return req, nil
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (a *Authorize) getMatchingPolicy(routeID uint64) *config.Policy {
options := a.currentOptions.Load()
for _, p := range options.GetAllPolicies() {
id, _ := p.RouteID()
if id == routeID {
return &p
}
}
return nil
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func ExtAuthzContextExtensionsRouteID(extAuthzContextExtensions map[string]string) uint64 {
if extAuthzContextExtensions == nil {
return 0
}
routeID, _ := strconv.ParseUint(extAuthzContextExtensions["route_id"], 10, 64)
return routeID
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func ExtAuthzContextExtensionsIsInternal(extAuthzContextExtensions map[string]string) bool {
return extAuthzContextExtensions != nil && extAuthzContextExtensions["internal"] == "true"
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func MakeExtAuthzContextExtensions(internal bool, routeID uint64) map[string]string {
return map[string]string{
"internal": strconv.FormatBool(internal),
"route_id": strconv.FormatUint(routeID, 10),
}
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func PerFilterConfigExtAuthzDisabled() *any.Any {
return marshalAny(&envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute{
Override: &envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute_Disabled{
Disabled: true,
},
})
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func PerFilterConfigExtAuthzContextExtensions(authzContextExtensions map[string]string) *any.Any {
return marshalAny(&envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute{
Override: &envoy_extensions_filters_http_ext_authz_v3.ExtAuthzPerRoute_CheckSettings{
CheckSettings: &envoy_extensions_filters_http_ext_authz_v3.CheckSettings{
ContextExtensions: authzContextExtensions,
},
},
})
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (b *Builder) buildControlPlanePathRoute(
options *config.Options,
path string,
requireStrictTransportSecurity bool,
) *envoy_config_route_v3.Route {
r := &envoy_config_route_v3.Route{
Name: "pomerium-path-" + path,
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: httpCluster,
},
},
},
ResponseHeadersToAdd: toEnvoyHeaders(options.GetSetResponseHeaders(requireStrictTransportSecurity)),
TypedPerFilterConfig: map[string]*any.Any{
PerFilterConfigExtAuthzName: PerFilterConfigExtAuthzContextExtensions(MakeExtAuthzContextExtensions(true, 0)),
},
}
return r
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (b *Builder) buildPomeriumAuthenticateHTTPRoutes(
options *config.Options,
host string,
requireStrictTransportSecurity bool,
) ([]*envoy_config_route_v3.Route, error) {
if !config.IsAuthenticate(options.Services) {
return nil, nil
}
for _, fn := range []func() (*url.URL, error){
options.GetAuthenticateURL,
options.GetInternalAuthenticateURL,
} {
u, err := fn()
if err != nil {
return nil, err
}
if urlMatchesHost(u, host) {
return []*envoy_config_route_v3.Route{
b.buildControlPlanePathRoute(options, options.AuthenticateCallbackPath, requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/", requireStrictTransportSecurity),
}, nil
}
}
return nil, nil
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (b *Builder) buildPomeriumHTTPRoutes(
options *config.Options,
host string,
requireStrictTransportSecurity bool,
) ([]*envoy_config_route_v3.Route, error) {
var routes []*envoy_config_route_v3.Route
// if this is the pomerium proxy in front of the the authenticate service, don't add
// these routes since they will be handled by authenticate
isFrontingAuthenticate, err := isProxyFrontingAuthenticate(options, host)
if err != nil {
return nil, err
}
if !isFrontingAuthenticate {
routes = append(routes,
b.buildControlPlanePathRoute(options, "/ping", requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/healthz", requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/.pomerium", requireStrictTransportSecurity),
b.buildControlPlanePrefixRoute(options, "/.pomerium/", requireStrictTransportSecurity),
b.buildControlPlanePathRoute(options, "/.well-known/pomerium", requireStrictTransportSecurity),
b.buildControlPlanePrefixRoute(options, "/.well-known/pomerium/", requireStrictTransportSecurity),
)
// per #837, only add robots.txt if there are no unauthenticated routes
if !hasPublicPolicyMatchingURL(options, url.URL{Scheme: "https", Host: host, Path: "/robots.txt"}) {
routes = append(routes, b.buildControlPlanePathRoute(options, "/robots.txt", requireStrictTransportSecurity))
}
}
authRoutes, err := b.buildPomeriumAuthenticateHTTPRoutes(options, host, requireStrictTransportSecurity)
if err != nil {
return nil, err
}
routes = append(routes, authRoutes...)
return routes, nil
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (b *Builder) buildGRPCRoutes() ([]*envoy_config_route_v3.Route, error) {
action := &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: "pomerium-control-plane-grpc",
},
},
}
return []*envoy_config_route_v3.Route{{
Name: "pomerium-grpc",
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{
Prefix: "/",
},
Grpc: &envoy_config_route_v3.RouteMatch_GrpcRouteMatchOptions{},
},
Action: action,
TypedPerFilterConfig: map[string]*any.Any{
PerFilterConfigExtAuthzName: PerFilterConfigExtAuthzDisabled(),
},
}}, nil
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
func (b *Builder) buildControlPlanePrefixRoute(
options *config.Options,
prefix string,
requireStrictTransportSecurity bool,
) *envoy_config_route_v3.Route {
r := &envoy_config_route_v3.Route{
Name: "pomerium-prefix-" + prefix,
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: httpCluster,
},
},
},
ResponseHeadersToAdd: toEnvoyHeaders(options.GetSetResponseHeaders(requireStrictTransportSecurity)),
TypedPerFilterConfig: map[string]*any.Any{
PerFilterConfigExtAuthzName: PerFilterConfigExtAuthzContextExtensions(MakeExtAuthzContextExtensions(true, 0)),
},
}
return r
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
routeString := func(typ, name string) string {
str := `{
"name": "pomerium-` + typ + `-` + name + `",
"match": {
"` + typ + `": "` + name + `"
},
"responseHeadersToAdd": [
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-Frame-Options",
"value": "SAMEORIGIN"
}
},
{
"appendAction": "OVERWRITE_IF_EXISTS_OR_ADD",
"header": {
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
}
],
"route": {
"cluster": "pomerium-control-plane-http"
},
"typedPerFilterConfig": {
"envoy.filters.http.ext_authz": {
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
"checkSettings": {
"contextExtensions": {
"internal": "true",
"route_id": "0"
}
}
}
}
}`
return str
} | 1 | Go | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
change, err := controllerutil.CreateOrUpdate(ctx, r.Client, ns, func() error {
if ns.Labels == nil {
ns.Labels = map[string]string{}
}
ns.Labels = helper.SetPodSecurity(ns.Labels)
return nil
})
if err != nil {
return err
}
r.Logger.V(1).Info("create or update ns", "change", change, "ns", ns.Name)
return nil
}) | 1 | Go | CWE-863 | Incorrect Authorization | The product 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 | safe |
err = listSignatures(ctx, sigRepo, manifestDesc, opts.maxSignatures, func(sigManifestDesc ocispec.Descriptor) error {
sigBlob, sigDesc, err := sigRepo.FetchSignatureBlob(ctx, sigManifestDesc)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: unable to fetch signature %s due to error: %v\n", sigManifestDesc.Digest.String(), err)
skippedSignatures = true
return nil
}
sigEnvelope, err := signature.ParseEnvelope(sigDesc.MediaType, sigBlob)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
return nil
}
envelopeContent, err := sigEnvelope.Content()
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
return nil
}
signedArtifactDesc, err := envelope.DescriptorFromSignaturePayload(&envelopeContent.Payload)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
return nil
}
signatureAlgorithm, err := proto.EncodeSigningAlgorithm(envelopeContent.SignerInfo.SignatureAlgorithm)
if err != nil {
logSkippedSignature(sigManifestDesc, err)
skippedSignatures = true
return nil
}
sig := signatureOutput{
MediaType: sigDesc.MediaType,
Digest: sigManifestDesc.Digest.String(),
SignatureAlgorithm: string(signatureAlgorithm),
SignedAttributes: getSignedAttributes(opts.outputFormat, envelopeContent),
UserDefinedAttributes: signedArtifactDesc.Annotations,
UnsignedAttributes: getUnsignedAttributes(envelopeContent),
Certificates: getCertificates(opts.outputFormat, envelopeContent),
SignedArtifact: *signedArtifactDesc,
}
// clearing annotations from the SignedArtifact field since they're already
// displayed as UserDefinedAttributes
sig.SignedArtifact.Annotations = nil
output.Signatures = append(output.Signatures, sig)
return nil
}) | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestInspectCommand_SecretsFromArgs(t *testing.T) {
opts := &inspectOpts{}
command := inspectCommand(opts)
expected := &inspectOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
InsecureRegistry: true,
Username: "user",
},
outputFormat: cmd.OutputPlaintext,
maxSignatures: 100,
}
if err := command.ParseFlags([]string{
"--password", expected.Password,
expected.reference,
"-u", expected.Username,
"--insecure-registry",
"--output", "text"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect inspect opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestInspectCommand_SecretsFromEnv(t *testing.T) {
t.Setenv(defaultUsernameEnv, "user")
t.Setenv(defaultPasswordEnv, "password")
opts := &inspectOpts{}
expected := &inspectOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
Username: "user",
},
outputFormat: cmd.OutputJSON,
maxSignatures: 100,
}
command := inspectCommand(opts)
if err := command.ParseFlags([]string{
expected.reference,
"--output", "json"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect inspect opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func (e ErrorExceedMaxSignatures) Error() string {
return fmt.Sprintf("exceeded configured limit of max signatures %d to examine", e.MaxSignatures)
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func runList(ctx context.Context, opts *listOpts) error {
// set log level
ctx = opts.LoggingFlagOpts.SetLoggerLevel(ctx)
// initialize
reference := opts.reference
sigRepo, err := getRepository(ctx, opts.inputType, reference, &opts.SecureFlagOpts, opts.allowReferrersAPI)
if err != nil {
return err
}
targetDesc, resolvedRef, err := resolveReferenceWithWarning(ctx, opts.inputType, reference, sigRepo, "list")
if err != nil {
return err
}
// print all signature manifest digests
return printSignatureManifestDigests(ctx, targetDesc, sigRepo, resolvedRef, opts.maxSignatures)
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
return sigRepo.ListSignatures(ctx, manifestDesc, func(signatureManifests []ocispec.Descriptor) error {
for _, sigManifestDesc := range signatureManifests {
if numOfSignatureProcessed >= maxSig {
return cmderr.ErrorExceedMaxSignatures{MaxSignatures: maxSig}
}
numOfSignatureProcessed++
if err := fn(sigManifestDesc); err != nil {
return err
}
}
return nil
}) | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
err := listSignatures(ctx, sigRepo, targetDesc, maxSigs, func(sigManifestDesc ocispec.Descriptor) error {
// print the previous signature digest
if prevDigest != "" {
printTitle()
fmt.Printf(" ├── %s\n", prevDigest)
}
prevDigest = sigManifestDesc.Digest
return nil
}) | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestListCommand_SecretsFromEnv(t *testing.T) {
t.Setenv(defaultUsernameEnv, "user")
t.Setenv(defaultPasswordEnv, "password")
opts := &listOpts{}
expected := &listOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
Username: "user",
},
maxSignatures: 100,
}
cmd := listCommand(opts)
if err := cmd.ParseFlags([]string{
expected.reference}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := cmd.Args(cmd, cmd.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect list opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestListCommand_SecretsFromArgs(t *testing.T) {
opts := &listOpts{}
cmd := listCommand(opts)
expected := &listOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Password: "password",
InsecureRegistry: true,
Username: "user",
},
maxSignatures: 100,
}
if err := cmd.ParseFlags([]string{
"--password", expected.Password,
expected.reference,
"-u", expected.Username,
"--insecure-registry"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := cmd.Args(cmd, cmd.Flags().Args()); err != nil {
t.Fatalf("Parse Args failed: %v", err)
}
if *opts != *expected {
t.Fatalf("Expect list opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func runVerify(command *cobra.Command, opts *verifyOpts) error {
// set log level
ctx := opts.LoggingFlagOpts.SetLoggerLevel(command.Context())
// initialize
sigVerifier, err := verifier.NewFromConfig()
if err != nil {
return err
}
// set up verification plugin config.
configs, err := cmd.ParseFlagMap(opts.pluginConfig, cmd.PflagPluginConfig.Name)
if err != nil {
return err
}
// set up user metadata
userMetadata, err := cmd.ParseFlagMap(opts.userMetadata, cmd.PflagUserMetadata.Name)
if err != nil {
return err
}
// core verify process
reference := opts.reference
sigRepo, err := getRepository(ctx, opts.inputType, reference, &opts.SecureFlagOpts, opts.allowReferrersAPI)
if err != nil {
return err
}
// resolve the given reference and set the digest
_, resolvedRef, err := resolveReferenceWithWarning(ctx, opts.inputType, reference, sigRepo, "verify")
if err != nil {
return err
}
intendedRef := resolveArtifactDigestReference(resolvedRef, opts.trustPolicyScope)
verifyOpts := notation.VerifyOptions{
ArtifactReference: intendedRef,
PluginConfig: configs,
MaxSignatureAttempts: opts.maxSignatureAttempts,
UserMetadata: userMetadata,
}
_, outcomes, err := notation.Verify(ctx, sigVerifier, sigRepo, verifyOpts)
err = checkVerificationFailure(outcomes, resolvedRef, err)
if err != nil {
return err
}
reportVerificationSuccess(outcomes, resolvedRef)
return nil
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestVerifyCommand_BasicArgs(t *testing.T) {
opts := &verifyOpts{}
command := verifyCommand(opts)
expected := &verifyOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
Username: "user",
Password: "password",
},
pluginConfig: []string{"key1=val1"},
maxSignatureAttempts: 100,
}
if err := command.ParseFlags([]string{
expected.reference,
"--username", expected.Username,
"--password", expected.Password,
"--plugin-config", "key1=val1"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse args failed: %v", err)
}
if !reflect.DeepEqual(*expected, *opts) {
t.Fatalf("Expect verify opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func TestVerifyCommand_MoreArgs(t *testing.T) {
opts := &verifyOpts{}
command := verifyCommand(opts)
expected := &verifyOpts{
reference: "ref",
SecureFlagOpts: SecureFlagOpts{
InsecureRegistry: true,
},
pluginConfig: []string{"key1=val1", "key2=val2"},
maxSignatureAttempts: 100,
}
if err := command.ParseFlags([]string{
expected.reference,
"--insecure-registry",
"--plugin-config", "key1=val1",
"--plugin-config", "key2=val2"}); err != nil {
t.Fatalf("Parse Flag failed: %v", err)
}
if err := command.Args(command, command.Flags().Args()); err != nil {
t.Fatalf("Parse args failed: %v", err)
}
if !reflect.DeepEqual(*expected, *opts) {
t.Fatalf("Expect verify opts: %v, got: %v", expected, opts)
}
} | 1 | Go | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
func NewQUICServer(addr, password, domain string, tcpTimeout, udpTimeout int, withoutbrook bool) (*QUICServer, error) {
if err := limits.Raise(); err != nil {
Log(&Error{"when": "try to raise system limits", "warning": err.Error()})
}
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(&Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(&Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
var p []byte
var f UDPServerConnFactory
if !withoutbrook {
p = []byte(password)
f = NewPacketServerConnFactory()
}
if withoutbrook {
var err error
p, err = crypto1.SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
f = NewSimplePacketServerConnFactory()
}
s := &QUICServer{
Password: p,
Domain: domain,
Addr: addr,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
UDPServerConnFactory: f,
RunnerGroup: runnergroup.New(),
WithoutBrook: withoutbrook,
}
return s, nil
} | 1 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product 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 (c *StreamClient) Exchange(local net.Conn) error {
go func() {
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
l, err := c.Read()
if err != nil {
return
}
if _, err := local.Write(c.RB[2+16 : 2+16+l]); err != nil {
return
}
}
}()
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := local.Read(c.WB[2+16 : len(c.WB)-16])
if err != nil {
return nil
}
if err := c.Write(l); err != nil {
return nil
}
}
return nil
} | 1 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product 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 (c *StreamClient) Write(l int) error {
binary.BigEndian.PutUint16(c.WB[:2], uint16(l))
c.ca.Seal(c.WB[:0], c.cn, c.WB[:2], nil)
NextNonce(c.cn)
c.ca.Seal(c.WB[:2+16], c.cn, c.WB[2+16:2+16+l], nil)
if _, err := c.Server.Write(c.WB[:2+16+l+16]); err != nil {
return err
}
NextNonce(c.cn)
return nil
} | 1 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product 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 (c *StreamClient) Read() (int, error) {
if _, err := io.ReadFull(c.Server, c.RB[:2+16]); err != nil {
return 0, err
}
if _, err := c.sa.Open(c.RB[:0], c.sn, c.RB[:2+16], nil); err != nil {
return 0, err
}
l := int(binary.BigEndian.Uint16(c.RB[:2]))
if _, err := io.ReadFull(c.Server, c.RB[2+16:2+16+l+16]); err != nil {
return 0, err
}
NextNonce(c.sn)
if _, err := c.sa.Open(c.RB[:2+16], c.sn, c.RB[2+16:2+16+l+16], nil); err != nil {
return 0, err
}
NextNonce(c.sn)
return l, nil
} | 1 | Go | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product 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 EscapeQuote(str string) string {
type Escape struct {
From string
To string
}
escape := []Escape{
{From: "`", To: ""}, // remove the backtick
{From: `\`, To: `\\`},
{From: `'`, To: `\'`},
{From: `"`, To: `\"`},
}
for _, e := range escape {
str = strings.ReplaceAll(str, e.From, e.To)
}
return str
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func TestEscape(t *testing.T) {
assert.Equal(t, "test", EscapeQuote("test"))
assert.Equal(t, "test", EscapeQuote("`test`"))
assert.Equal(t, `\'test\'`, EscapeQuote("'test'"))
assert.Equal(t, `\"test\"`, EscapeQuote(`"test"`))
assert.Equal(t, `\\test\\`, EscapeQuote(`\test\`))
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (r *MySQL) Probe() (bool, string) {
if r.tls != nil {
mysql.RegisterTLSConfig(global.DefaultProg, r.tls)
}
db, err := sql.Open("mysql", r.ConnStr)
if err != nil {
return false, err.Error()
}
defer db.Close()
// Check if we need to query specific data
if len(r.Data) > 0 {
if err := r.ProbeWithDataVerification(db); err != nil {
return false, err.Error()
}
} else {
if err := r.ProbeWithPing(db); err != nil {
return false, err.Error()
}
}
return true, "Check MySQL Server Successfully!"
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (r *MySQL) ProbeWithDataVerification(db *sql.DB) error {
for k, v := range r.Data {
log.Debugf("[%s / %s / %s] - Verifying Data - [%s] : [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, k, v)
sql, err := r.getSQL(k)
if err != nil {
return err
}
log.Debugf("[%s / %s / %s] - SQL - [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, sql)
rows, err := db.Query(sql)
if err != nil {
return err
}
if !rows.Next() {
rows.Close()
return fmt.Errorf("No data found for [%s]", k)
}
//check the value is equal to the value in data
var value string
if err := rows.Scan(&value); err != nil {
rows.Close()
return err
}
if value != v {
rows.Close()
return fmt.Errorf("Value not match for [%s] expected [%s] got [%s] ", k, v, value)
}
rows.Close()
log.Debugf("[%s / %s / %s] - Data Verified Successfully! - [%s] : [%s]", r.ProbeKind, r.ProbeName, r.ProbeTag, k, v)
}
return nil
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (r *MySQL) getSQL(str string) (string, error) {
if len(strings.TrimSpace(str)) == 0 {
return "", fmt.Errorf("Empty SQL data")
}
fields := strings.Split(str, ":")
if len(fields) != 5 {
return "", fmt.Errorf("Invalid SQL data - [%s]. (syntax: database:table:field:key:value)", str)
}
db := global.EscapeQuote(fields[0])
table := global.EscapeQuote(fields[1])
field := global.EscapeQuote(fields[2])
key := global.EscapeQuote(fields[3])
value := global.EscapeQuote(fields[4])
//check value is int or not
if _, err := strconv.Atoi(value); err != nil {
return "", fmt.Errorf("Invalid SQL data - [%s], the value must be int", str)
}
sql := fmt.Sprintf("SELECT `%s` FROM `%s`.`%s` WHERE `%s` = %s", field, db, table, key, value)
return sql, nil
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (r *MySQL) ProbeWithPing(db *sql.DB) error {
if err := db.Ping(); err != nil {
return err
}
row, err := db.Query("show status like \"uptime\"") // run a SQL to test
if err != nil {
return err
}
defer row.Close()
return nil
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (r *PostgreSQL) getSQL(str string) (string, string, error) {
if len(strings.TrimSpace(str)) == 0 {
return "", "", fmt.Errorf("Empty SQL data")
}
fields := strings.Split(str, ":")
if len(fields) != 5 {
return "", "", fmt.Errorf("Invalid SQL data - [%s]. (syntax: database:table:field:key:value)", str)
}
db := global.EscapeQuote(fields[0])
table := global.EscapeQuote(fields[1])
field := global.EscapeQuote(fields[2])
key := global.EscapeQuote(fields[3])
value := global.EscapeQuote(fields[4])
//check value is int or not
if _, err := strconv.Atoi(value); err != nil {
return "", "", fmt.Errorf("Invalid SQL data - [%s], the value must be int", str)
}
sql := fmt.Sprintf(`SELECT "%s" FROM "%s" WHERE "%s" = %s`, field, table, key, value)
return db, sql, nil
} | 1 | Go | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
func (v *SnapshotJob) do(ffmpegPath, inputUrl string) (err error) {
outputPicDir := path.Join(StaticDir, v.App)
if err = os.MkdirAll(outputPicDir, 0777); err != nil {
log.Println(fmt.Sprintf("create snapshot image dir:%v failed, err is %v", outputPicDir, err))
return
}
normalPicPath := path.Join(outputPicDir, fmt.Sprintf("%v", v.Stream)+"-%03d.png")
bestPng := path.Join(outputPicDir, fmt.Sprintf("%v-best.png", v.Stream))
params := []string{
"-i", inputUrl,
"-vf", "fps=1",
"-vcodec", "png",
"-f", "image2",
"-an",
"-vframes", strconv.Itoa(v.vframes),
"-y", normalPicPath,
}
log.Println(fmt.Sprintf("start snapshot, cmd param=%v %v", ffmpegPath, strings.Join(params, " ")))
timeoutCtx, _ := context.WithTimeout(v.cancelCtx, v.timeout)
cmd := exec.CommandContext(timeoutCtx, ffmpegPath, params...)
if err = cmd.Run(); err != nil {
log.Println(fmt.Sprintf("run snapshot %v cmd failed, err is %v", v.Tag(), err))
return
}
bestFileSize := int64(0)
for i := 1; i <= v.vframes; i++ {
pic := path.Join(outputPicDir, fmt.Sprintf("%v-%03d.png", v.Stream, i))
fi, err := os.Stat(pic)
if err != nil {
log.Println(fmt.Sprintf("stat pic:%v failed, err is %v", pic, err))
continue
}
if bestFileSize == 0 {
bestFileSize = fi.Size()
} else if fi.Size() > bestFileSize {
os.Remove(bestPng)
os.Symlink(pic, bestPng)
bestFileSize = fi.Size()
}
}
log.Println(fmt.Sprintf("%v the best thumbnail is %v", v.Tag(), bestPng))
return
} | 1 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
func urlEncode(targetString string) string {
// We use QueryEscape instead of PathEscape here
// for consistency across Drivers. For example:
// QueryEscape escapes space as "+" whereas PE
// it as %20F. PE also does not escape @ or &
// either but QE does.
// The behavior of QE in Golang is more in sync
// with URL encoders in Python and Java hence the choice
return url.QueryEscape(targetString)
} | 1 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
func isValidURL(targetURL string) bool {
if !matcher.MatchString(targetURL) {
logger.Infof(" The provided URL is not a valid URL - " + targetURL)
return false
}
return true
} | 1 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
func TestEncodeURL(t *testing.T) {
testcases := []tcEncodeList{
{"Hello @World", "Hello+%40World"},
{"Test//String", "Test%2F%2FString"},
}
for _, test := range testcases {
result := urlEncode(test.in)
if test.out != result {
t.Errorf("Failed to encode string, input %v, expected: %v, got: %v", test.in, test.out, result)
}
}
} | 1 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
func TestValidURL(t *testing.T) {
testcases := []tcURLList{
{"https://ssoTestURL.okta.com", true},
{"https://ssoTestURL.okta.com:8080", true},
{"https://ssoTestURL.okta.com/testpathvalue", true},
{"-a calculator", false},
{"This is a random test", false},
{"file://TestForFile", false},
}
for _, test := range testcases {
result := isValidURL(test.in)
if test.out != result {
t.Errorf("Failed to validate URL, input :%v, expected: %v, got: %v", test.in, test.out, result)
}
}
} | 1 | Go | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
func (r *TerraformRunnerServer) NewTerraform(ctx context.Context, req *NewTerraformRequest) (*NewTerraformReply, error) {
r.InstanceID = req.GetInstanceID()
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating new terraform", "workingDir", req.WorkingDir, "execPath", req.ExecPath)
tf, err := tfexec.NewTerraform(req.WorkingDir, req.ExecPath)
if err != nil {
log.Error(err, "unable to create new terraform", "workingDir", req.WorkingDir, "execPath", req.ExecPath)
return nil, err
}
// hold only 1 instance
r.tf = tf
var terraform infrav1.Terraform
if err := terraform.FromBytes(req.Terraform, r.Scheme); err != nil {
log.Error(err, "there was a problem getting the terraform resource")
return nil, err
}
// cache the Terraform resource when initializing
r.terraform = &terraform
// init default logger
r.initLogger(log)
return &NewTerraformReply{Id: r.InstanceID}, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) initLogger(log logr.Logger) {
disableTestLogging := os.Getenv("DISABLE_TF_LOGS") == "1"
if !disableTestLogging {
r.tf.SetStdout(os.Stdout)
r.tf.SetStderr(os.Stderr)
if os.Getenv("ENABLE_SENSITIVE_TF_LOGS") == "1" {
r.tf.SetLogger(&LocalPrintfer{logger: log})
}
}
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) tfShowPlanFileRaw(ctx context.Context, planPath string, opts ...tfexec.ShowOption) (string, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
r.tf.SetStderr(io.Discard)
defer r.initLogger(log)
return r.tf.ShowPlanFileRaw(ctx, planPath, opts...)
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) Plan(ctx context.Context, req *PlanRequest) (*PlanReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating a plan")
ctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-r.Done:
cancel()
case <-ctx.Done():
}
}()
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
var planOpt []tfexec.PlanOption
if req.Out != "" {
planOpt = append(planOpt, tfexec.Out(req.Out))
} else {
// if backend is disabled completely, there will be no plan output file (req.Out = "")
log.Info("backend seems to be disabled completely, so there will be no plan output file")
}
if req.Refresh == false {
planOpt = append(planOpt, tfexec.Refresh(req.Refresh))
}
if req.Destroy {
planOpt = append(planOpt, tfexec.Destroy(req.Destroy))
}
for _, target := range req.Targets {
planOpt = append(planOpt, tfexec.Target(target))
}
drifted, err := r.tf.Plan(ctx, planOpt...)
if err != nil {
st := status.New(codes.Internal, err.Error())
var stateErr *tfexec.ErrStateLocked
if errors.As(err, &stateErr) {
st, err = st.WithDetails(&PlanReply{Message: "not ok", StateLockIdentifier: stateErr.ID})
if err != nil {
return nil, err
}
}
log.Error(err, "error creating the plan")
return nil, st.Err()
}
planCreated := false
if req.Out != "" {
planCreated = true
plan, err := r.tfShowPlanFile(ctx, req.Out)
if err != nil {
return nil, err
}
// This is the case when the plan is empty.
if plan.PlannedValues.Outputs == nil &&
plan.PlannedValues.RootModule.Resources == nil &&
plan.ResourceChanges == nil &&
plan.PriorState == nil &&
plan.OutputChanges == nil {
planCreated = false
}
}
return &PlanReply{Message: "ok", Drifted: drifted, PlanCreated: planCreated}, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) tfShowPlanFile(ctx context.Context, planPath string, opts ...tfexec.ShowOption) (*tfjson.Plan, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
r.tf.SetStderr(io.Discard)
defer r.initLogger(log)
return r.tf.ShowPlanFile(ctx, planPath, opts...)
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) SaveTFPlan(ctx context.Context, req *SaveTFPlanRequest) (*SaveTFPlanReply, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("save the plan")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
var tfplan []byte
if req.BackendCompletelyDisable {
tfplan = []byte("dummy plan")
} else {
var err error
tfplan, err = ioutil.ReadFile(filepath.Join(r.tf.WorkingDir(), TFPlanName))
if err != nil {
err = fmt.Errorf("error reading plan file: %s", err)
log.Error(err, "unable to complete SaveTFPlan function")
return nil, err
}
}
planRev := strings.Replace(req.Revision, "/", "-", 1)
planName := "plan-" + planRev
if err := r.writePlanAsSecret(ctx, req.Name, req.Namespace, log, planName, tfplan, "", req.Uuid); err != nil {
return nil, err
}
if r.terraform.Spec.StoreReadablePlan == "json" {
planObj, err := r.tfShowPlanFile(ctx, TFPlanName)
if err != nil {
log.Error(err, "unable to get the plan output for json")
return nil, err
}
jsonBytes, err := json.Marshal(planObj)
if err != nil {
log.Error(err, "unable to marshal the plan to json")
return nil, err
}
if err := r.writePlanAsSecret(ctx, req.Name, req.Namespace, log, planName, jsonBytes, ".json", req.Uuid); err != nil {
return nil, err
}
} else if r.terraform.Spec.StoreReadablePlan == "human" {
rawOutput, err := r.tfShowPlanFileRaw(ctx, TFPlanName)
if err != nil {
log.Error(err, "unable to get the plan output for human")
return nil, err
}
if err := r.writePlanAsConfigMap(ctx, req.Name, req.Namespace, log, planName, rawOutput, "", req.Uuid); err != nil {
return nil, err
}
}
return &SaveTFPlanReply{Message: "ok"}, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) ShowPlanFileRaw(ctx context.Context, req *ShowPlanFileRawRequest) (*ShowPlanFileRawReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("show the raw plan file")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
rawOutput, err := r.tfShowPlanFileRaw(ctx, req.Filename)
if err != nil {
log.Error(err, "unable to get the raw plan output")
return nil, err
}
return &ShowPlanFileRawReply{RawOutput: rawOutput}, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) ShowPlanFile(ctx context.Context, req *ShowPlanFileRequest) (*ShowPlanFileReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("show the raw plan file")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
plan, err := r.tfShowPlanFile(ctx, req.Filename)
if err != nil {
log.Error(err, "unable to get the json plan output")
return nil, err
}
jsonBytes, err := json.Marshal(plan)
if err != nil {
log.Error(err, "unable to marshal the plan to json")
return nil, err
}
return &ShowPlanFileReply{JsonOutput: jsonBytes}, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) Output(ctx context.Context, req *OutputRequest) (*OutputReply, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating outputs")
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
outputs, err := r.tfOutput(ctx)
if err != nil {
log.Error(err, "unable to get outputs")
return nil, err
}
outputReply := &OutputReply{Outputs: map[string]*OutputMeta{}}
for k, v := range outputs {
outputReply.Outputs[k] = &OutputMeta{
Sensitive: v.Sensitive,
Type: v.Type,
Value: v.Value,
}
}
return outputReply, nil
} | 1 | 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 | safe |
func (r *TerraformRunnerServer) tfOutput(ctx context.Context, opts ...tfexec.OutputOption) (map[string]tfexec.OutputMeta, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
r.tf.SetStderr(io.Discard)
defer r.initLogger(log)
return r.tf.Output(ctx, opts...)
} | 1 | 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 | safe |
func (ctx *Context) RedirectToFirst(location ...string) {
for _, loc := range location {
if len(loc) == 0 {
continue
}
// Unfortunately browsers consider a redirect Location with preceding "//", "\\" and "/\" as meaning redirect to "http(s)://REST_OF_PATH"
// Therefore we should ignore these redirect locations to prevent open redirects
if len(loc) > 1 && (loc[0] == '/' || loc[0] == '\\') && (loc[1] == '/' || loc[1] == '\\') {
continue
}
u, err := url.Parse(loc)
if err != nil || ((u.Scheme != "" || u.Host != "") && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {
continue
}
ctx.Redirect(loc)
return
}
ctx.Redirect(setting.AppSubURL + "/")
} | 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 (t *assetAction) checkERC20Deposit() error {
asset, _ := t.asset.ERC20()
return t.bridgeView.FindDeposit(
t.erc20D, t.blockHeight, t.logIndex, asset.Address(), t.txHash,
)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (t *assetAction) checkERC20BridgeResumed() error {
return t.bridgeView.FindBridgeResumed(
t.erc20BridgeResumed, t.blockHeight, t.logIndex, t.txHash)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (t *assetAction) checkERC20AssetList() error {
return t.bridgeView.FindAssetList(t.erc20AL, t.blockHeight, t.logIndex, t.txHash)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (t *assetAction) checkERC20BridgeStopped() error {
return t.bridgeView.FindBridgeStopped(
t.erc20BridgeStopped, t.blockHeight, t.logIndex, t.txHash)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (t *assetAction) checkERC20AssetLimitsUpdated() error {
asset, _ := t.asset.ERC20()
return t.bridgeView.FindAssetLimitsUpdated(
t.erc20AssetLimitsUpdated, t.blockHeight, t.logIndex, asset.Address(), t.txHash,
)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (mr *MockERC20BridgeViewMockRecorder) FindAssetLimitsUpdated(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAssetLimitsUpdated", reflect.TypeOf((*MockERC20BridgeView)(nil).FindAssetLimitsUpdated), arg0, arg1, arg2, arg3, arg4)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (m *MockERC20BridgeView) FindBridgeResumed(arg0 *types.ERC20EventBridgeResumed, arg1, arg2 uint64, arg3 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindBridgeResumed", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (m *MockERC20BridgeView) FindAssetList(arg0 *types.ERC20AssetList, arg1, arg2 uint64, arg3 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindAssetList", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (mr *MockERC20BridgeViewMockRecorder) FindDeposit(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeposit", reflect.TypeOf((*MockERC20BridgeView)(nil).FindDeposit), arg0, arg1, arg2, arg3, arg4)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (mr *MockERC20BridgeViewMockRecorder) FindAssetList(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAssetList", reflect.TypeOf((*MockERC20BridgeView)(nil).FindAssetList), arg0, arg1, arg2, arg3)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (mr *MockERC20BridgeViewMockRecorder) FindBridgeStopped(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindBridgeStopped", reflect.TypeOf((*MockERC20BridgeView)(nil).FindBridgeStopped), arg0, arg1, arg2, arg3)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (m *MockERC20BridgeView) FindBridgeStopped(arg0 *types.ERC20EventBridgeStopped, arg1, arg2 uint64, arg3 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindBridgeStopped", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (mr *MockERC20BridgeViewMockRecorder) FindBridgeResumed(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindBridgeResumed", reflect.TypeOf((*MockERC20BridgeView)(nil).FindBridgeResumed), arg0, arg1, arg2, arg3)
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (m *MockERC20BridgeView) FindAssetLimitsUpdated(arg0 *types.ERC20AssetLimitsUpdated, arg1, arg2 uint64, arg3, arg4 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindAssetLimitsUpdated", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (m *MockERC20BridgeView) FindDeposit(arg0 *types.ERC20Deposit, arg1, arg2 uint64, arg3, arg4 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FindDeposit", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].(error)
return ret0
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindDeposit(
d *types.ERC20Deposit,
blockNumber, logIndex uint64,
ethAssetAddress string,
txHash string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_deposit", d.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetDeposited(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
// user_address
[]ethcommon.Address{ethcommon.HexToAddress(d.SourceEthereumAddress)},
// asset_source
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)})
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
depamount := d.Amount.BigInt()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetDeposited
targetPartyID := strings.TrimPrefix(d.TargetPartyID, "0x")
for iter.Next() {
if hex.EncodeToString(iter.Event.VegaPublicKey[:]) == targetPartyID &&
iter.Event.Amount.Cmp(depamount) == 0 &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20Deposit
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindWithdrawal(
w *types.ERC20Withdrawal,
blockNumber, logIndex uint64,
ethAssetAddress string,
txHash string,
) (*big.Int, string, uint, error) {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return nil, "", 0, err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_withdrawal", w.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetWithdrawn(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
// user_address
[]ethcommon.Address{ethcommon.HexToAddress(w.TargetEthereumAddress)},
// asset_source
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)})
if err != nil {
resp = getMaybeHTTPStatus(err)
return nil, "", 0, err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetWithdrawn
nonce := &big.Int{}
_, ok := nonce.SetString(w.ReferenceNonce, 10)
if !ok {
return nil, "", 0, fmt.Errorf("could not use reference nonce, expected base 10 integer: %v", w.ReferenceNonce)
}
for iter.Next() {
if nonce.Cmp(iter.Event.Nonce) == 0 &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return nil, "", 0, ErrUnableToFindERC20Withdrawal
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return nil, "", 0, err
}
return nonce, event.Raw.TxHash.Hex(), event.Raw.Index, nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindBridgeStopped(
al *types.ERC20EventBridgeStopped,
blockNumber,
logIndex uint64,
txHash string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_bridge_stopped", resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterBridgeStopped(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedBridgeStopped
for iter.Next() {
if iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20BridgeStopped
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindAssetLimitsUpdated(
update *types.ERC20AssetLimitsUpdated,
blockNumber uint64, logIndex uint64,
ethAssetAddress string,
txHash string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_asset_limits_updated", update.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetLimitsUpdated(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
[]ethcommon.Address{ethcommon.HexToAddress(ethAssetAddress)},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetLimitsUpdated
for iter.Next() {
eventLifetimeLimit, _ := num.UintFromBig(iter.Event.LifetimeLimit)
eventWithdrawThreshold, _ := num.UintFromBig(iter.Event.WithdrawThreshold)
if update.LifetimeLimits.EQ(eventLifetimeLimit) &&
update.WithdrawThreshold.EQ(eventWithdrawThreshold) &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20AssetLimitsUpdated
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindBridgeResumed(
al *types.ERC20EventBridgeResumed,
blockNumber,
logIndex uint64,
txHash string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_bridge_stopped", resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterBridgeResumed(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedBridgeResumed
for iter.Next() {
if iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20BridgeStopped
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (e *ERC20LogicView) FindAssetList(
al *types.ERC20AssetList,
blockNumber,
logIndex uint64,
txHash string,
) error {
bf, err := bridgecontract.NewErc20BridgeLogicRestrictedFilterer(
e.clt.CollateralBridgeAddress(), e.clt)
if err != nil {
return err
}
resp := "ok"
defer func() {
metrics.EthCallInc("find_asset_list", al.VegaAssetID, resp)
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
iter, err := bf.FilterAssetListed(
&bind.FilterOpts{
Start: blockNumber - 1,
Context: ctx,
},
[]ethcommon.Address{ethcommon.HexToAddress(al.AssetSource)},
[][32]byte{},
)
if err != nil {
resp = getMaybeHTTPStatus(err)
return err
}
defer iter.Close()
var event *bridgecontract.Erc20BridgeLogicRestrictedAssetListed
assetID := strings.TrimPrefix(al.VegaAssetID, "0x")
for iter.Next() {
if hex.EncodeToString(iter.Event.VegaAssetId[:]) == assetID &&
iter.Event.Raw.BlockNumber == blockNumber &&
uint64(iter.Event.Raw.Index) == logIndex &&
iter.Event.Raw.TxHash.Hex() == txHash {
event = iter.Event
break
}
}
if event == nil {
return ErrUnableToFindERC20AssetList
}
// now ensure we have enough confirmations
if err := e.ethConfs.Check(event.Raw.BlockNumber); err != nil {
return err
}
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (*BridgeViewStub) FindAssetList(al *types.ERC20AssetList, blockNumber, logIndex uint64, txHash string) error {
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
func (*BridgeViewStub) FindDeposit(d *types.ERC20Deposit, blockNumber, logIndex uint64, ethAssetAddress string, txHash string) error {
return nil
} | 1 | Go | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.