id
stringlengths 13
16
| language
stringclasses 9
values | input
dict | output
dict | metadata
dict |
|---|---|---|---|---|
CVE-2021-32701
|
Go
|
{
"vulnerable_code": " - run: go-acc -o coverage.txt ./... -- -failfast -timeout=20m\n - run: test -z \"$CIRCLE_PR_NUMBER\" && goveralls -service=circle-ci -coverprofile=coverage.txt -repotoken=$COVERALLS_REPO_TOKEN || echo \"forks are not allowed to push to coveralls\"\n these headers will be passed to upstream services.\n For example, an user containing scopes/branches inside an organization profile\n has some level of data addressed to him. In this case, the upstream service\n need to know that, and \"filter\" the data according to his \"branch_id\". The\n permission that is given to the user (and the remote authorizers manages) has\n a record of the \"branch_id\", for the following responses will be returned as\n status code 200 (if granted) and containing a header like X-Branch-Id.\n The upstream service receives the X-Branch-Id and does your thing.\n The configuration requires to configure a list of \"allowed headers\" returning\n from remote authorizer, that will be accepted in the pipeline.\n closes [#668](https://github.com/ory/oathkeeper/issues/668):\n JWT Claims added to error details field.\n closes [#630](https://github.com/ory/oathkeeper/issues/630):\n This makes `/` also a separator as well as the presumably default value of\n `.`. This allows using <\\*> for matching only one path segment.\n closes [#511](https://github.com/ory/oathkeeper/issues/511):\n This change introduces a url_param config option for redirect error handler.\n If it contains a url paramter name, the redirect url will have this parameter\n set, containing the current url (from which Oathkeeper has redirected the\n user).\n size.\n This change makes sure the Content-Length doesn't get included in the response\n body and adds a test to prevent future regressions.\n closes [#417](https://github.com/ory/oathkeeper/issues/417):\n This patch introduces new configuration parameters that allow the hydrator\n mutator to cache requests.\n the body into account in its decision.\n The current remote_json authorizer does not have the ability to send the\n request body of the request to authorize. This means this cannot be taken into\n account while checking permissions.\n closes [#377](https://github.com/ory/oathkeeper/issues/377):\n This patch removes the `scope` key from the OAuth2 Introspection request body\n when a scope strategy other than `none` is set for the OAuth2 Introspection\n handler. If the scope strategy is `none`, the `scope` key is included in the\n body.\n closes [#324](https://github.com/ory/oathkeeper/issues/324):\n Add a new file 'Dockerfile-dc' which will primarily be used by Docker Compose\n to build docker images. Unlike the existing Dockerfile which depends on the\n Makefile to build the binary, this Dockerfile copies the source code and\n builds the binary.\n closes [#374](https://github.com/ory/oathkeeper/issues/374):\n Fixed link to Envoy configuration page and added link to AWS API Gateway.\n closes [#321](https://github.com/ory/oathkeeper/issues/321):\n This patch adds the ability to choose a matching strategy and adds a\n glob-based matching strategy to the available options (regex is still the\n default).\n closes [#336](https://github.com/ory/oathkeeper/issues/336):\n The subject_from modifier is a GJSON path that points to the `subject` field.\n Useful if the upstream API does not return a `{\"subject\": \"...\"}` format.\n closes [#335](https://github.com/ory/oathkeeper/issues/335):\n The extra_from modifier is a GJSON path that points to the extra field. Useful\n if the upstream API does not return a `{\"subject\": \"...\", \"extra\": \"...\"}`\n format.\n [#330](https://github.com/ory/oathkeeper/issues/330):\n Also updates the schemas to add missing cookie config element.\n closes [#323](https://github.com/ory/oathkeeper/issues/323):\n Previously, MIME matching respected the request's wildcards which lead to\n multiple handlers feeling responsible for a particular request. Now, wildcards\n coming from the HTTP Request itself are interpreted literally.\n Additionally, ORY Oathkeeper respected the X-Forwarded-For HTTP Header for\n matching remote IP addresses. This behavior is now turned off by default\n because clients were able to fake this header otherwise. It can explicitly be\n turned on by setting\n [#119](https://github.com/ory/oathkeeper/issues/119):\n This patch adds a new feature called error handlers. It allows to define the\n error handling logic globally and per rule. It is now possible, for example,\n to return a JSON response for `Accept: application/json` requests and a HTTP\n Redirect response for requests that are coming from a user.\n This also resolves several issues, as noted below:\n [#317](https://github.com/ory/oathkeeper/issues/317):\n Previously, some keys did not respect the values set in the environment\n variables.\n [#242](https://github.com/ory/oathkeeper/issues/242):\n Adds details such as the HTTP Method, User Agent, Subject, and other\n information to the logging output of both the reverse proxy and the decision\n API.\n closes [#283](https://github.com/ory/oathkeeper/issues/283):\n Remove health endpoints from the logs to make monitoring easier. Setting\n `log_level` to `trace` will show these calls.\n closes [#291](https://github.com/ory/oathkeeper/issues/291):\n A bug caused the rule matcher to not cache the regular expression result.\n [#280](https://github.com/ory/oathkeeper/issues/280):\n This patch automatically binds environment variables to configuration keys.\n This patch resolves several issues:\n [#257](https://github.com/ory/oathkeeper/issues/257):\n Add additional optional configuration to jwt and oauth2_introspection\n authenticators allowing to set from where (which header or query parameter)\n the token should be received. The configuration is a token_from field in\n per-rule-configuration, as described in a linked issue.\n closes [#266](https://github.com/ory/oathkeeper/issues/266):\n Adds the ability to modify rules with backwards compatibility.\n closes [#217](https://github.com/ory/oathkeeper/issues/217):\n This patch allows oathkeeper to re-load any changes made to the configuraiton\n file and/or the access rules to be reloaded without a restart.\n Some configuration keys like serve._, log._, profiling however require a\n restart.\n closes [#213](https://github.com/ory/oathkeeper/issues/213):\n This commit adds support for defining access rules in YAML format, in addition\n to existing JSON format.\n closes [#204](https://github.com/ory/oathkeeper/issues/204):\n There's no DSN in oathkeeper\n closes [#199](https://github.com/ory/oathkeeper/issues/199):\n Previously, negroni.With was mistakenly used to add middleware onto the stack.\n The proper method however is negroni.Use.\n This patch fixes the use of negroni.With and resolves issues around logging\n and the decisions endpoint.\n closes [#138](https://github.com/ory/oathkeeper/issues/138):\n Previously, the JWT authenticator only used the \"scope\" claim to retrieve\n scope values from a JWT. Now, \"scp\", \"scope\", \"scopes\" are supported as string\n arrays and strings separated by spaces.\n closes [#42](https://github.com/ory/oathkeeper/issues/42):\n This patch adds endpoint `/judge` to `oathkeeper serve api`. The `/judge`\n endpoint mimics the behavior of `oathkeeper serve proxy` but instead of\n forwarding the request to the upstream server, the endpoint answers directly\n with a HTTP response.\n The HTTP response returns status code 200 if the request should be allowed and\n any other status code (e.g. 401, 403) if not.\n Assuming you are making the following request:\n a server handled proxy requests.\n It will help prevent a case of unexpected closing a client connection if an\n upstream request is executing more than default timeout.\n closes [#101](https://github.com/ory/oathkeeper/issues/101):\n This patch improves compatibility with ORY Hydra 1.0.0-beta.8 and updates\n vendored dependencies.\n closes [#38](https://github.com/ory/oathkeeper/issues/38):\n Previously, PUT and POST did not result in errors (409) when non-existing\n resources were modified, or existing resources were created. This patch\n resolves that.\n closes [#73](https://github.com/ory/oathkeeper/issues/73):\n This patch resolves an issue where updates would not properly propagate. This\n caused deleted rules to still be available in the proxy.\n closes [#71](https://github.com/ory/oathkeeper/issues/71):\n This patch adds another ID Token signing algorithm (HS256) which is easier to\n set up as it does not rely on ORY Hydra but instead on a shared secret.\n Additionally the ability to specify which ID Token singing algorithm to use\n has been added. Environmental variables to configure the behvaiour have been\n added as well.\nfunc (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {\n\t\treturn nil, false\n\t\treturn nil, false\n\ti := item.(*AuthenticatorOAuth2IntrospectionResult)\n\texpires := time.Unix(i.Expires, 0)\n\tif expires.Before(time.Now()) {\n\t\ta.tokenCache.Del(token)\n\t\treturn nil, false\n\treturn i, true\nfunc (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) {\n\ttracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))\n\tss := a.c.ToScopeStrategy(cf.ScopeStrategy, \"authenticators.oauth2_introspection.scope_strategy\")\n\ti, ok := a.tokenFromCache(cf, token)\n\tif !ok {\n\t\tbody := url.Values{\"token\": {token}}\n\t\tif len(i.TokenUse) > 0 && i.TokenUse != \"access_token\" {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Use of introspected token is not an access token but \\\"%s\\\"\", i.TokenUse)))\n\t\t}\n\t\tif !i.Active {\n\t\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token i says token is not active\"))\n\t\t}\n\t\tfor _, audience := range cf.Audience {\n\t\t\tif !stringslice.Has(i.Audience, audience) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token audience is not intended for target audience %s\", audience)))\n\t\t\t}\n\t\tif len(cf.Issuers) > 0 {\n\t\t\tif !stringslice.Has(cf.Issuers, i.Issuer) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token issuer does not match any trusted issuer\")))\n\t\t\t}\n\t\tif ss != nil {\n\t\t\tfor _, scope := range cf.Scopes {\n\t\t\t\tif !ss(strings.Split(i.Scope, \" \"), scope) {\n\t\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Scope %s was not granted\", scope)))\n\t\t\t\t}\n\t\tif len(i.Extra) == 0 {\n\t\t\ti.Extra = map[string]interface{}{}\n\t\t}\n\t\ti.Extra[\"username\"] = i.Username\n\t\ti.Extra[\"client_id\"] = i.ClientID\n\t\ti.Extra[\"scope\"] = i.Scope\n\t\tif len(i.Audience) != 0 {\n\t\t\ti.Extra[\"aud\"] = i.Audience\n\t\t}\n\t\ta.tokenToCache(cf, i, token)\n\t\tcache, _ := ristretto.NewCache(&ristretto.Config{\n\t\t\tMaxCost: int64(c.Cache.MaxCost),\n"
}
|
{
"secure_code": " - run: go-acc -o coverage.out ./... -- -failfast -timeout=20m\n - run: |\n bash <(curl -s https://codecov.io/bash)\nnode_modules: package.json package-lock.json\n\t\tnpm i\n\n these headers will be passed to upstream services. For example, an user\n containing scopes/branches inside an organization profile has some level of\n data addressed to him. In this case, the upstream service need to know that,\n and \"filter\" the data according to his \"branch_id\". The permission that is\n given to the user (and the remote authorizers manages) has a record of the\n \"branch_id\", for the following responses will be returned as status code 200\n (if granted) and containing a header like X-Branch-Id. The upstream service\n receives the X-Branch-Id and does your thing. The configuration requires to\n configure a list of \"allowed headers\" returning from remote authorizer, that\n will be accepted in the pipeline.\n\n\n closes [#668](https://github.com/ory/oathkeeper/issues/668): JWT Claims added\n to error details field.\n closes [#630](https://github.com/ory/oathkeeper/issues/630): This makes `/`\n also a separator as well as the presumably default value of `.`. This allows\n using <\\*> for matching only one path segment.\n closes [#511](https://github.com/ory/oathkeeper/issues/511): This change\n introduces a url_param config option for redirect error handler. If it\n contains a url paramter name, the redirect url will have this parameter set,\n containing the current url (from which Oathkeeper has redirected the user).\n size. This change makes sure the Content-Length doesn't get included in the\n response body and adds a test to prevent future regressions.\n closes [#417](https://github.com/ory/oathkeeper/issues/417): This patch\n introduces new configuration parameters that allow the hydrator mutator to\n cache requests.\n the body into account in its decision. The current remote_json authorizer does\n not have the ability to send the request body of the request to authorize.\n This means this cannot be taken into account while checking permissions.\n closes [#377](https://github.com/ory/oathkeeper/issues/377): This patch\n removes the `scope` key from the OAuth2 Introspection request body when a\n scope strategy other than `none` is set for the OAuth2 Introspection handler.\n If the scope strategy is `none`, the `scope` key is included in the body.\n closes [#324](https://github.com/ory/oathkeeper/issues/324): Add a new file\n 'Dockerfile-dc' which will primarily be used by Docker Compose to build docker\n images. Unlike the existing Dockerfile which depends on the Makefile to build\n the binary, this Dockerfile copies the source code and builds the binary.\n closes [#374](https://github.com/ory/oathkeeper/issues/374): Fixed link to\n Envoy configuration page and added link to AWS API Gateway.\n closes [#321](https://github.com/ory/oathkeeper/issues/321): This patch adds\n the ability to choose a matching strategy and adds a glob-based matching\n strategy to the available options (regex is still the default).\n closes [#336](https://github.com/ory/oathkeeper/issues/336): The subject_from\n modifier is a GJSON path that points to the `subject` field. Useful if the\n upstream API does not return a `{\"subject\": \"...\"}` format.\n closes [#335](https://github.com/ory/oathkeeper/issues/335): The extra_from\n modifier is a GJSON path that points to the extra field. Useful if the\n upstream API does not return a `{\"subject\": \"...\", \"extra\": \"...\"}` format.\n [#330](https://github.com/ory/oathkeeper/issues/330): Also updates the schemas\n to add missing cookie config element.\n closes [#323](https://github.com/ory/oathkeeper/issues/323): Previously, MIME\n matching respected the request's wildcards which lead to multiple handlers\n feeling responsible for a particular request. Now, wildcards coming from the\n HTTP Request itself are interpreted literally. Additionally, ORY Oathkeeper\n respected the X-Forwarded-For HTTP Header for matching remote IP addresses.\n This behavior is now turned off by default because clients were able to fake\n this header otherwise. It can explicitly be turned on by setting\n [#119](https://github.com/ory/oathkeeper/issues/119): This patch adds a new\n feature called error handlers. It allows to define the error handling logic\n globally and per rule. It is now possible, for example, to return a JSON\n response for `Accept: application/json` requests and a HTTP Redirect response\n for requests that are coming from a user. This also resolves several issues,\n as noted below:\n [#317](https://github.com/ory/oathkeeper/issues/317): Previously, some keys\n did not respect the values set in the environment variables.\n [#242](https://github.com/ory/oathkeeper/issues/242): Adds details such as the\n HTTP Method, User Agent, Subject, and other information to the logging output\n of both the reverse proxy and the decision API.\n closes [#283](https://github.com/ory/oathkeeper/issues/283): Remove health\n endpoints from the logs to make monitoring easier. Setting `log_level` to\n `trace` will show these calls.\n closes [#291](https://github.com/ory/oathkeeper/issues/291): A bug caused the\n rule matcher to not cache the regular expression result.\n [#280](https://github.com/ory/oathkeeper/issues/280): This patch automatically\n binds environment variables to configuration keys. This patch resolves several\n issues:\n [#257](https://github.com/ory/oathkeeper/issues/257): Add additional optional\n configuration to jwt and oauth2_introspection authenticators allowing to set\n from where (which header or query parameter) the token should be received. The\n configuration is a token_from field in per-rule-configuration, as described in\n a linked issue.\n closes [#266](https://github.com/ory/oathkeeper/issues/266): Adds the ability\n to modify rules with backwards compatibility.\n closes [#217](https://github.com/ory/oathkeeper/issues/217): This patch allows\n oathkeeper to re-load any changes made to the configuraiton file and/or the\n access rules to be reloaded without a restart. Some configuration keys like\n serve._, log._, profiling however require a restart.\n closes [#213](https://github.com/ory/oathkeeper/issues/213): This commit adds\n support for defining access rules in YAML format, in addition to existing JSON\n format.\n closes [#204](https://github.com/ory/oathkeeper/issues/204): There's no DSN in\n oathkeeper\n closes [#199](https://github.com/ory/oathkeeper/issues/199): Previously,\n negroni.With was mistakenly used to add middleware onto the stack. The proper\n method however is negroni.Use. This patch fixes the use of negroni.With and\n resolves issues around logging and the decisions endpoint.\n closes [#138](https://github.com/ory/oathkeeper/issues/138): Previously, the\n JWT authenticator only used the \"scope\" claim to retrieve scope values from a\n JWT. Now, \"scp\", \"scope\", \"scopes\" are supported as string arrays and strings\n separated by spaces.\n closes [#42](https://github.com/ory/oathkeeper/issues/42): This patch adds\n endpoint `/judge` to `oathkeeper serve api`. The `/judge` endpoint mimics the\n behavior of `oathkeeper serve proxy` but instead of forwarding the request to\n the upstream server, the endpoint answers directly with a HTTP response. The\n HTTP response returns status code 200 if the request should be allowed and any\n other status code (e.g. 401, 403) if not. Assuming you are making the\n following request:\n a server handled proxy requests. It will help prevent a case of unexpected\n closing a client connection if an upstream request is executing more than\n default timeout.\n closes [#101](https://github.com/ory/oathkeeper/issues/101): This patch\n improves compatibility with ORY Hydra 1.0.0-beta.8 and updates vendored\n dependencies.\n closes [#38](https://github.com/ory/oathkeeper/issues/38): Previously, PUT and\n POST did not result in errors (409) when non-existing resources were modified,\n or existing resources were created. This patch resolves that.\n closes [#73](https://github.com/ory/oathkeeper/issues/73): This patch resolves\n an issue where updates would not properly propagate. This caused deleted rules\n to still be available in the proxy.\n closes [#71](https://github.com/ory/oathkeeper/issues/71): This patch adds\n another ID Token signing algorithm (HS256) which is easier to set up as it\n does not rely on ORY Hydra but instead on a shared secret. Additionally the\n ability to specify which ID Token singing algorithm to use has been added.\n Environmental variables to configure the behvaiour have been added as well.\n\nPlease note that caching will not be used if the scope strategy is `none` and\n`required_scope` is not empty. In that case, the configured introspection URL\nwill always be called and is expected to check if the scope is valid or not.\n\n\n\t\"github.com/ory/fosite\"\n\nfunc (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string, ss fosite.ScopeStrategy) *AuthenticatorOAuth2IntrospectionResult {\n\t\treturn nil\n\t}\n\n\tif ss == nil && len(config.Scopes) > 0 {\n\t\treturn nil\n\t\treturn nil\n\ti, ok := item.(*AuthenticatorOAuth2IntrospectionResult)\n\tif !ok {\n\t\treturn nil\n\treturn i\nfunc (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string, ss fosite.ScopeStrategy) {\n\tif ss == nil && len(config.Scopes) > 0 {\n\t\treturn\n\t}\n\n\t_ = tracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))\n\tss := a.c.ToScopeStrategy(cf.ScopeStrategy, \"authenticators.oauth2_introspection.config.scope_strategy\")\n\ti := a.tokenFromCache(cf, token, ss)\n\t// If the token can not be found, and the scope strategy is nil, and the required scope list\n\t// is not empty, then we can not use the cache.\n\tif i == nil {\n\t\tbody := url.Values{\"token\": {token}}\n\n\t}\n\tif len(i.TokenUse) > 0 && i.TokenUse != \"access_token\" {\n\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Use of introspected token is not an access token but \\\"%s\\\"\", i.TokenUse)))\n\t}\n\tif !i.Active {\n\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token is not active\"))\n\t}\n\tif i.Expires > 0 && time.Unix(i.Expires, 0).Before(time.Now()) {\n\t\treturn errors.WithStack(helper.ErrUnauthorized.WithReason(\"Access token expired\"))\n\t}\n\n\tfor _, audience := range cf.Audience {\n\t\tif !stringslice.Has(i.Audience, audience) {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token audience is not intended for target audience %s\", audience)))\n\t}\n\tif len(cf.Issuers) > 0 {\n\t\tif !stringslice.Has(cf.Issuers, i.Issuer) {\n\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Token issuer does not match any trusted issuer\")))\n\t}\n\tif ss != nil {\n\t\tfor _, scope := range cf.Scopes {\n\t\t\tif !ss(strings.Split(i.Scope, \" \"), scope) {\n\t\t\t\treturn errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf(\"Scope %s was not granted\", scope)))\n\t}\n\ta.tokenToCache(cf, i, token, ss)\n\tif len(i.Extra) == 0 {\n\t\ti.Extra = map[string]interface{}{}\n\t}\n\ti.Extra[\"username\"] = i.Username\n\ti.Extra[\"client_id\"] = i.ClientID\n\ti.Extra[\"scope\"] = i.Scope\n\tif len(i.Audience) != 0 {\n\t\ti.Extra[\"aud\"] = i.Audience\n\t\tcost := int64(c.Cache.MaxCost)\n\t\tif cost == 0 {\n\t\t\tcost = 100000000\n\t\t}\n\t\tcache, err := ristretto.NewCache(&ristretto.Config{\n\t\t\tMaxCost: cost,\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ory/x/assertx\"\n\tt.Run(\"method=authenticate-with-cache\", func(t *testing.T) {\n\t\tviper.Set(\"authenticators.oauth2_introspection.config.cache.enabled\", true)\n\t\tt.Cleanup(func() {\n\t\t\tviper.Set(\"authenticators.oauth2_introspection.config.cache.enabled\", false)\n\t\t})\n\n\t\tvar didNotUseCache sync.WaitGroup\n\n\t\tsetup := func(t *testing.T, config string) []byte {\n\t\t\trouter := httprouter.New()\n\t\t\trouter.POST(\"/oauth2/introspect\", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t\t\t\tdefer didNotUseCache.Done()\n\t\t\t\trequire.NoError(t, r.ParseForm())\n\t\t\t\tswitch r.Form.Get(\"token\") {\n\t\t\t\tcase \"inactive-scope-b\":\n\t\t\t\t\trequire.NoError(t, json.NewEncoder(w).Encode(&AuthenticatorOAuth2IntrospectionResult{\n\t\t\t\t\t\tActive: false,\n\t\t\t\t\t}))\n\t\t\t\tcase \"another-active-scope-a\":\n\t\t\t\t\tfallthrough\n\t\t\t\tcase \"active-scope-a\":\n\t\t\t\t\tif r.Form.Get(\"scope\") != \"\" && r.Form.Get(\"scope\") != \"scope-a\" {\n\t\t\t\t\t\trequire.NoError(t, json.NewEncoder(w).Encode(&AuthenticatorOAuth2IntrospectionResult{\n\t\t\t\t\t\t\tActive: false,\n\t\t\t\t\t\t}))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\trequire.NoError(t, json.NewEncoder(w).Encode(&AuthenticatorOAuth2IntrospectionResult{\n\t\t\t\t\t\tActive: true,\n\t\t\t\t\t\tScope: \"scope-a\",\n\t\t\t\t\t\tSubject: \"subject\",\n\t\t\t\t\t\tAudience: []string{\"audience\"},\n\t\t\t\t\t\tIssuer: \"foo\",\n\t\t\t\t\t\tUsername: \"username\",\n\t\t\t\t\t\tExpires: time.Now().Add(time.Second).Unix(),\n\t\t\t\t\t\tExtra: map[string]interface{}{\"extra\": \"foo\"},\n\t\t\t\t\t}))\n\t\t\t\tcase \"refresh-token\":\n\t\t\t\t\trequire.NoError(t, json.NewEncoder(w).Encode(&AuthenticatorOAuth2IntrospectionResult{\n\t\t\t\t\t\tActive: true,\n\t\t\t\t\t\tScope: \"scope-a\",\n\t\t\t\t\t\tSubject: \"subject\",\n\t\t\t\t\t\tAudience: []string{\"audience\"},\n\t\t\t\t\t\tIssuer: \"foo\",\n\t\t\t\t\t\tUsername: \"username\",\n\t\t\t\t\t\tTokenUse: \"refresh_token\",\n\t\t\t\t\t\tExtra: map[string]interface{}{\"extra\": \"foo\"},\n\t\t\t\t\t}))\n\t\t\t\tdefault:\n\t\t\t\t\trequire.NoError(t, json.NewEncoder(w).Encode(&AuthenticatorOAuth2IntrospectionResult{\n\t\t\t\t\t\tActive: false,\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t})\n\t\t\tts := httptest.NewServer(router)\n\t\t\tt.Cleanup(ts.Close)\n\n\t\t\tconfig, err = sjson.Set(config, \"introspection_url\", ts.URL+\"/oauth2/introspect\")\n\t\t\trequire.NoError(t, err)\n\t\t\tconfig, err = sjson.Set(config, \"pre_authorization.token_url\", ts.URL+\"/oauth2/token\")\n\t\t\trequire.NoError(t, err)\n\n\t\t\treturn []byte(config)\n\t\t}\n\n\t\tt.Run(\"case=with none scope strategy\", func(t *testing.T) {\n\t\t\tviper.Set(\"authenticators.oauth2_introspection.config.scope_strategy\", \"none\")\n\t\t\tr := &http.Request{Header: http.Header{\"Authorization\": {\"bearer active-scope-a\"}}}\n\t\t\texpected := new(AuthenticationSession)\n\t\t\tt.Run(\"case=initial request succeeds\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\n\t\t\t\tdidNotUseCache.Add(1)\n\t\t\t\terr = a.Authenticate(r, expected, config, nil)\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\n\t\t\t// We expect to use the cache here because we are not interested to validate the scope. Usually we would\n\t\t\t// expect to make the upstream call if the upstream has to validate the scope.\n\t\t\tt.Run(\"case=second request does use cache because no scope was requested and strategy is nil\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\tsess := new(AuthenticationSession)\n\n\t\t\t\terr = a.Authenticate(r, sess, config, nil)\n\t\t\t\tdidNotUseCache.Wait() // Would result in a panic if wg.done was called!\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassertx.EqualAsJSON(t, expected, sess)\n\t\t\t})\n\n\t\t\tt.Run(\"case=second request does not use cache because scope strategy is disabled and scope was requested request succeeds\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\tsess := new(AuthenticationSession)\n\n\t\t\t\tdidNotUseCache.Add(1)\n\t\t\t\terr = a.Authenticate(r, sess, config, nil)\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassertx.EqualAsJSON(t, expected, sess)\n\t\t\t})\n\n\t\t\tt.Run(\"case=request fails because we requested a scope which the upstream does not validate\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-b\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\tsess := new(AuthenticationSession)\n\n\t\t\t\tdidNotUseCache.Add(1)\n\t\t\t\terr = a.Authenticate(r, sess, config, nil)\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\trequire.Error(t, err)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"case=does not use cache for refresh tokens\", func(t *testing.T) {\n\t\t\tfor _, strategy := range []string{\"wildcard\", \"none\"} {\n\t\t\t\tt.Run(\"scope_strategy=\"+strategy, func(t *testing.T) {\n\t\t\t\t\tviper.Set(\"authenticators.oauth2_introspection.config.scope_strategy\", strategy)\n\t\t\t\t\tr := &http.Request{Header: http.Header{\"Authorization\": {\"bearer refresh_token\"}}}\n\t\t\t\t\texpected := new(AuthenticationSession)\n\n\t\t\t\t\t// The initial request\n\t\t\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\n\t\t\t\t\t// Also doesn't use the cache the second time\n\t\t\t\t\tdidNotUseCache.Add(2)\n\t\t\t\t\trequire.Error(t, a.Authenticate(r, expected, config, nil))\n\t\t\t\t\trequire.Error(t, a.Authenticate(r, expected, config, nil))\n\t\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"case=with a scope scope strategy\", func(t *testing.T) {\n\t\t\tviper.Set(\"authenticators.oauth2_introspection.config.scope_strategy\", \"wildcard\")\n\t\t\tr := &http.Request{Header: http.Header{\"Authorization\": {\"bearer another-active-scope-a\"}}}\n\t\t\texpected := new(AuthenticationSession)\n\n\t\t\t// The initial request\n\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\n\t\t\tdidNotUseCache.Add(1)\n\t\t\trequire.NoError(t, a.Authenticate(r, expected, config, nil))\n\t\t\tdidNotUseCache.Wait()\n\n\t\t\tt.Run(\"case=request succeeds and uses the cache\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\tsess := new(AuthenticationSession)\n\n\t\t\t\terr = a.Authenticate(r, sess, config, nil)\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassertx.EqualAsJSON(t, expected, sess)\n\t\t\t})\n\n\t\t\tt.Run(\"case=request the initial request which also passes\", func(t *testing.T) {\n\t\t\t\tconfig := setup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\tsess := new(AuthenticationSession)\n\n\t\t\t\terr = a.Authenticate(r, sess, config, nil)\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassertx.EqualAsJSON(t, expected, sess)\n\t\t\t})\n\n\t\t\tt.Run(\"case=requests a scope the token does not have\", func(t *testing.T) {\n\t\t\t\trequire.Error(t, a.Authenticate(r, new(AuthenticationSession),\n\t\t\t\t\tsetup(t, `{ \"required_scope\": [\"scope-b\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`),\n\t\t\t\t\tnil))\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t})\n\n\t\t\tt.Run(\"case=requests an audience which the token does not have\", func(t *testing.T) {\n\t\t\t\trequire.Error(t, a.Authenticate(r, new(AuthenticationSession),\n\t\t\t\t\tsetup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"not-audience\"] }`),\n\t\t\t\t\tnil))\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t})\n\n\t\t\tt.Run(\"case=does not trust the issuer\", func(t *testing.T) {\n\t\t\t\trequire.Error(t, a.Authenticate(r, new(AuthenticationSession),\n\t\t\t\t\tsetup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"not-foo\", \"bar\"], \"target_audience\": [\"audience\"] }`),\n\t\t\t\t\tnil))\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t})\n\n\t\t\tt.Run(\"case=respects the expiry time\", func(t *testing.T) {\n\t\t\t\tsetup(t, `{ \"required_scope\": [\"scope-a\"], \"trusted_issuers\": [\"foo\", \"bar\"], \"target_audience\": [\"audience\"] }`)\n\t\t\t\trequire.NoError(t, a.Authenticate(r, new(AuthenticationSession), config, nil))\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\trequire.Error(t, a.Authenticate(r, new(AuthenticationSession), config, nil))\n\t\t\t\tdidNotUseCache.Wait()\n\t\t\t})\n\t\t})\n\t})\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2016-1000232
|
JavaScript
|
{
"vulnerable_code": "// Used for checking whether or not there is a trailing semi-colon\nvar TRAILING_SEMICOLON = /;+$/;\n\n // S4.1.1 Trailing semi-colons are not part of the specification.\n var semiColonCheck = TRAILING_SEMICOLON.exec(str);\n if (semiColonCheck) {\n str = str.slice(0, semiColonCheck.index);\n }\n\n var unparsed = str.slice(firstSemi).replace(/^\\s*;\\s*/,'').trim();\n var cookie_avs = unparsed.split(/\\s*;\\s*/);\n var av = cookie_avs.shift();"
}
|
{
"secure_code": " var unparsed = str.slice(firstSemi + 1).trim();\n var cookie_avs = unparsed.split(';');\n var av = cookie_avs.shift().trim();\n if (av.length === 0) { // happens if \";;\" appears\n continue;\n }\n },\n \"way too many semicolons followed by non-semicolon\": {\n topic: function() {\n // takes abnormally long due to semi-catastrophic regexp backtracking\n var str = 'foo=bar' + (';'.repeat(65535)) + ' domain=example.com';\n return Cookie.parse(str) || null;\n },\n \"parsed\": function(c) { assert.ok(c) },\n \"key\": function(c) { assert.equal(c.key, 'foo') },\n \"value\": function(c) { assert.equal(c.value, 'bar') },\n \"no path\": function(c) { assert.equal(c.path, null) },\n \"no domain\": function(c) { assert.equal(c.domain, 'example.com') },\n \"no extensions\": function(c) { assert.ok(!c.extensions) }"
}
|
{
"source": "CVEFixes"
}
|
CVE-2018-20954
|
Python
|
{
"vulnerable_code": " 'crypto/gpg/keylist/secret', '<address>')\n res = self._gnupg().list_secret_keys()\n {%- set pgp_keys = mailpile('crypto/gpg/keylist/secret').result %}"
}
|
{
"secure_code": " # *** FIXME JackDca 2018-09-21 - Above behaviour not seen in 2.1.18 if\n # --with-colons is used (but true for human-readable output) so this\n # code could be deleted.\n 'crypto/gpg/keylist/secret', '[<check>]')\n HTTP_QUERY_VARS = {'check': 'True to omit disabled, expired, revoked keys'}\n args = list(self.args)\n if len(args) > 0:\n check = args[0]\n else:\n check = self.data.get('check', '')\n check = 'True' in check\n \n all = self._gnupg().list_secret_keys()\n if check:\n res = {fprint : all[fprint] for fprint in all\n if not (all[fprint]['revoked'] or all[fprint]['disabled'])}\n else:\n res = all\n {%- set pgp_keys = mailpile('crypto/gpg/keylist/secret','True').result %}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2020-28941
|
C
|
{
"vulnerable_code": "\tif (!ldisc_data)"
}
|
{
"secure_code": "\n\tmutex_lock(&speakup_tty_mutex);\n\tif (speakup_tty) {\n\t\tmutex_unlock(&speakup_tty_mutex);\n\t\treturn -EBUSY;\n\t}\n\tif (!ldisc_data) {\n\t\tspeakup_tty = NULL;\n\t\tmutex_unlock(&speakup_tty_mutex);\n\t}\n\tmutex_unlock(&speakup_tty_mutex);"
}
|
{
"source": "CVEFixes"
}
|
CVE-2018-13305
|
C
|
{
"vulnerable_code": " if (!mquant || mquant > 31) { \\"
}
|
{
"secure_code": " if (!mquant || mquant > 31 || mquant < -31) { \\"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-23648
|
PHP
|
{
"vulnerable_code": " public function lostpasswordAction(Request $request, CsrfProtectionHandler $csrfProtection, Config $config, RateLimiterFactory $resetPasswordLimiter): Response\n $loginUrl = $this->generateUrl('pimcore_admin_login_check', [\n 'token' => $token,\n 'reset' => 'true',\n ], UrlGeneratorInterface::ABSOLUTE_URL);\n"
}
|
{
"secure_code": "use Pimcore\\SystemSettingsConfig;\nuse Symfony\\Component\\Routing\\RouterInterface;\n public function lostpasswordAction(\n Request $request,\n CsrfProtectionHandler $csrfProtection,\n Config $config,\n RateLimiterFactory $resetPasswordLimiter,\n RouterInterface $router\n ): Response\n $domain = SystemSettingsConfig::get()['general']['domain'];\n if (!$domain) {\n throw new \\Exception('No main domain set in system settings, unable to generate reset password link');\n }\n\n $context = $router->getContext();\n $context->setHost($domain);\n\n $loginUrl = $this->generateUrl('pimcore_admin_login_check', [\n 'token' => $token,\n 'reset' => 'true',\n ], UrlGeneratorInterface::ABSOLUTE_URL);\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-46229
|
Python
|
{
"vulnerable_code": " \"\"\"Load all child links from a URL page.\"\"\"\n prevent_outside: Optional[bool] = True,"
}
|
{
"secure_code": " \"\"\"Load all child links from a URL page.\n\n **Security Note**: This loader is a crawler that will start crawling\n at a given URL and then expand to crawl child links recursively.\n\n Web crawlers should generally NOT be deployed with network access\n to any internal servers.\n\n Control access to who can submit crawling requests and what network access\n the crawler has.\n\n While crawling, the crawler may encounter malicious URLs that would lead to a\n server-side request forgery (SSRF) attack.\n\n To mitigate risks, the crawler by default will only load URLs from the same\n domain as the start URL (controlled via prevent_outside named argument).\n\n This will mitigate the risk of SSRF attacks, but will not eliminate it.\n\n For example, if crawling a host which hosts several sites:\n\n https://some_host/alice_site/\n https://some_host/bob_site/\n\n A malicious URL on Alice's site could cause the crawler to make a malicious\n GET request to an endpoint on Bob's site. Both sites are hosted on the\n same host, so such a request would not be prevented by default.\n\n See https://python.langchain.com/docs/security\n \"\"\"\n prevent_outside: bool = True,\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2013-3301
|
C
|
{
"vulnerable_code": "loff_t ftrace_regex_lseek(struct file *file, loff_t offset, int whence);\nftrace_regex_lseek(struct file *file, loff_t offset, int whence)\n\t.llseek = ftrace_regex_lseek,\n\t.llseek = ftrace_regex_lseek,\n\t.llseek\t\t= seq_lseek,\n\t.llseek\t\t= seq_lseek,\n\t.llseek = ftrace_regex_lseek,"
}
|
{
"secure_code": "loff_t ftrace_filter_lseek(struct file *file, loff_t offset, int whence);\nftrace_filter_lseek(struct file *file, loff_t offset, int whence)\n\t.llseek = ftrace_filter_lseek,\n\t.llseek = ftrace_filter_lseek,\n\t.llseek\t\t= ftrace_filter_lseek,\n\t.llseek\t\t= ftrace_filter_lseek,\n\t.llseek = ftrace_filter_lseek,"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-22111
|
PHP
|
{
"vulnerable_code": " $user->roles()->sync([$request->roles]);\n"
}
|
{
"secure_code": " if (!auth()->user()->can('absence-view')) {\n session()->flash('flash_message_warning', __('You do not have permission to view this page'));\n return redirect()->back();\n }\n\n if( !auth()->user()->canChangePasswordOn($user) ) {\n unset($request['password']);\n }\n\n\n if(auth()->user()->canChangeRole() ) {\n $user->roles()->sync([$request->roles]);\n }\n public function canChangePasswordOn(User $user)\n {\n if($this->id === $user->id || ( $this->roles->first()->name == Role::OWNER_ROLE || $this->roles->first()->name == Role::ADMIN_ROLE)) {\n return true;\n }\n\n return false;\n }\n\n public function canChangeRole()\n {\n return $this->roles->first()->name == Role::OWNER_ROLE || $this->roles->first()->name == Role::ADMIN_ROLE;\n }\n@if(isset($user) && auth()->user()->canChangePasswordOn($user))\n\n@endif\n@if(isset($user) && auth()->user()->canChangeRole())\n@endif"
}
|
{
"source": "CVEFixes"
}
|
CVE-2020-8981
|
PHP
|
{
"vulnerable_code": "helper_ensure_confirmed( sprintf( plugin_lang_get( 'ensure_delete' ), $t_repo->name ), plugin_lang_get( 'delete_repository' ) );"
}
|
{
"secure_code": "$t_message = sprintf( plugin_lang_get( 'ensure_delete' ), string_attribute( $t_repo->name ) );\nhelper_ensure_confirmed( $t_message, plugin_lang_get( 'delete_repository' ) );"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-41913
|
Ruby
|
{
"vulnerable_code": " let(:user) { Fabricate(:user, admin: true) }\n let(:topic) { Fabricate(:topic, user: user) }\n let(:post1) { Fabricate(:post, user: user, topic: topic) }\n let(:invitee1) { Fabricate(:user) }\n let(:invitee2) { Fabricate(:user) }\n"
}
|
{
"secure_code": " invalid_allowed_groups: \"Invalid allowed groups.\"\n acting_user_not_allowed_to_invite_these_groups: \"Current user is not allowed to invite these groups.\"\n invitees = filter_out_unavailable_groups(invitees)\n\n\n def invitee_groups(invitees)\n Group.where(name: invitees.map { |i| i[:identifier] })\n end\n\n def filter_out_unavailable_groups(invitees)\n groups = invitee_groups(invitees)\n invitees.filter do |i|\n group = groups.find { |g| g.name === i[:identifier] }\n\n !group || (@guardian.can_see_group?(group) && @guardian.can_see_group_members?(group))\n end\n end\n return false unless can_invite_groups?(extracted_event)\n\n\n private\n\n def can_invite_groups?(event)\n guardian = Guardian.new(@post.acting_user)\n return true unless event[:\"allowed-groups\"]\n\n event[:\"allowed-groups\"].split(',').each do |group_name|\n group = Group.find_by(name: group_name)\n\n if !group || !guardian.can_see_group?(group)\n @post.errors.add(:base, I18n.t(\"discourse_post_event.errors.models.event.invalid_allowed_groups\"))\n return false\n end\n\n if !guardian.can_see_group_members?(group)\n @post.errors.add(:base, I18n.t(\"discourse_post_event.errors.models.event.acting_user_not_allowed_to_invite_these_groups\"))\n return false\n end\n end\n\n true\n end\n Fabricate(:group, name: \"euro\")\n Fabricate(:group, name: \"america\")\n\n\n it \"rejects private groups in allowedGroups\" do\n moderator = Fabricate(:user, moderator: true)\n private_group = Fabricate(\n :group,\n visibility_level: Group.visibility_levels[:owners])\n\n expect {\n create_post_with_event(moderator, \"allowedGroups='#{private_group.name}'\")\n }.to raise_error(ActiveRecord::RecordNotSaved)\n end\n\n it \"rejects non-existent groups in allowedGroups\" do\n moderator = Fabricate(:user, moderator: true)\n\n expect {\n create_post_with_event(moderator, \"allowedGroups='non-existent_group_name'\")\n }.to raise_error(ActiveRecord::RecordNotSaved)\n end\n\n it \"rejects public groups with private members in allowedGroups\" do\n moderator = Fabricate(:user, moderator: true)\n public_group_with_private_members = Fabricate(\n :group,\n visibility_level: Group.visibility_levels[:public],\n members_visibility_level: Group.visibility_levels[:owners])\n\n expect {\n create_post_with_event(moderator, \"allowedGroups='#{public_group_with_private_members.name}'\")\n }.to raise_error(ActiveRecord::RecordNotSaved)\n end\n let(:user) { Fabricate(:user, admin: true) }\n let(:topic) { Fabricate(:topic, user: user) }\n let(:post1) { Fabricate(:post, user: user, topic: topic) }\n let(:invitee1) { Fabricate(:user) }\n let(:invitee2) { Fabricate(:user) }\n\n\n context 'with a private event' do\n let(:moderator) { Fabricate(:user, moderator: true) }\n let(:topic) { Fabricate(:topic, user: moderator) }\n let(:first_post) { Fabricate(:post, user: moderator, topic: topic) }\n let(:private_event) { Fabricate(:event, post: first_post, status: Event.statuses[:private]) }\n\n before do\n sign_in(moderator)\n end\n\n context 'when bulk inviting via CSV file' do\n def csv_file(content)\n file = Tempfile.new(\"invites.csv\")\n file.write(content)\n file.rewind\n file\n end\n\n it \"doesn't invite a private group\" do\n private_group = Fabricate(:group, visibility_level: Group.visibility_levels[:owners])\n\n file = csv_file(\"#{private_group.name},going\\n\")\n params = { file: fixture_file_upload(file) }\n post \"/discourse-post-event/events/#{private_event.id}/csv-bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n private_event.reload\n expect(private_event.raw_invitees).to be_nil\n end\n\n it \"returns 200 when inviting a non-existent group\" do\n file = csv_file(\"non-existent group name,going\\n\")\n params = { file: fixture_file_upload(file) }\n post \"/discourse-post-event/events/#{private_event.id}/csv-bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n end\n\n it \"doesn't invite a public group with private members\" do\n public_group_with_private_members = Fabricate(\n :group,\n visibility_level: Group.visibility_levels[:public],\n members_visibility_level: Group.visibility_levels[:owners])\n\n file = csv_file(\"#{public_group_with_private_members.name},going\\n\")\n params = { file: fixture_file_upload(file) }\n post \"/discourse-post-event/events/#{private_event.id}/csv-bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n private_event.reload\n expect(private_event.raw_invitees).to be_nil\n end\n end\n\n context 'when doing bulk inviting via UI' do\n it \"doesn't invite a private group\" do\n private_group = Fabricate(:group, visibility_level: Group.visibility_levels[:owners])\n\n params = { invitees: [\n { 'identifier' => private_group.name, 'attendance' => 'going' }\n ] }\n post \"/discourse-post-event/events/#{private_event.id}/bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n private_event.reload\n expect(private_event.raw_invitees).to be_nil\n end\n\n it \"returns 200 when inviting a non-existent group\" do\n params = { invitees: [\n { 'identifier' => 'non-existent group name', 'attendance' => 'going' }\n ] }\n post \"/discourse-post-event/events/#{private_event.id}/bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n end\n\n it \"doesn't invite a public group with private members\" do\n public_group_with_private_members = Fabricate(\n :group,\n visibility_level: Group.visibility_levels[:public],\n members_visibility_level: Group.visibility_levels[:owners])\n\n params = { invitees: [\n { 'identifier' => public_group_with_private_members.name, 'attendance' => 'going' }\n ] }\n post \"/discourse-post-event/events/#{private_event.id}/bulk-invite.json\", { params: params }\n\n expect(response.status).to eq(200)\n private_event.reload\n expect(private_event.raw_invitees).to be_nil\n end\n end\n end"
}
|
{
"source": "CVEFixes"
}
|
CVE-2021-3729
|
PHP
|
{
"vulnerable_code": " protected UserRepositoryInterface $userRepository;\n app('view')->share('title', (string) trans('firefly.currencies'));\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $subTitle = (string) trans('firefly.create_currency');\n public function defaultCurrency(Request $request, TransactionCurrency $currency)\n app('preferences')->set('currencyPreference', $currency->code);\n app('preferences')->mark();\n\n Log::channel('audit')->info(sprintf('Make %s the default currency.', $currency->code));\n\n $this->repository->enable($currency);\n $request->session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name]));\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $message = (string) trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);\n $subTitle = (string) trans('form.delete_currency', ['name' => $currency->name]);\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $request->session()->flash('error', (string) trans('firefly.cannot_delete_currency', ['name' => e($currency->name)]));\n $request->session()->flash('error', (string) trans('firefly.cannot_delete_fallback_currency', ['name' => e($currency->name)]));\n $request->session()->flash('success', (string) trans('firefly.deleted_currency', ['name' => $currency->name]));\n * @throws FireflyException\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $message = (string) trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);\n session()->flash('warning', (string) trans('firefly.disable_EUR_side_effects'));\n session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]);\n 'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $currency->enabled,\n session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));\n $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');\n $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;\n $request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')]));\n $request->session()->flash('error', (string) trans('firefly.could_not_store_currency'));\n $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name]));\n if (1 === (int) $request->get('create_another')) {\n $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $request->session()->flash('success', (string) trans('firefly.updated_currency', ['name' => $currency->name]));\n if (1 === (int) $request->get('return_to_edit')) {\n <a class=\"btn btn-success pull-right\" href=\"{{ route('currencies.create') }}\">{{ 'create_currency'|_ }}</a>\n <a class=\"btn btn-default\" href=\"{{ route('currencies.edit',currency.id) }}\"><span class=\"fa fa-fw fa-pencil\"></span></a>\n <a class=\"btn btn-danger\" href=\"{{ route('currencies.delete',currency.id) }}\"><span class=\"fa fa-fw fa-trash\"></span></a>\n <span class=\"text-muted\">\n {{ currency.name }} ({{ currency.code }}) ({{ currency.symbol|raw }})\n <span class=\"label label-success\" id=\"default-currency\">{{ 'default_currency'|_ }}</span>\n {% if currency.enabled == false %}\n <br><small class=\"text-danger\">{{ 'currency_is_disabled'|_ }}</small>\n {% if currency.id != defaultCurrency.id %}\n <a class=\"btn btn-default\"\n href=\"{{ route('currencies.default',currency.id) }}\">\n <span class=\"fa fa-fw fa-star\"></span>\n {{ 'make_default_currency'|_ }}</a>\n {% endif %}\n {% if currency.enabled %}\n <a class=\"btn btn-default\"\n href=\"{{ route('currencies.disable',currency.id) }}\">\n <span class=\"fa fa-fw fa-square-o\"></span>\n {{ 'disable_currency'|_ }}</a>\n {% endif %}\n {% if not currency.enabled %}\n <a class=\"btn btn-default\"\n href=\"{{ route('currencies.enable',currency.id) }}\">\n <span class=\"fa fa-fw fa-check-square-o\"></span>\n {{ 'enable_currency'|_ }}</a>\n {% endif %}\n Route::get('default/{currency}', ['uses' => 'CurrencyController@defaultCurrency', 'as' => 'default']);"
}
|
{
"secure_code": "\n protected UserRepositoryInterface $userRepository;\n app('view')->share('title', (string)trans('firefly.currencies'));\n\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $subTitle = (string)trans('firefly.create_currency');\n public function defaultCurrency(Request $request)\n $currencyId = (int)$request->get('id');\n if ($currencyId > 0) {\n // valid currency?\n $currency = $this->repository->find($currencyId);\n if (null !== $currency) {\n app('preferences')->set('currencyPreference', $currency->code);\n app('preferences')->mark();\n Log::channel('audit')->info(sprintf('Make %s the default currency.', $currency->code));\n\n $this->repository->enable($currency);\n $request->session()->flash('success', (string)trans('firefly.new_default_currency', ['name' => $currency->name]));\n\n return redirect(route('currencies.index'));\n }\n }\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $message = (string)trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);\n $subTitle = (string)trans('form.delete_currency', ['name' => $currency->name]);\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $request->session()->flash('error', (string)trans('firefly.cannot_delete_currency', ['name' => e($currency->name)]));\n $request->session()->flash('error', (string)trans('firefly.cannot_delete_fallback_currency', ['name' => e($currency->name)]));\n $request->session()->flash('success', (string)trans('firefly.deleted_currency', ['name' => $currency->name]));\n * @throws FireflyException\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $message = (string)trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);\n session()->flash('warning', (string)trans('firefly.disable_EUR_side_effects'));\n session()->flash('success', (string)trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $subTitle = (string)trans('breadcrumbs.edit_currency', ['name' => $currency->name]);\n 'enabled' => $hasOldInput ? (bool)$request->old('enabled') : $currency->enabled,\n session()->flash('success', (string)trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));\n $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');\n $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;\n $request->session()->flash('info', (string)trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')]));\n\n $request->session()->flash('error', (string)trans('firefly.could_not_store_currency'));\n $request->session()->flash('success', (string)trans('firefly.created_currency', ['name' => $currency->name]));\n if (1 === (int)$request->get('create_another')) {\n\n $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));\n $request->session()->flash('success', (string)trans('firefly.updated_currency', ['name' => $currency->name]));\n if (1 === (int)$request->get('return_to_edit')) {\n/*\n * index.js\n * Copyright (c) 2019 james@firefly-iii.org\n *\n * This file is part of Firefly III (https://github.com/firefly-iii).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\n/**\n *\n */\n$(function () {\n \"use strict\";\n $('.make_default').on('click', setDefaultCurrency);\n\n});\n\nfunction setDefaultCurrency(e) {\n var button = $(e.currentTarget);\n var currencyId = parseInt(button.data('id'));\n\n $.post(makeDefaultUrl, {\n _token: token,\n id: currencyId\n }).done(function (data) {\n // lame but it works\n location.reload();\n }).fail(function () {\n console.error('I failed :(');\n });\n}\n <a class=\"btn btn-success pull-right\" href=\"{{ route('currencies.create') }}\">{{ 'create_currency'|_ }}</a>\n <a class=\"btn btn-default\" href=\"{{ route('currencies.edit',currency.id) }}\"><span\n class=\"fa fa-fw fa-pencil\"></span></a>\n <a class=\"btn btn-danger\" href=\"{{ route('currencies.delete',currency.id) }}\"><span\n class=\"fa fa-fw fa-trash\"></span></a>\n <span class=\"text-muted\">\n {{ currency.name }} ({{ currency.code }}) ({{ currency.symbol|raw }})\n <span class=\"label label-success\" id=\"default-currency\">{{ 'default_currency'|_ }}</span>\n {% if currency.enabled == false %}\n <br><small class=\"text-danger\">{{ 'currency_is_disabled'|_ }}</small>\n {% if currency.id != defaultCurrency.id %}\n <button data-id=\"{{ currency.id }}\" class=\"make_default btn btn-default\"><span\n class=\"fa fa-fw fa-star\"></span> {{ 'make_default_currency'|_ }}</button>\n {% endif %}\n {% if currency.enabled %}\n <a class=\"btn btn-default\"\n href=\"{{ route('currencies.disable',currency.id) }}\">\n <span class=\"fa fa-fw fa-square-o\"></span>\n {{ 'disable_currency'|_ }}</a>\n {% endif %}\n {% if not currency.enabled %}\n <a class=\"btn btn-default\"\n href=\"{{ route('currencies.enable',currency.id) }}\">\n <span class=\"fa fa-fw fa-check-square-o\"></span>\n {{ 'enable_currency'|_ }}</a>\n {% endif %}\n{% block scripts %}\n <script type=\"text/javascript\" nonce=\"{{ JS_NONCE }}\">\n var makeDefaultUrl = \"{{ route('currencies.default') }}\";\n </script>\n <script type=\"text/javascript\" src=\"v1/js/ff/currencies/index.js?v={{ FF_VERSION }}\" nonce=\"{{ JS_NONCE }}\"></script>\n{% endblock %}\n Route::post('default', ['uses' => 'CurrencyController@defaultCurrency', 'as' => 'default']);"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-30470
|
JavaScript
|
{
"vulnerable_code": "// CHECK:function foo#1#2(p1 : number)#3 : string"
}
|
{
"secure_code": " // Non-strict functions can be aliased in multiple ways (\n // arguments.callee, Function.prototype.caller etc). Do not try to identify\n // the callsites for those.\n if (!F->isStrictMode()) {\n return false;\n }\n\n// CHECK:function foo#1#2(p1)#3 : string\n/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n// RUN: %hermes %s\n\nvar f;\nvar funcp;\nvar argumentsp;\nvar callee = _ => \"callee\";\n\nfunction calleeDirectly(a) {\n return a.callee;\n}\n\nfunction calleeIndirectly(a) {\n return a[callee()];\n}\n\nprint(\"directArgumentsCallee\");\n(function directArgumentsCallee(param) {\n try {\n funcp = arguments.callee;\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"indirectArgumentsCallee\");\n(function indirectArgumentsCallee(param) {\n try {\n funcp = arguments.callee;\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"passignArgumentsToAnotherFunction_directArgumentsCallee\");\n(function passignArgumentsToAnotherFunction_DirectArgumentsCallee(param) {\n try {\n funcp = calleeDirectly(arguments);\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"passignArgumentsToAnotherFunction_indirectArgumentsCallee\");\n(function passignArgumentsToAnotherFunction_indirectArgumentsCallee(param) {\n try {\n funcp = calleeIndirectly(arguments);\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"arrow_directArgumentsCallee\");\n(function arrow_directArgumentsCallee(param) {\n try {\n funcp = (_ => arguments.callee)();\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"arrow_indirectArgumentsCallee\");\n(function arrow_indirectArgumentsCallee(param) {\n try {\n funcp = (_ => arguments[callee()])();\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = funcp({ a: 1.1 });\nf();\n\nprint(\"capture_directArgumentsCallee\");\n(function capture_directArgumentsCallee(param) {\n try {\n argumentsp = arguments;\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = argumentsp.callee({ a: 1.1 });\nf();\n\nprint(\"capture_indirectArgumentsCallee\");\n(function capture_indirectArgumentsCallee(param) {\n try {\n argumentsp = arguments;\n } catch (e) {\n }\n let f = () => {\n return param;\n };\n return f;\n})();\nf = argumentsp[callee()]({ a: 1.1 });\nf();"
}
|
{
"source": "CVEFixes"
}
|
CVE-2016-10270
|
C
|
{
"vulnerable_code": "\tuint64 nstrips64;\n\tuint32 nstrips32;\n\t * never increase the number of strips in an image\n\tnstrips64 = TIFFhowmany_64(bytecount, stripbytes);\n\tif ((nstrips64==0)||(nstrips64>0xFFFFFFFF)) /* something is wonky, do nothing. */\n\t return;\n\tnstrips32 = (uint32)nstrips64;\n\tnewcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64),\n\tnewoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64),\n\tfor (strip = 0; strip < nstrips32; strip++) {\n\t\tnewoffsets[strip] = offset;\n\ttd->td_stripsperimage = td->td_nstrips = nstrips32;\n /* If the value was already computed and store in td_nstrips, then return it,\n since ChopUpSingleUncompressedStrip might have altered and resized the\n since the td_stripbytecount and td_stripoffset arrays to the new value\n after the initial affectation of td_nstrips = TIFFNumberOfStrips() in\n tif_dirread.c ~line 3612.\n See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */\n if( td->td_nstrips )\n return td->td_nstrips;\n"
}
|
{
"secure_code": "2016-12-03 Even Rouault <even.rouault at spatialys.com>\n\n\t* libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to\n\tinstanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip),\n\tinstead of a logic based on the total size of data. Which is faulty is\n\tthe total size of data is not sufficient to fill the whole image, and thus\n\tresults in reading outside of the StripByCounts/StripOffsets arrays when\n\tusing TIFFReadScanline().\n\tReported by Agostino Sarubbo.\n\tFixes http://bugzilla.maptools.org/show_bug.cgi?id=2608.\n\n\t* libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done\n\tfor http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since\n\tthe above change is a better fix that makes it unnecessary.\n\n\tuint32 nstrips;\n\t * never increase the number of rows per strip\n nstrips = TIFFhowmany_32(td->td_imagelength, rowsperstrip);\n if( nstrips == 0 )\n return;\n\tnewcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),\n\tnewoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),\n\tfor (strip = 0; strip < nstrips; strip++) {\n\t\tnewoffsets[strip] = stripbytes ? offset : 0;\n\ttd->td_stripsperimage = td->td_nstrips = nstrips;"
}
|
{
"source": "CVEFixes"
}
|
CVE-2017-5553
|
PHP
|
{
"vulnerable_code": "\t\tif (preg_match_all('/^[ ]{0,3}\\[(.+)\\][ ]?:[ ]*\\n?[ ]*(.+)$/m', $text, $matches, PREG_SET_ORDER))\n\t\t\t\tif( preg_match_all( '/(!?)(\\[((?:[^][]+|(?2))*)\\])\\(([^\"]*?)( \"([^\"]+)\")?\\)/', $text, $matches, PREG_SET_ORDER ) )\n\t\t\t\t\t\t\t\t$element = '<img src=\"'.$matches[4].'\" alt=\"'.$matches[3].'\"'.( ! empty( $matches[6] ) ? ' title=\"'.$matches[6].'\"' : '' ).'>';\n\t\t\t\t\t\t\t\t$element = '<a href=\"'.$matches[4].'\"'.( ! empty( $matches[6] ) ? ' title=\"'.$matches[6].'\"' : '' ).'>'.$element_text.'</a>';"
}
|
{
"secure_code": "\t12. Ignore wrong URLs for links and images; Allow only which begin with http://, https:// or /\n\t\tif (preg_match_all('/^[ ]{0,3}\\[(.+)\\][ ]?:[ ]*\\n?[ ]*((https?:\\/\\/|\\/).+)$/m', $text, $matches, PREG_SET_ORDER))\n\t\t\t\tif( preg_match_all( '/(!?)(\\[((?:[^][]+|(?2))*)\\])\\((https?:\\/\\/|\\/)([^\"]*?)( \"([^\"]+)\")?\\)/', $text, $matches, PREG_SET_ORDER ) )\n\t\t\t\t\t\t\t\t$element = '<img src=\"'.$matches[4].$matches[5].'\" alt=\"'.$matches[3].'\"'.( ! empty( $matches[7] ) ? ' title=\"'.$matches[7].'\"' : '' ).'>';\n\t\t\t\t\t\t\t\t$element = '<a href=\"'.$matches[4].$matches[5].'\"'.( ! empty( $matches[7] ) ? ' title=\"'.$matches[7].'\"' : '' ).'>'.$element_text.'</a>';"
}
|
{
"source": "CVEFixes"
}
|
CVE-2020-26245
|
JavaScript
|
{
"vulnerable_code": " <div class=\"version\">Current Version: <span id=\"version\">4.30.4</span></div>\n// Object.freeze(String.prototype);\n// Object.freeze(Object.prototype);\n\n\n const ifaceSanitized = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);\n let srvString = util.sanitizeShellString(srv);"
}
|
{
"secure_code": "| 4.30.5 | 2020-11-26 | adapted security update (prototype pollution prevention) |\n <tr>\n <th scope=\"row\">4.30.5</th>\n <td>2020-11-26</td>\n <td>adapted security update (prototype pollution prevention)</td>\n </tr>\n <div class=\"version\">Current Version: <span id=\"version\">4.30.5</span></div>\n s[i].__proto__.toLowerCase = util.stringToLower;\n let ifaceSanitized = '';\n const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);\n for (let i = 0; i <= 2000; i++) {\n if (!(s[i] === undefined)) {\n ifaceSanitized = ifaceSanitized + s[i];\n }\n }\n let srvString = '';\n srvString.__proto__.toLowerCase = util.stringToLower;\n srvString.__proto__.replace = util.stringReplace;\n srvString.__proto__.trim = util.stringTrim;\n\n const s = util.sanitizeShellString(srv);\n for (let i = 0; i <= 2000; i++) {\n if (!(s[i] === undefined)) {\n srvString = srvString + s[i];\n }\n }\n\n\nconst stringReplace = new String().replace;\nconst stringToLower = new String().toLowerCase;\nconst stringToString = new String().toString;\nconst stringSubstr = new String().substr;\nconst stringTrim = new String().trim;\n\n\n st.__proto__.replace = stringReplace;\n st.__proto__.toLowerCase = stringToLower;\n st.__proto__.toString = stringToString;\n st.__proto__.substr = stringSubstr;\n\n stm.__proto__.replace = stringReplace;\n s1.__proto__.toLowerCase = stringToLower;\nexports.stringReplace = stringReplace;\nexports.stringToLower = stringToLower;\nexports.stringToString = stringToString;\nexports.stringSubstr = stringSubstr;\nexports.stringTrim = stringTrim;"
}
|
{
"source": "CVEFixes"
}
|
CVE-2018-14553
|
C
|
{
"vulnerable_code": "\tif (src->styleLength > 0) {\n\t\tdst->styleLength = src->styleLength;\n\t\tdst->stylePos = src->stylePos;\n\t\tfor (i = 0; i < src->styleLength; i++) {\n\t\t\tdst->style[i] = src->style[i];\n\t\t}\n\t}\n\n\tgdimageclone/bug00300"
}
|
{
"secure_code": "\t\tdst->stylePos = src->stylePos;\n/style\n\tstyle\n\tgdimageclone/bug00300 \\\n\tgdimageclone/style\n/**\n * Cloning an image should exactly reproduce all style related data\n */\n\n\n#include <string.h>\n#include \"gd.h\"\n#include \"gdtest.h\"\n\n\nint main()\n{\n gdImagePtr im, clone;\n int style[] = {0, 0, 0};\n\n im = gdImageCreate(8, 8);\n gdImageSetStyle(im, style, sizeof(style)/sizeof(style[0]));\n\n clone = gdImageClone(im);\n gdTestAssert(clone != NULL);\n\n gdTestAssert(clone->styleLength == im->styleLength);\n gdTestAssert(clone->stylePos == im->stylePos);\n gdTestAssert(!memcmp(clone->style, im->style, sizeof(style)/sizeof(style[0])));\n\n gdImageDestroy(clone);\n gdImageDestroy(im);\n\n return gdNumFailures();\n}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-36405
|
C
|
{
"vulnerable_code": " - **Source**: https://github.com/pq-crystals/kyber/commit/b628ba78711bc28327dc7d2d5c074a00f061884e with copy_from_upstream patches\n- **Optimized Implementation sources**: https://github.com/pq-crystals/kyber/commit/b628ba78711bc28327dc7d2d5c074a00f061884e with copy_from_upstream patches\n source: https://github.com/pq-crystals/kyber/commit/b628ba78711bc28327dc7d2d5c074a00f061884e\n - **Source**: https://github.com/pq-crystals/kyber/commit/11d00ff1f20cfca1f72d819e5a45165c1e0a2816 with copy_from_upstream patches\n source: https://github.com/pq-crystals/kyber/commit/11d00ff1f20cfca1f72d819e5a45165c1e0a2816\n git_commit: b628ba78711bc28327dc7d2d5c074a00f061884e\n git_commit: 11d00ff1f20cfca1f72d819e5a45165c1e0a2816\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);\n int16_t mask;\n mask = -(int16_t)((msg[i] >> j)&1);\n r->coeffs[8*i+j] = mask & ((KYBER_Q+1)/2);"
}
|
{
"secure_code": " - **Source**: https://github.com/pq-crystals/kyber/commit/441c0519a07e8b86c8d079954a6b10bd31d29efc with copy_from_upstream patches\n- **Optimized Implementation sources**: https://github.com/pq-crystals/kyber/commit/441c0519a07e8b86c8d079954a6b10bd31d29efc with copy_from_upstream patches\n source: https://github.com/pq-crystals/kyber/commit/441c0519a07e8b86c8d079954a6b10bd31d29efc\n - **Source**: https://github.com/pq-crystals/kyber/commit/d1321ce5ac0b53f583eb47a040dc3625ee8e7e37 with copy_from_upstream patches\n source: https://github.com/pq-crystals/kyber/commit/d1321ce5ac0b53f583eb47a040dc3625ee8e7e37\n git_commit: 441c0519a07e8b86c8d079954a6b10bd31d29efc\n git_commit: d1321ce5ac0b53f583eb47a040dc3625ee8e7e37\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n\n#include \"verify.h\"\n r->coeffs[8*i+j] = 0;\n cmov_int16(r->coeffs+8*i+j, ((KYBER_Q+1)/2), (msg[i] >> j)&1);\n\n\n/*************************************************\n* Name: cmov_int16\n*\n* Description: Copy input v to *r if b is 1, don't modify *r if b is 0. \n* Requires b to be in {0,1};\n* Runs in constant time.\n*\n* Arguments: int16_t *r: pointer to output int16_t\n* int16_t v: input int16_t \n* uint8_t b: Condition bit; has to be in {0,1}\n**************************************************/\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b)\n{\n b = -b;\n *r ^= b & ((*r) ^ v);\n}\n#define cmov_int16 KYBER_NAMESPACE(cmov_int16)\nvoid cmov_int16(int16_t *r, int16_t v, uint16_t b);\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-35939
|
C++
|
{
"vulnerable_code": "inline void ScatterNd(const RuntimeShape& indices_shape,\n const IndicesT* indices_data,\n const RuntimeShape& updates_shape,\n const UpdatesT* updates_data,\n const RuntimeShape& output_shape, UpdatesT* output_data) {\n TFLITE_DCHECK(0 <= idx && idx < output_shape.Dims(j));\n reference_ops::ScatterNd(\n return kTfLiteOk;\n return ScatterNd<IndicesT, float>(indices, updates, output);\n return ScatterNd<IndicesT, uint8_t>(indices, updates, output);\n return ScatterNd<IndicesT, bool>(indices, updates, output);\n return ScatterNd<IndicesT, int8_t>(indices, updates, output);\n return ScatterNd<IndicesT, int32_t>(indices, updates, output);\n return ScatterNd<IndicesT, int64_t>(indices, updates, output);"
}
|
{
"secure_code": "inline TfLiteStatus ScatterNd(const RuntimeShape& indices_shape,\n const IndicesT* indices_data,\n const RuntimeShape& updates_shape,\n const UpdatesT* updates_data,\n const RuntimeShape& output_shape,\n UpdatesT* output_data) {\n if (n_slices * slice_size > updates_shape.FlatSize()) {\n return kTfLiteError;\n }\n if (to_pos < 0 || to_pos + slice_size > output_flat_size) {\n return kTfLiteError;\n }\n return kTfLiteOk;\n return reference_ops::ScatterNd(\n TfLiteStatus status = kTfLiteError;\n status = ScatterNd<IndicesT, float>(indices, updates, output);\n break;\n status = ScatterNd<IndicesT, uint8_t>(indices, updates, output);\n break;\n status = ScatterNd<IndicesT, bool>(indices, updates, output);\n break;\n status = ScatterNd<IndicesT, int8_t>(indices, updates, output);\n break;\n status = ScatterNd<IndicesT, int32_t>(indices, updates, output);\n break;\n status = ScatterNd<IndicesT, int64_t>(indices, updates, output);\n break;\n if (status != kTfLiteOk) {\n TF_LITE_KERNEL_LOG(context, \"scatter_nd index out of bounds\");\n }\n return status;\nTEST(ScatterNdOpTest, ReadAndWriteArrayLimits) {\n ScatterNdOpModel m({TensorType_INT32, {5, 1}}, {TensorType_INT32, {5}},\n {TensorType_INT32, {1}});\n m.SetIndices<int32_t>({4, 3, 1, 0, 2});\n m.SetUpdates<int32_t>({1, 2, 3, 7, 9});\n m.SetShape<int32_t>({5});\n ASSERT_EQ(m.Invoke(), kTfLiteOk);\n EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({5}));\n EXPECT_THAT(m.GetOutput<int32_t>(), ElementsAreArray({7, 3, 9, 2, 1}));\n}\n\nTEST(ScatterNdOpTest, OOBRead) {\n ScatterNdOpModel m({TensorType_INT32, {1, 1}}, {TensorType_INT32, {1}},\n {TensorType_INT32, {1}});\n m.SetIndices<int32_t>({4});\n m.SetUpdates<int32_t>({1});\n m.SetShape<int32_t>({1});\n ASSERT_EQ(m.Invoke(), kTfLiteError);\n}\n\nTEST(ScatterNdOpTest, OOBWrites) {\n ScatterNdOpModel m({TensorType_INT32, {5, 1}}, {TensorType_INT32, {5}},\n {TensorType_INT32, {1}});\n m.SetIndices<int32_t>({4, 3, 1, -0x38, 0x38});\n m.SetUpdates<int32_t>({1, 2, 3, 0x44444444, 0x55555555});\n m.SetShape<int32_t>({1});\n ASSERT_EQ(m.Invoke(), kTfLiteError);\n}\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2019-3560
|
C++
|
{
"vulnerable_code": " length +=\n sizeof(ContentType) + sizeof(ProtocolVersion) + sizeof(uint16_t);\n buf.trimStart(length);"
}
|
{
"secure_code": " buf.trimStart(static_cast<size_t>(kPlaintextHeaderSize) + length);\nTEST_F(PlaintextRecordTest, TestSkipOversizedRecord) {\n read_.setSkipEncryptedRecords(true);\n addToQueue(\"170301fffb\");\n auto longBuf = IOBuf::create(0xfffb);\n longBuf->append(0xfffb);\n queue_.append(std::move(longBuf));\n EXPECT_FALSE(read_.read(queue_).hasValue());\n EXPECT_TRUE(queue_.empty());\n}\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-24840
|
Python
|
{
"vulnerable_code": " upload_path = str(\n getattr(settings, \"S3FILE_UPLOAD_PATH\", pathlib.PurePosixPath(\"tmp\", \"s3file\"))\n upload_path = safe_join(str(storage.location), upload_path)\nfrom s3file.storages import local_dev, storage\n request.FILES.setlist(field_name, list(self.get_files_from_storage(paths)))\n def get_files_from_storage(paths):\n location = storage.aws_location\n except AttributeError:\n location = storage.location\n f = storage.open(str(path.relative_to(location)))\nimport os\ndef upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:\n return file_name\ndef another_upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"another_%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:\n return file_name\ndef yet_another_upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"yet_another_%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:\n return file_name\n @pytest.fixture\n def freeze(self, monkeypatch):\n \"\"\"Freeze datetime and UUID.\"\"\"\n monkeypatch.setattr(\n \"s3file.forms.S3FileInputMixin.upload_folder\",\n os.path.join(storage.aws_location, \"tmp\"),\n )\n\n def test_value_from_datadict(self, client, upload_file):\n print(storage.location)\n uploaded_file = storage.save(\"test.jpg\", f)\n \"file\": json.dumps([uploaded_file]),\n \"s3file\": '[\"file\"]',\n def test_build_attr(self):\n def test_get_conditions(self, freeze):\n [\"starts-with\", \"$key\", \"custom/location/tmp\"],\n def test_file_insert(self, request, driver, live_server, upload_file, freeze):\n assert storage.exists(\"tmp/%s.txt\" % request.node.name)\n def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze):\n def test_progress(self, driver, live_server, upload_file, freeze):\n freeze,\n file_input.send_keys(\" \\n \".join([upload_file, another_upload_file]))\n file_input.send_keys(yet_another_upload_file)\n def test_get_files_from_storage(self):\n [os.path.join(storage.aws_location, name)]\n def test_process_request(self, rf):\n def test_process_request__multiple_files(self, rf):\n def test_process_request__no_location(self, rf, settings):\n \"/\", data={\"file\": \"tmp/s3file/s3_file.txt\", \"s3file\": \"file\"}\n def test_process_request__no_file(self, rf, caplog):\n request = rf.post(\"/\", data={\"file\": \"does_not_exist.txt\", \"s3file\": \"file\"})\n assert \"File not found: does_not_exist.txt\" in caplog.text"
}
|
{
"secure_code": "from django.core import signing\n upload_path = safe_join(\n str(storage.aws_location),\n str(\n getattr(\n settings, \"S3FILE_UPLOAD_PATH\", pathlib.PurePosixPath(\"tmp\", \"s3file\")\n )\n ),\n signer = signing.Signer(\n salt=f\"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}\"\n )\n print(self.upload_folder)\n defaults[\"data-s3f-signature\"] = signer.signature(self.upload_folder)\nfrom django.core import signing\nfrom django.core.exceptions import PermissionDenied, SuspiciousFileOperation\nfrom django.utils.crypto import constant_time_compare\nfrom .forms import S3FileInputMixin\nfrom .storages import local_dev, storage\n\n if paths:\n try:\n signature = request.POST[f\"{field_name}-s3f-signature\"]\n except KeyError:\n raise PermissionDenied(\"No signature provided.\")\n try:\n request.FILES.setlist(\n field_name, list(self.get_files_from_storage(paths, signature))\n )\n except SuspiciousFileOperation as e:\n raise PermissionDenied(\"Illegal file name!\") from e\n def get_files_from_storage(paths, signature):\n try:\n location = storage.aws_location\n except AttributeError:\n location = storage.location\n signer = signing.Signer(\n salt=f\"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}\"\n )\n print(path)\n print(signer.signature(path.parent), signature)\n if not constant_time_compare(signer.signature(path.parent), signature):\n raise PermissionDenied(\"Illegal signature!\")\n relative_path = str(path.relative_to(location))\n except ValueError as e:\n raise SuspiciousFileOperation(\n f\"Path is not inside the designated upload location: {path}\"\n ) from e\n\n f = storage.open(relative_path)\n var hiddenSignatureInput = document.createElement('input')\n hiddenSignatureInput.type = 'hidden'\n hiddenSignatureInput.name = name + '-s3f-signature'\n console.log(fileInput.dataset.s3fSignature)\n hiddenSignatureInput.value = fileInput.dataset.s3fSignature\n form.appendChild(hiddenSignatureInput)\nfrom pathlib import Path\nfrom pathlib import Path\nfrom s3file.storages import storage\n\ndef freeze_upload_folder(monkeypatch):\n \"\"\"Freeze datetime and UUID.\"\"\"\n upload_folder = Path(storage.aws_location) / \"tmp\" / \"s3file\"\n monkeypatch.setattr(\n \"s3file.forms.S3FileInputMixin.upload_folder\",\n str(upload_folder),\n )\n return upload_folder\n\n\n@pytest.fixture\ndef upload_file(request, freeze_upload_folder):\n path = Path(tempfile.mkdtemp()) / freeze_upload_folder / f\"{request.node.name}.txt\"\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:\n return str(path.absolute())\ndef another_upload_file(request, freeze_upload_folder):\n path = (\n Path(tempfile.mkdtemp())\n / freeze_upload_folder\n / f\"another_{request.node.name}.txt\"\n )\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:\n return str(path.absolute())\ndef yet_another_upload_file(request, freeze_upload_folder):\n path = (\n Path(tempfile.mkdtemp())\n / freeze_upload_folder\n / f\"yet_another_{request.node.name}.txt\"\n )\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:\n return str(path.absolute())\n def test_value_from_datadict(self, freeze_upload_folder, client, upload_file):\n uploaded_file = storage.save(freeze_upload_folder / \"test.jpg\", f)\n \"file\": f\"custom/location/{uploaded_file}\",\n \"file-s3f-signature\": \"m94qBxBsnMIuIICiY133kX18KkllSPMVbhGAdAwNn1A\",\n \"s3file\": \"file\",\n def test_build_attr(self, freeze_upload_folder):\n \"data-s3f-signature\",\n assert (\n ClearableFileInput().build_attrs({})[\"data-s3f-signature\"]\n == \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\"\n )\n def test_get_conditions(self, freeze_upload_folder):\n [\"starts-with\", \"$key\", \"custom/location/tmp/s3file\"],\n def test_file_insert(\n self, request, driver, live_server, upload_file, freeze_upload_folder\n ):\n assert storage.exists(\"tmp/s3file/%s.txt\" % request.node.name)\n def test_file_insert_submit_value(\n self, driver, live_server, upload_file, freeze_upload_folder\n ):\n def test_progress(self, driver, live_server, upload_file, freeze_upload_folder):\n freeze_upload_folder,\n file_input.send_keys(\n \" \\n \".join(\n [\n str(freeze_upload_folder / upload_file),\n str(freeze_upload_folder / another_upload_file),\n ]\n )\n )\n file_input.send_keys(str(freeze_upload_folder / yet_another_upload_file))\nimport pytest\nfrom django.core.exceptions import PermissionDenied, SuspiciousFileOperation\n def test_get_files_from_storage(self, freeze_upload_folder):\n [os.path.join(storage.aws_location, name)],\n \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n def test_process_request(self, freeze_upload_folder, rf):\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n def test_process_request__location_escape(self, freeze_upload_folder, rf):\n storage.save(\"secrets/passwords.txt\", ContentFile(b\"keep this secret\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/secrets/passwords.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n assert \"Illegal signature!\" in str(e.value)\n\n def test_process_request__multiple_files(self, freeze_upload_folder, rf):\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n \"other_file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n def test_process_request__no_location(self, freeze_upload_folder, rf, settings):\n \"/\",\n data={\n \"file\": f\"tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"scjzm3N8njBQIVSGEhOchtM0TkGyb2U6OXGLVlRUZhY\",\n },\n def test_process_request__no_file(self, freeze_upload_folder, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n },\n )\n assert (\n \"File not found: custom/location/tmp/s3file/does_not_exist.txt\"\n in caplog.text\n )\n\n def test_process_request__no_signature(self, rf, caplog):\n request = rf.post(\n \"/\", data={\"file\": \"tmp/s3file/does_not_exist.txt\", \"s3file\": \"file\"}\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n\n def test_process_request__wrong_signature(self, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"fake\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)"
}
|
{
"source": "CVEFixes"
}
|
CVE-2012-2675
|
C
|
{
"vulnerable_code": "\tunsigned flags=NEDMALLOC_FORCERESERVE(p, 0, no*size);\r\n\treturn nedpmalloc2(p, size*no, 0, M2_ZERO_MEMORY|flags);\r"
}
|
{
"secure_code": "\tsize_t bytes=no*size;\r\n\t/* Avoid multiplication overflow. */\r\n\tif(size && no!=bytes/size)\r\n\t\treturn 0;\r\n\tunsigned flags=NEDMALLOC_FORCERESERVE(p, 0, bytes);\r\n\treturn nedpmalloc2(p, bytes, 0, M2_ZERO_MEMORY|flags);\r"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-34071
|
C#
|
{
"vulnerable_code": " if(Uri.IsWellFormedUriString(encodedImagePath, UriKind.Relative))\n if (Uri.IsWellFormedUriString(redir, UriKind.Relative)\n && redir.StartsWith(\"//\") == false"
}
|
{
"secure_code": "\n\n /// <summary>\n /// Determines whether the provided web path is well-formed according to the specified UriKind.\n /// </summary>\n /// <param name=\"webPath\">The web path to check. This can be null.</param>\n /// <param name=\"uriKind\">The kind of Uri (Absolute, Relative, or RelativeOrAbsolute).</param>\n /// <returns>\n /// true if <paramref name=\"webPath\"/> is well-formed; otherwise, false.\n /// </returns>\n public static bool IsWellFormedWebPath(string? webPath, UriKind uriKind)\n {\n if (string.IsNullOrWhiteSpace(webPath))\n {\n return false;\n }\n\n if (webPath.StartsWith(\"//\"))\n {\n return uriKind is not UriKind.Relative;\n }\n\n return Uri.IsWellFormedUriString(webPath, uriKind);\n }\nusing Umbraco.Cms.Core.Routing;\n if(WebPath.IsWellFormedWebPath(encodedImagePath, UriKind.Relative))\nusing Umbraco.Cms.Core.Routing;\n if (WebPath.IsWellFormedWebPath(redir, UriKind.Relative)\n\n\n [Test]\n [TestCase(\"ftp://hello.com/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"file:///hello.com/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"ws://hello.com/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"wss://hello.com/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com:8080/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com:8080/\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path?query=param\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path?query=param\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path?query=param#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path?query=param#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com:8080/path?query=param#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com:8080/path?query=param#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080/path?query=param#fragment\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080/path\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"//hello.com\", UriKind.Absolute, ExpectedResult = true)]\n [TestCase(\"/test/test.jpg\", UriKind.Absolute, ExpectedResult = false)]\n [TestCase(\"/test\", UriKind.Absolute, ExpectedResult = false)]\n [TestCase(\"test\", UriKind.Absolute, ExpectedResult = false)]\n [TestCase(\"\", UriKind.Absolute, ExpectedResult = false)]\n [TestCase(null, UriKind.Absolute, ExpectedResult = false)]\n [TestCase(\"this is not welformed\", UriKind.Absolute, ExpectedResult = false)]\n [TestCase(\"ftp://hello.com/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"file:///hello.com/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"ws://hello.com/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"wss://hello.com/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com:8080/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com:8080/\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com/path\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com/path\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com/path?query=param\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com/path?query=param\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com/path#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com/path#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com/path?query=param#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com/path?query=param#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"https://hello.com:8080/path?query=param#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"http://hello.com:8080/path?query=param#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"//hello.com:8080/path?query=param#fragment\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"//hello.com:8080/path\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"//hello.com:8080\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"//hello.com\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"/test/test.jpg\", UriKind.Relative, ExpectedResult = true)]\n [TestCase(\"/test\", UriKind.Relative, ExpectedResult = true)]\n [TestCase(\"test\", UriKind.Relative, ExpectedResult = true)]\n [TestCase(\"\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(null, UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"this is not welformed\", UriKind.Relative, ExpectedResult = false)]\n [TestCase(\"ftp://hello.com/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"file:///hello.com/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"ws://hello.com/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"wss://hello.com/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com:8080/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com:8080/\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path?query=param\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path?query=param\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com/path?query=param#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com/path?query=param#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"https://hello.com:8080/path?query=param#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"http://hello.com:8080/path?query=param#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080/path?query=param#fragment\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080/path\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"//hello.com:8080\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"//hello.com\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"/test/test.jpg\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"/test\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"test\", UriKind.RelativeOrAbsolute, ExpectedResult = true)]\n [TestCase(\"\", UriKind.RelativeOrAbsolute, ExpectedResult = false)]\n [TestCase(null, UriKind.RelativeOrAbsolute, ExpectedResult = false)]\n [TestCase(\"this is not welformed\", UriKind.RelativeOrAbsolute, ExpectedResult = false)]\n public bool IsWellFormedWebPath(string? webPath, UriKind uriKind) => WebPath.IsWellFormedWebPath(webPath, uriKind);\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2020-11008
|
C
|
{
"vulnerable_code": "\tif (!proto_end)\n\t\treturn 0;\n\t\tchar *decoded = url_decode(url);\n\t\tint has_nl = !!strchr(decoded, '\\n');\n\t# do not actually issue \"list\" or other commands, as we do not\n\t# want to rely on what curl would actually do with such a broken\n\t# URL. This is just about making sure we do not segfault during\n\t# initialization.\n\ttest_must_fail git remote-http http::/example.com/repo.git"
}
|
{
"secure_code": "\tif (!proto_end) {\n\t\tif (!quiet)\n\t\t\twarning(_(\"url has no scheme: %s\"), url);\n\t\treturn -1;\n\t}\n/*\n * Count directory components that a relative submodule URL should chop\n * from the remote_url it is to be resolved against.\n *\n * In other words, this counts \"../\" components at the start of a\n * submodule URL.\n *\n * Returns the number of directory components to chop and writes a\n * pointer to the next character of url after all leading \"./\" and\n * \"../\" components to out.\n */\nstatic int count_leading_dotdots(const char *url, const char **out)\n{\n\tint result = 0;\n\twhile (1) {\n\t\tif (starts_with_dot_dot_slash(url)) {\n\t\t\tresult++;\n\t\t\turl += strlen(\"../\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (starts_with_dot_slash(url)) {\n\t\t\turl += strlen(\"./\");\n\t\t\tcontinue;\n\t\t}\n\t\t*out = url;\n\t\treturn result;\n\t}\n}\n\t\tchar *decoded;\n\t\tconst char *next;\n\t\tint has_nl;\n\n\t\tdecoded = url_decode(url);\n\t\thas_nl = !!strchr(decoded, '\\n');\n\n\n\t\t/*\n\t\t * URLs which escape their root via \"../\" can overwrite\n\t\t * the host field and previous components, resolving to\n\t\t * URLs like https::example.com/submodule.git that were\n\t\t * susceptible to CVE-2020-11008.\n\t\t */\n\t\tif (count_leading_dotdots(url, &next) > 0 &&\n\t\t *next == ':')\n\t\t\treturn -1;\n\ttest_must_fail git remote-http http::/example.com/repo.git 2>stderr &&\n\ttest_i18ngrep \"url has no scheme\" stderr\ntest_expect_success 'fsck rejects missing URL scheme' '\n\tgit checkout --orphan missing-scheme &&\n\tcat >.gitmodules <<-\\EOF &&\n\t[submodule \"foo\"]\n\t\turl = http::one.example.com/foo.git\n\tEOF\n\tgit add .gitmodules &&\n\ttest_tick &&\n\tgit commit -m \"gitmodules with missing URL scheme\" &&\n\ttest_when_finished \"rm -rf dst\" &&\n\tgit init --bare dst &&\n\tgit -C dst config transfer.fsckObjects true &&\n\ttest_must_fail git push dst HEAD 2>err &&\n\tgrep gitmodulesUrl err\n'\n\ntest_expect_success 'fsck rejects relative URL resolving to missing scheme' '\n\tgit checkout --orphan relative-missing-scheme &&\n\tcat >.gitmodules <<-\\EOF &&\n\t[submodule \"foo\"]\n\t\turl = \"..\\\\../.\\\\../:one.example.com/foo.git\"\n\tEOF\n\tgit add .gitmodules &&\n\ttest_tick &&\n\tgit commit -m \"gitmodules with relative URL that strips off scheme\" &&\n\ttest_when_finished \"rm -rf dst\" &&\n\tgit init --bare dst &&\n\tgit -C dst config transfer.fsckObjects true &&\n\ttest_must_fail git push dst HEAD 2>err &&\n\tgrep gitmodulesUrl err\n'\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-4980
|
PHP
|
{
"vulnerable_code": " $hasvalue = ! empty($vars['hostname']) ? \"value='\" . $vars['hostname'] . \"'\" : '';\n $ifaliasvalue = isset($vars['ifAlias']) ? \"value='\" . $vars['ifAlias'] . \"'\" : '';\n echo \"<div class='alert alert-danger'>Port ID {$vars['purge']} not found! Could not purge port.</div>\";"
}
|
{
"secure_code": " $hasvalue = ! empty($vars['hostname']) ? \"value='\" . htmlspecialchars($vars['hostname']) . \"'\" : '';\n $ifaliasvalue = isset($vars['ifAlias']) ? \"value='\" . htmlspecialchars($vars['ifAlias']) . \"'\" : '';\n echo \"<div class='alert alert-danger'>Port ID \" . htmlspecialchars($vars['purge']) . ' not found! Could not purge port.</div>';"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-29882
|
C++
|
{
"vulnerable_code": " \"srs_utest_protocol\" \"srs_utest_protocol2\" \"srs_utest_kernel2\")\n#define VERSION_REVISION 209\n#define VERSION_REVISION 120\n XX(ERROR_STREAM_CASTER_HEVC_FORMAT , 4057, \"CasterTsHevcFormat\", \"Invalid ts HEVC Format for stream caster\")\n if (!query_get(\"callback\").empty()) {\n jsonp = true;\n }"
}
|
{
"secure_code": " \"srs_utest_protocol\" \"srs_utest_protocol2\" \"srs_utest_kernel2\" \"srs_utest_protocol3\")\n* v6.0, 2024-03-26, Filter JSONP callback function name. v6.0.121\n* v5.0, 2024-03-26, Filter JSONP callback function name. v5.0.210\n#define VERSION_REVISION 210\n#define VERSION_REVISION 121\n XX(ERROR_STREAM_CASTER_HEVC_FORMAT , 4057, \"CasterTsHevcFormat\", \"Invalid ts HEVC Format for stream caster\") \\\n XX(ERROR_HTTP_JSONP , 4058, \"HttpJsonp\", \"Invalid callback for JSONP\")\n// For callback function name, only allow [a-zA-Z0-9_-.] characters.\nbool srs_is_valid_jsonp_callback(std::string callback)\n{\n for (int i = 0; i < (int)callback.length(); i++) {\n char ch = callback.at(i);\n bool is_alpha_beta = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');\n bool is_number = (ch >= '0' && ch <= '9');\n if (!is_alpha_beta && !is_number && ch != '.' && ch != '_' && ch != '-') {\n return false;\n }\n }\n return true;\n}\n\n string callback= query_get(\"callback\");\n jsonp = !callback.empty();\n\n\n if (!srs_is_valid_jsonp_callback(callback)) {\n return srs_error_new(ERROR_HTTP_JSONP, \"invalid callback=%s\", callback.c_str());\n }\n//\n// Copyright (c) 2013-2024 The SRS Authors\n//\n// SPDX-License-Identifier: MIT\n//\n#include <srs_utest_protocol3.hpp>\n\nusing namespace std;\n\n#include <srs_kernel_error.hpp>\n#include <srs_core_autofree.hpp>\n#include <srs_protocol_utility.hpp>\n#include <srs_protocol_rtmp_msg_array.hpp>\n#include <srs_protocol_rtmp_stack.hpp>\n#include <srs_kernel_utility.hpp>\n#include <srs_app_st.hpp>\n#include <srs_protocol_amf0.hpp>\n#include <srs_protocol_rtmp_stack.hpp>\n#include <srs_protocol_http_conn.hpp>\n#include <srs_protocol_protobuf.hpp>\n#include <srs_kernel_buffer.hpp>\n\nextern bool srs_is_valid_jsonp_callback(std::string callback);\n\nVOID TEST(ProtocolHttpTest, JsonpCallbackName)\n{\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"callback\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback1234567890\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback-1234567890\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback_1234567890\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback.1234567890\"));\n EXPECT_TRUE(srs_is_valid_jsonp_callback(\"Callback1234567890-_.\"));\n EXPECT_FALSE(srs_is_valid_jsonp_callback(\"callback()//\"));\n EXPECT_FALSE(srs_is_valid_jsonp_callback(\"callback!\"));\n EXPECT_FALSE(srs_is_valid_jsonp_callback(\"callback;\"));\n}\n\n//\n// Copyright (c) 2013-2024 The SRS Authors\n//\n// SPDX-License-Identifier: MIT\n//\n\n#ifndef SRS_UTEST_PROTOCOL3_HPP\n#define SRS_UTEST_PROTOCOL3_HPP\n\n/*\n#include <srs_utest_protocol3.hpp>\n*/\n#include <srs_utest_protocol.hpp>\n\n#endif\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-22198
|
Go
|
{
"vulnerable_code": " \"github.com/0xJacky/Nginx-UI/api\"\n \"github.com/0xJacky/Nginx-UI/settings\"\n \"github.com/gin-gonic/gin\"\n \"net/http\"\n c.JSON(http.StatusOK, gin.H{\n \"server\": settings.ServerSettings,\n \"nginx\": settings.NginxSettings,\n \"openai\": settings.OpenAISettings,\n })\n var json struct {\n Server settings.Server `json:\"server\"`\n Nginx settings.Nginx `json:\"nginx\"`\n Openai settings.OpenAI `json:\"openai\"`\n }\n\n if !api.BindAndValid(c, &json) {\n return\n }\n\n settings.ServerSettings = json.Server\n settings.NginxSettings = json.Nginx\n settings.OpenAISettings = json.Openai\n\n settings.ReflectFrom()\n\n err := settings.Save()\n if err != nil {\n api.ErrHandler(c, err)\n return\n }\n GetSettings(c)\n\tConfigDir string `json:\"config_dir\"`\n\tPIDPath string `json:\"pid_path\"`\n\tTestConfigCmd string `json:\"test_config_cmd\"`\n\tReloadCmd string `json:\"reload_cmd\"`\n\tRestartCmd string `json:\"restart_cmd\"`\n\tHttpHost string `json:\"http_host\"`\n\tHttpPort string `json:\"http_port\"`\n\tRunMode string `json:\"run_mode\"`\n\tJwtSecret string `json:\"jwt_secret\"`\n\tNodeSecret string `json:\"node_secret\"`\n\tEmail string `json:\"email\"`\n\tDatabase string `json:\"database\"`\n\tStartCmd string `json:\"start_cmd\"`\n\tDemo bool `json:\"demo\"`\n\tPageSize int `json:\"page_size\"`"
}
|
{
"secure_code": "\t\"github.com/0xJacky/Nginx-UI/api\"\n\t\"github.com/0xJacky/Nginx-UI/settings\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n\t\"reflect\"\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"server\": settings.ServerSettings,\n\t\t\"nginx\": settings.NginxSettings,\n\t\t\"openai\": settings.OpenAISettings,\n\t})\n\tvar json struct {\n\t\tServer settings.Server `json:\"server\"`\n\t\tNginx settings.Nginx `json:\"nginx\"`\n\t\tOpenai settings.OpenAI `json:\"openai\"`\n\t}\n\n\tif !api.BindAndValid(c, &json) {\n\t\treturn\n\t}\n\n\t// todo: omit protected fields when binding\n\tfillSettings(&settings.ServerSettings, &json.Server)\n\tfillSettings(&settings.NginxSettings, &json.Nginx)\n\tfillSettings(&settings.OpenAISettings, &json.Openai)\n\n\tsettings.ReflectFrom()\n\n\terr := settings.Save()\n\tif err != nil {\n\t\tapi.ErrHandler(c, err)\n\t\treturn\n\t}\n\n\tGetSettings(c)\n}\nfunc fillSettings(targetSettings interface{}, newSettings interface{}) {\n\ts := reflect.TypeOf(targetSettings).Elem()\n\tvt := reflect.ValueOf(targetSettings).Elem()\n\tvn := reflect.ValueOf(newSettings).Elem()\n\n\t// copy the values from new to target settings if it is not protected\n\tfor i := 0; i < s.NumField(); i++ {\n\t\tif s.Field(i).Tag.Get(\"protected\") != \"true\" {\n\t\t\tvt.Field(i).Set(vn.Field(i))\n\t\t}\n\t}\n\tConfigDir string `json:\"config_dir\" protected:\"true\"`\n\tPIDPath string `json:\"pid_path\" protected:\"true\"`\n\tTestConfigCmd string `json:\"test_config_cmd\" protected:\"true\"`\n\tReloadCmd string `json:\"reload_cmd\" protected:\"true\"`\n\tRestartCmd string `json:\"restart_cmd\" protected:\"true\"`\n\tHttpHost string `json:\"http_host\" protected:\"true\"`\n\tHttpPort string `json:\"http_port\" protected:\"true\"`\n\tRunMode string `json:\"run_mode\" protected:\"true\"`\n\tJwtSecret string `json:\"jwt_secret\" protected:\"true\"`\n\tNodeSecret string `json:\"node_secret\" protected:\"true\"`\n\tEmail string `json:\"email\" protected:\"true\"`\n\tDatabase string `json:\"database\" protected:\"true\"`\n\tStartCmd string `json:\"start_cmd\" protected:\"true\"`\n\tDemo bool `json:\"demo\" protected:\"true\"`\n\tPageSize int `json:\"page_size\" protected:\"true\"`"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-42703
|
C
|
{
"vulnerable_code": "\t * Count of child anon_vmas and VMAs which points to this anon_vma.\n\tunsigned degree;\n\t\tanon_vma->degree = 1;\t/* Reference for first vma */\n\t\t/* vma reference or self-parent link for new root */\n\t\tanon_vma->degree++;\n\t\t * Reuse existing anon_vma if its degree lower than two,\n\t\t * that means it has no vma and only one anon_vma child.\n\t\t * Do not choose parent anon_vma, otherwise first child\n\t\t * will always reuse it. Root anon_vma is never reused:\n\t\t anon_vma != src->anon_vma && anon_vma->degree < 2)\n\t\tdst->anon_vma->degree++;\n\tanon_vma->parent->degree++;\n\t\t\tanon_vma->parent->degree--;\n\t\tvma->anon_vma->degree--;\n\t\tVM_WARN_ON(anon_vma->degree);"
}
|
{
"secure_code": "\t * Count of child anon_vmas. Equals to the count of all anon_vmas that\n\t * have ->parent pointing to this one, including itself.\n\tunsigned long num_children;\n\t/* Count of VMAs whose ->anon_vma pointer points to this object. */\n\tunsigned long num_active_vmas;\n\t\tanon_vma->num_children = 0;\n\t\tanon_vma->num_active_vmas = 0;\n\t\tanon_vma->num_children++; /* self-parent link for new root */\n\t\tanon_vma->num_active_vmas++;\n\t\t * Reuse existing anon_vma if it has no vma and only one\n\t\t * anon_vma child.\n\t\t * Root anon_vma is never reused:\n\t\t anon_vma->num_children < 2 &&\n\t\t anon_vma->num_active_vmas == 0)\n\t\tdst->anon_vma->num_active_vmas++;\n\tanon_vma->num_active_vmas++;\n\tanon_vma->parent->num_children++;\n\t\t\tanon_vma->parent->num_children--;\n\t\tvma->anon_vma->num_active_vmas--;\n\t\tVM_WARN_ON(anon_vma->num_children);\n\t\tVM_WARN_ON(anon_vma->num_active_vmas);"
}
|
{
"source": "CVEFixes"
}
|
CVE-2018-20595
|
Java
|
{
"vulnerable_code": " // if (!state.equals(cachedState)) throw new BusinessException(\"state error\");"
}
|
{
"secure_code": " STATE_ERROR(4042), //statιθ――\n\nimport org.hswebframework.web.BusinessException;\nimport org.hswebframework.web.oauth2.core.ErrorType;\n if (!state.equals(cachedState)) {\n throw new BusinessException(ErrorType.STATE_ERROR.name());\n }"
}
|
{
"source": "CVEFixes"
}
|
CVE-2015-5283
|
C
|
{
"vulnerable_code": "static int __net_init sctp_net_init(struct net *net)\n\t/* Initialize the control inode/socket for handling OOTB packets. */\n\tif ((status = sctp_ctl_sock_init(net))) {\n\t\tpr_err(\"Failed to initialize the SCTP control sock\\n\");\n\t\tgoto err_ctl_sock_init;\n\t}\n\nerr_ctl_sock_init:\n\tsctp_dbg_objcnt_exit(net);\n\tsctp_proc_exit(net);\nstatic void __net_exit sctp_net_exit(struct net *net)\n\t/* Free the control endpoint. */\n\tinet_ctl_sock_destroy(net->sctp.ctl_sock);\n\nstatic struct pernet_operations sctp_net_ops = {\n\t.init = sctp_net_init,\n\t.exit = sctp_net_exit,\n\tstatus = sctp_v4_protosw_init();\n\tstatus = register_pernet_subsys(&sctp_net_ops);\n\t\tgoto err_register_pernet_subsys;\n\tunregister_pernet_subsys(&sctp_net_ops);\nerr_register_pernet_subsys:\n\tunregister_pernet_subsys(&sctp_net_ops);"
}
|
{
"secure_code": "static int __net_init sctp_defaults_init(struct net *net)\nstatic void __net_exit sctp_defaults_exit(struct net *net)\nstatic struct pernet_operations sctp_defaults_ops = {\n\t.init = sctp_defaults_init,\n\t.exit = sctp_defaults_exit,\n};\n\nstatic int __net_init sctp_ctrlsock_init(struct net *net)\n{\n\tint status;\n\n\t/* Initialize the control inode/socket for handling OOTB packets. */\n\tstatus = sctp_ctl_sock_init(net);\n\tif (status)\n\t\tpr_err(\"Failed to initialize the SCTP control sock\\n\");\n\n\treturn status;\n}\n\nstatic void __net_init sctp_ctrlsock_exit(struct net *net)\n{\n\t/* Free the control endpoint. */\n\tinet_ctl_sock_destroy(net->sctp.ctl_sock);\n}\n\nstatic struct pernet_operations sctp_ctrlsock_ops = {\n\t.init = sctp_ctrlsock_init,\n\t.exit = sctp_ctrlsock_exit,\n\tstatus = register_pernet_subsys(&sctp_defaults_ops);\n\tif (status)\n\t\tgoto err_register_defaults;\n\tstatus = sctp_v4_protosw_init();\n\tstatus = register_pernet_subsys(&sctp_ctrlsock_ops);\n\t\tgoto err_register_ctrlsock;\n\tunregister_pernet_subsys(&sctp_ctrlsock_ops);\nerr_register_ctrlsock:\n\tunregister_pernet_subsys(&sctp_defaults_ops);\nerr_register_defaults:\n\tunregister_pernet_subsys(&sctp_ctrlsock_ops);\n\tunregister_pernet_subsys(&sctp_defaults_ops);\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2017-5549
|
C
|
{
"vulnerable_code": "\tif (rc < 0)\n\t\tdev_err(&port->dev, \"Reading line status failed (error = %d)\\n\",\n\t\t\trc);\n\telse {"
}
|
{
"secure_code": "\tif (rc != KLSI_STATUSBUF_LEN) {\n\t\tdev_err(&port->dev, \"reading line status failed: %d\\n\", rc);\n\t\tif (rc >= 0)\n\t\t\trc = -EIO;\n\t} else {"
}
|
{
"source": "CVEFixes"
}
|
CVE-2018-20178
|
C
|
{
"vulnerable_code": "ber_parse_header(STREAM s, int tagval, int *length)\n\t\t\t\twhile (collen > 0)\n\t\t\t\twhile (replen > 0)\n\t\t\t\twhile (collen > 0)\n\t\t\t\twhile (replen > 0)\n\t\ttoken->end = token->p = token->data;\n Copyright (C) 2005 Matrox Graphics Inc. \n\tint length;\n\tint length;\nRD_BOOL ber_parse_header(STREAM s, int tagval, int *length);\n/* Process bitmap updates */\nvoid\nprocess_bitmap_updates(STREAM s)\n\tuint16 num_updates;\n\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n\tint i;\n\n\tin_uint16_le(s, num_updates);\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tin_uint16_le(s, left);\n\t\tin_uint16_le(s, top);\n\t\tin_uint16_le(s, right);\n\t\tin_uint16_le(s, bottom);\n\t\tin_uint16_le(s, width);\n\t\tin_uint16_le(s, height);\n\t\tin_uint16_le(s, bpp);\n\t\tBpp = (bpp + 7) / 8;\n\t\tin_uint16_le(s, compress);\n\t\tin_uint16_le(s, bufsize);\n\n\t\tcx = right - left + 1;\n\t\tcy = bottom - top + 1;\n\n\t\tlogger(Graphics, Debug,\n\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n\t\t left, top, right, bottom, width, height, Bpp, compress);\n\n\t\tif (!compress)\n\t\t{\n\t\t\tint y;\n\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\t\t\tfor (y = 0; y < height; y++)\n\t\t\t{\n\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n\t\t\t\t\t width * Bpp);\n\t\t\t}\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\t\txfree(bmpdata);\n\t\t\tcontinue;\n\t\t}\n\t\tif (compress & 0x400)\n\t\t{\n\t\t\tsize = bufsize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tin_uint8s(s, 2);\t/* pad */\n\t\t\tin_uint16_le(s, size);\n\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n\t\t}\n\t\tin_uint8p(s, data, size);\n\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\telse\n\t\t{\n\t\t\tlogger(Graphics, Warning,\n\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n\t\t}\n\n#define s_check_rem(s,n)\t((s)->p + n <= (s)->end)"
}
|
{
"secure_code": "ber_parse_header(STREAM s, int tagval, uint32 *length)\n\t\t\t\twhile (indexw < width && collen > 0)\n\t\t\t\twhile (indexw < width && replen > 0)\n\t\t\t\twhile (indexw < width && collen > 0)\n\t\t\t\twhile (indexw < width && replen > 0)\n\tstruct stream packet = *s;\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"cliprdr_process(), consume of packet from stream would overrun\", &packet);\n\t}\n\n/* [MS-RDPBCGR], TS_BITMAP_DATA, flags */\n#define BITMAP_COMPRESSION 0x0001\n\n\tstruct stream packet;\n\tpacket = *s;\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\t rdp_protocol_error(\"cssp_read_tsrequest(), consume of version from stream would overrun\",\n\t\t\t\t &packet);\n\t}\n\t\tif (!s_check_rem(s, length))\n\t\t{\n\t\t\trdp_protocol_error(\"cssp_read_tsrequest(), consume of token from stream would overrun\",\n\t\t\t\t\t &packet);\n\t\t}\n\n\t\ts_realloc(token, length);\n\t\ts_reset(token);\n Copyright (C) 2005 Matrox Graphics Inc.\n Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB\n\tstruct stream packet = *s;\n\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n\t}\n\tuint32 length;\n\tstruct stream packet = *s;\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n\t}\n\n\tuint32 length;\n\tstruct stream packet;\n\t\n\tpacket = *s;\n\n\tif (!s_check_rem(s, length))\n\t{\n\t\trdp_protocol_error(\"mcs_recv_connect_response(), consume connect id from stream would overrun\", &packet);\n\t}\n\n\tstruct stream packet = *s;\n\tif (!s_check_rem(s, length + 7))\n\t{\n\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n\t}\n\nvoid rdp_protocol_error(const char *message, STREAM s);\nRD_BOOL ber_parse_header(STREAM s, int tagval, uint32 *length);\n\tstruct stream packet = *s;\n\n\tif ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))\n\t{\n\t\tlogger(Protocol, Error, \"rdp_in_unistr(), length of unicode data is out of bounds.\");\n\t\tabort();\n\t}\n\n\tif (!s_check_rem(s, in_len))\n\t{\n\t\trdp_protocol_error(\"rdp_in_unistr(), consume of unicode data from stream would overrun\", &packet);\n\t}\n\n\tstruct stream packet = *s;\n\n\tif (!s_check_rem(s, len_src_descriptor))\n\t{\n\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n\t}\n/* Process TS_BITMAP_DATA */\nstatic void\nprocess_bitmap_data(STREAM s)\n\tuint16 cx, cy, bpp, Bpp, flags, bufsize, size;\n\t\n\tstruct stream packet = *s;\n\tin_uint16_le(s, left); /* destLeft */\n\tin_uint16_le(s, top); /* destTop */\n\tin_uint16_le(s, right); /* destRight */\n\tin_uint16_le(s, bottom); /* destBottom */\n\tin_uint16_le(s, width); /* width */\n\tin_uint16_le(s, height); /* height */\n\tin_uint16_le(s, bpp); /*bitsPerPixel */\n\tBpp = (bpp + 7) / 8;\n\tin_uint16_le(s, flags); /* flags */\n\tin_uint16_le(s, bufsize); /* bitmapLength */\n\tcx = right - left + 1;\n\tcy = bottom - top + 1;\n\t/* FIXME: There are a assumtion that we do not consider in\n\t\tthis code. The value of bpp is not passed to\n\t\tui_paint_bitmap() which relies on g_server_bpp for drawing\n\t\tthe bitmap data.\n\n\t\tDoes this means that we can sanity check bpp with g_server_bpp ?\n\t*/\n\n\tif (Bpp == 0 || width == 0 || height == 0)\n\t{\n logger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n\t}\n\n\tif ((RD_UINT32_MAX / Bpp) <= (width * height))\n\t{\n\t\tlogger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n\t}\n \n\tif (flags == 0)\n\t{\n\t\t/* read uncompressed bitmap data */\n\t\tint y;\n\t\tfor (y = 0; y < height; y++)\n\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);\n\t\t\n\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t\treturn;\n\t}\n\n\tif (flags & NO_BITMAP_COMPRESSION_HDR)\n\t{\n\t\tsize = bufsize;\n\t}\n\telse\n\t{\n\t\t/* Read TS_CD_HEADER */\n\t\tin_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */\n\t\tin_uint16_le(s, size); /* cbCompMainBodySize */\n\t\tin_uint8s(s, 2); /* skip cbScanWidth */\n\t\tin_uint8s(s, 2); /* skip cbUncompressedSize */\n\t}\n\n\t/* read compressed bitmap data */\n\tif (!s_check_rem(s, size))\n\t{\n\t\trdp_protocol_error(\"process_bitmap_data(), consume of bitmap data from stream would overrun\", &packet);\n\t}\n\tin_uint8p(s, data, size);\n\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n\t{\n\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n\t}\n\telse\n\t{\n\t\tlogger(Protocol, Warning, \"%s(), failed to decompress bitmap\", __func__);\n\t}\n\n\txfree(bmpdata);\n}\n\n/* Process TS_UPDATE_BITMAP_DATA */\nvoid\nprocess_bitmap_updates(STREAM s)\n{\n\tint i;\n\tuint16 num_updates;\n\t\n\tin_uint16_le(s, num_updates); /* rectangles */\n\n\tfor (i = 0; i < num_updates; i++)\n\t{\n\t\tprocess_bitmap_data(s);\n\n/* Abort rdesktop upon protocol error\n\n A protocol error is defined as:\n\n - A value is outside specified range for example;\n bpp for a bitmap is not allowed to be greater than the\n value 32 but is represented by a byte in protocol.\n\n*/\nvoid\nrdp_protocol_error(const char *message, STREAM s)\n{\n\tlogger(Protocol, Error, \"%s(), %s\", __func__, message);\n\tif (s)\n\t\thexdump(s->p, s_length(s));\n\texit(0);\n}\n\tstruct stream packet = *s;\n\n\t\t\t\t/* g_client_id is sent back to server,\n\t\t\t\t so lets check that we actually got\n\t\t\t\t valid data from stream to prevent\n\t\t\t\t that we leak back data to server */\n\t\t\t\tif (!s_check(s))\n\t\t\t\t{\n\t\t\t\t\trdp_protocol_error(\"rdpdr_process(), consume of g_client_id from stream did overrun\", &packet);\n\t\t\t\t}\n\n\tstruct stream packet = *in;\n\n\tif (!s_check_rem(in, 4))\n\t{\n\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n\t}\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"rdpsnddbg_process(), stream is in unstable state\", s);\n\t}\n\n\n\t\t\tif ((size_t)len >= sizeof(icon_buf))\n\t\t\t{\n\t\t\t\tlogger(Protocol, Warning, \"seamless_process_line(), icon data would overrun icon_buf\");\n\t\t\t\tbreak;\n\t\t\t}\n\tstruct stream packet = *s;\n\n\tif (!s_check(s))\n\t{\n\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n\t}\n\tif (length <= 0)\n\t\treturn;\n\n\tstruct stream packet;\n\t\tpacket = *s;\n\t\t\t\tif (!s_check_rem(s, 8)) {\n\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume fastpath signature from stream would overrun\", &packet);\n\t\t\t\t}\n\n\t\t\t\t\tif (!s_check_rem(s, 8)) {\n\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume encrypt signature from stream would overrun\", &packet);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!s_check_rem(s, 8)) {\n\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume redirect signature from stream would overrun\", &packet);\n\t\t\t\t\t}\n\n#define s_check_rem(s,n) (s_check(s) && (n <= (s)->end - (s)->p))\n#define RD_UINT32_MAX (uint32)(-1)\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2016-10969
|
PHP
|
{
"vulnerable_code": "\t\t$placeholder = __( 'What is your conversation about?', 'supportflow' );\n\t\techo '<h4>' . __( 'Subject', 'supportflow' ) . '</h4>';\n\t\techo '<input type=\"text\" id=\"subject\" name=\"post_title\" class=\"sf_autosave\" placeholder=\"' . $placeholder . '\" value=\"' . get_the_title() . '\" autocomplete=\"off\" />';\n\t\techo '<p class=\"description\">' . __( 'Please describe what this ticket is about in several words', 'supportflow' ) . '</p>';"
}
|
{
"secure_code": "\t\t?>\n\n\t\t<h4><?php _e( 'Subject', 'supportflow' ); ?></h4>\n\t\t<input\n\t\t\ttype=\"text\"\n\t\t\tid=\"subject\"\n\t\t\tname=\"post_title\"\n\t\t\tclass=\"sf_autosave\"\n\t\t\tplaceholder=\"<?php _e( 'What is your conversation about?', 'supportflow' ); ?>\"\n\t\t\tvalue=\"<?php echo esc_attr( get_the_title() ); ?>\"\n\t\t\tautocomplete=\"off\"\n\t\t/>\n\t\t<p class=\"description\">\n\t\t\t<?php _e( 'Please describe what this ticket is about in several words', 'supportflow' ) ?>\n\t\t</p>\n\n\t\t<?php"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-4126
|
Go
|
{
"vulnerable_code": "\tresp, err := uc.userService.UseRePassword(ctx, req)\n\thandler.HandleResponse(ctx, err, resp)\n// @Param data body schema.UserModifyPassWordRequest true \"UserModifyPassWordRequest\"\n\treq := &schema.UserModifyPassWordRequest{}\nfunc (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string) {\n\tAvatar *AvatarInfo `json:\"avatar\"`\n// UserModifyPassWordRequest\ntype UserModifyPassWordRequest struct {\n\tUserID string `json:\"-\" ` // user_id\n\tOldPass string `json:\"old_pass\" ` // old password\n\tPass string `json:\"pass\" ` // password\nfunc (u *UserModifyPassWordRequest) Check() (errFields []*validator.FormErrorField, err error) {\n\tRemoveUserTokens(ctx context.Context, userID string)\n// RemoveUserTokens Log out all users under this user id\nfunc (as *AuthService) RemoveUserTokens(ctx context.Context, userID string) {\n\tas.authRepo.RemoveUserTokens(ctx, userID)\n\tus.authService.RemoveUserTokens(ctx, req.UserID)\n\tus.authService.RemoveUserTokens(ctx, req.UserID)\n// UseRePassword\nfunc (us *UserService) UseRePassword(ctx context.Context, req *schema.UserRePassWordRequest) (resp *schema.GetUserResp, err error) {\n\t\treturn nil, errors.BadRequest(reason.EmailVerifyURLExpired)\n\t\treturn nil, err\n\t\treturn nil, errors.BadRequest(reason.UserNotFound)\n\t\treturn nil, err\n\t\treturn nil, err\n\tresp = &schema.GetUserResp{}\n\treturn resp, nil\nfunc (us *UserService) UserModifyPassWordVerification(ctx context.Context, request *schema.UserModifyPassWordRequest) (bool, error) {\n\tuserInfo, has, err := us.userRepo.GetByUserID(ctx, request.UserID)\n\t\treturn false, fmt.Errorf(\"user does not exist\")\n\tisPass := us.verifyPassword(ctx, request.OldPass, userInfo.Pass)\nfunc (us *UserService) UserModifyPassword(ctx context.Context, request *schema.UserModifyPassWordRequest) error {\n\tenpass, err := us.encryptPassword(ctx, request.Pass)\n\tuserInfo, has, err := us.userRepo.GetByUserID(ctx, request.UserID)\n\tif !has {\n\t\treturn fmt.Errorf(\"user does not exist\")\n\tisPass := us.verifyPassword(ctx, request.OldPass, userInfo.Pass)\n\t\treturn fmt.Errorf(\"the old password verification failed\")\nfunc (us *UserService) verifyPassword(ctx context.Context, LoginPass, UserPass string) bool {\n\terr := bcrypt.CompareHashAndPassword([]byte(UserPass), []byte(LoginPass))"
}
|
{
"secure_code": "\terr := uc.userService.UpdatePasswordWhenForgot(ctx, req)\n\thandler.HandleResponse(ctx, err, nil)\n// @Param data body schema.UserModifyPasswordReq true \"UserModifyPasswordReq\"\n\treq := &schema.UserModifyPasswordReq{}\n\treq.AccessToken = middleware.ExtractToken(ctx)\nfunc (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainToken string) {\n\t\tif token == remainToken {\n\t\t\tcontinue\n\t\t}\n\t// user have password\n\tHavePassword bool `json:\"have_password\"`\n\tr.HavePassword = len(userInfo.Pass) > 0\n\tAvatar *AvatarInfo `json:\"avatar\"`\n\tHavePassword bool `json:\"have_password\"`\ntype UserModifyPasswordReq struct {\n\tOldPass string `json:\"old_pass\"`\n\tPass string `json:\"pass\"`\n\tUserID string `json:\"-\"`\n\tAccessToken string `json:\"-\"`\nfunc (u *UserModifyPasswordReq) Check() (errFields []*validator.FormErrorField, err error) {\n\tRemoveUserTokens(ctx context.Context, userID string, remainToken string)\n// RemoveUserAllTokens Log out all users under this user id\nfunc (as *AuthService) RemoveUserAllTokens(ctx context.Context, userID string) {\n\tas.authRepo.RemoveUserTokens(ctx, userID, \"\")\n}\n\n// RemoveTokensExceptCurrentUser remove all tokens except the current user\nfunc (as *AuthService) RemoveTokensExceptCurrentUser(ctx context.Context, userID string, accessToken string) {\n\tas.authRepo.RemoveUserTokens(ctx, userID, accessToken)\n\tus.authService.RemoveUserAllTokens(ctx, req.UserID)\n\tus.authService.RemoveUserAllTokens(ctx, req.UserID)\n\tresp.HavePassword = len(userInfo.Pass) > 0\n// UpdatePasswordWhenForgot update user password when user forgot password\nfunc (us *UserService) UpdatePasswordWhenForgot(ctx context.Context, req *schema.UserRePassWordRequest) (err error) {\n\t\treturn errors.BadRequest(reason.EmailVerifyURLExpired)\n\t\treturn err\n\t\treturn errors.BadRequest(reason.UserNotFound)\n\t\treturn err\n\t\treturn err\n\t// When the user changes the password, all the current user's tokens are invalid.\n\tus.authService.RemoveUserAllTokens(ctx, userInfo.ID)\n\treturn nil\nfunc (us *UserService) UserModifyPassWordVerification(ctx context.Context, req *schema.UserModifyPasswordReq) (bool, error) {\n\tuserInfo, has, err := us.userRepo.GetByUserID(ctx, req.UserID)\n\t\treturn false, errors.BadRequest(reason.UserNotFound)\n\tisPass := us.verifyPassword(ctx, req.OldPass, userInfo.Pass)\nfunc (us *UserService) UserModifyPassword(ctx context.Context, req *schema.UserModifyPasswordReq) error {\n\tenpass, err := us.encryptPassword(ctx, req.Pass)\n\tuserInfo, exist, err := us.userRepo.GetByUserID(ctx, req.UserID)\n\tif !exist {\n\t\treturn errors.BadRequest(reason.UserNotFound)\n\n\tisPass := us.verifyPassword(ctx, req.OldPass, userInfo.Pass)\n\t\treturn errors.BadRequest(reason.OldPasswordVerificationFailed)\n\n\tus.authService.RemoveTokensExceptCurrentUser(ctx, userInfo.ID, req.AccessToken)\nfunc (us *UserService) verifyPassword(ctx context.Context, loginPass, userPass string) bool {\n\tif len(loginPass) == 0 && len(userPass) == 0 {\n\t\treturn true\n\t}\n\terr := bcrypt.CompareHashAndPassword([]byte(userPass), []byte(loginPass))"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-24833
|
PHP
|
{
"vulnerable_code": " )\n converter.makeHtml(text)\n // data URI format: data:[<mediaType>][;base64],<data>\n // position in data URI string of where mediaType ends\n const mediaTypeEnd = attachmentData.indexOf(';');\n // extract mediaType\n const mediaType = attachmentData.substring(5, mediaTypeEnd);\n // Transform into a Blob\n const buf = new Uint8Array(decodedData.length);\n for (let i = 0; i < decodedData.length; ++i) {\n buf[i] = decodedData.charCodeAt(i);\n }\n const blob = new window.Blob([ buf ], { type: mediaType });\n\n // Get Blob URL\n const blobUrl = window.URL.createObjectURL(blob);\n\n // IE does not support setting a data URI on an a element\n // Using msSaveBlob to download\n if (window.Blob && navigator.msSaveBlob) {\n $attachmentLink.off('click').on('click', function () {\n navigator.msSaveBlob(blob, fileName);\n });\n } else {\n $attachmentLink.attr('href', blobUrl);\n }\n me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mediaType);\n newDoc.write('</head><body><pre>' + DOMPurify.sanitize(Helper.htmlEntities(paste)) + '</pre></body></html>');\n DOMPurify.setConfig({\n ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i,\n SAFE_FOR_JQUERY: true\n });\n\n\t\t<script type=\"text/javascript\" data-cfasync=\"false\" src=\"js/privatebin.js?<?php echo rawurlencode($VERSION); ?>\" integrity=\"sha512-EdUms2nI12Cmtv014stIEBlyPjeKMHlkg7NiBJup1b7jJF5amKhev2RwTaldINXK4UaWbZtQ6hGuMPNvvNQZFA==\" crossorigin=\"anonymous\"></script>\n\t\t<script type=\"text/javascript\" data-cfasync=\"false\" src=\"js/privatebin.js?<?php echo rawurlencode($VERSION); ?>\" integrity=\"sha512-EdUms2nI12Cmtv014stIEBlyPjeKMHlkg7NiBJup1b7jJF5amKhev2RwTaldINXK4UaWbZtQ6hGuMPNvvNQZFA==\" crossorigin=\"anonymous\"></script>"
}
|
{
"secure_code": " * ADDED: Sanitize SVG preview, preventing script execution in instance context\n * CHANGED: Drop support for attachment download in IE\n /**\n * DOMpurify settings for HTML content\n *\n * @private\n */\n const purifyHtmlConfig = {\n ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i,\n SAFE_FOR_JQUERY: true,\n USE_PROFILES: {\n html: true\n }\n };\n\n /**\n * DOMpurify settings for SVG content\n *\n * @private\n */\n const purifySvgConfig = {\n USE_PROFILES: {\n svg: true,\n svgFilters: true\n }\n };\n\n ),\n purifyHtmlConfig\n converter.makeHtml(text),\n purifyHtmlConfig\n * get blob URL from string data and mime type\n *\n * @name AttachmentViewer.getBlobUrl\n * @private\n * @function\n * @param {string} data - raw data of attachment\n * @param {string} data - mime type of attachment\n * @return {string} objectURL\n */\n function getBlobUrl(data, mimeType)\n {\n // Transform into a Blob\n const buf = new Uint8Array(data.length);\n for (let i = 0; i < data.length; ++i) {\n buf[i] = data.charCodeAt(i);\n }\n const blob = new window.Blob(\n [buf],\n {\n type: mimeType\n }\n );\n\n // Get Blob URL\n return window.URL.createObjectURL(blob);\n }\n\n /**\n // data URI format: data:[<mimeType>][;base64],<data>\n // position in data URI string of where mimeType ends\n const mimeTypeEnd = attachmentData.indexOf(';');\n // extract mimeType\n const mimeType = attachmentData.substring(5, mimeTypeEnd);\n let blobUrl = getBlobUrl(decodedData, mimeType);\n $attachmentLink.attr('href', blobUrl);\n // sanitize SVG preview\n // prevents executing embedded scripts when CSP is not set and user\n // right-clicks/long-taps and opens the SVG in a new tab - prevented\n // in the preview by use of an img tag, which disables scripts, too\n if (mimeType.match(/image\\/svg/i)) {\n const sanitizedData = DOMPurify.sanitize(\n decodedData,\n purifySvgConfig\n );\n blobUrl = getBlobUrl(sanitizedData, mimeType);\n }\n\n me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mimeType);\n newDoc.write(\n '</head><body><pre>' +\n DOMPurify.sanitize(\n Helper.htmlEntities(paste),\n purifyHtmlConfig\n ) +\n '</pre></body></html>'\n );\n\t\t<script type=\"text/javascript\" data-cfasync=\"false\" src=\"js/privatebin.js?<?php echo rawurlencode($VERSION); ?>\" integrity=\"sha512-5fNML95dptjIMzFG4KAGE2nNbORbyrCWq4ql9tkvoUF2HSnemlxzngQ5PlWhpi0J2ttKIEqfGMBjU5MywzzdWQ==\" crossorigin=\"anonymous\"></script>\n\t\t<script type=\"text/javascript\" data-cfasync=\"false\" src=\"js/privatebin.js?<?php echo rawurlencode($VERSION); ?>\" integrity=\"sha512-5fNML95dptjIMzFG4KAGE2nNbORbyrCWq4ql9tkvoUF2HSnemlxzngQ5PlWhpi0J2ttKIEqfGMBjU5MywzzdWQ==\" crossorigin=\"anonymous\"></script>"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-21512
|
JavaScript
|
{
"vulnerable_code": " fieldName = helpers.srcEscape(fields[i].name);\n\n if (helpers.privateObjectProps.has(fields[i].name)) {\n throw new Error(\n `The field name (${fieldName}) can't be the same as an object's private property.`,\n );\n }\n\n parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);\n lvalue = `result[${helpers.srcEscape(\n fields[i].table + options.nestTables + fields[i].name,\n )}]`;\n tableName = helpers.srcEscape(fields[i].table);\n\n parserFn(`result[${helpers.srcEscape(resultTablesArray[i])}] = {};`);\n fieldName = helpers.srcEscape(fields[i].name);\n if (helpers.privateObjectProps.has(fields[i].name)) {\n throw new Error(\n `The field name (${fieldName}) can't be the same as an object's private property.`,\n );\n }\n\n parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);\n lvalue = `result[${helpers.srcEscape(\n fields[i].table + options.nestTables + fields[i].name,\n )}]`;\n lvalue = `result[${helpers.srcEscape(fields[i].table)}][${fieldName}]`;\nimport { srcEscape } from '../../../../lib/helpers.js';\n { name: prop },\n `The field name (${srcEscape(fields[0].name)}) can't be the same as an object's private property.`,\nimport { srcEscape } from '../../../../lib/helpers.js';\n { name: prop },\n `The field name (${srcEscape(fields[0].name)}) can't be the same as an object's private property.`,"
}
|
{
"secure_code": "\nconst fieldEscape = (field) => {\n if (privateObjectProps.has(field)) {\n throw new Error(\n `The field name (${field}) can't be the same as an object's private property.`,\n );\n }\n\n return srcEscape(field);\n};\n\nexports.fieldEscape = fieldEscape;\n fieldName = helpers.fieldEscape(fields[i].name);\n // parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);\n lvalue = `result[${helpers.fieldEscape(fields[i].table + options.nestTables + fields[i].name)}]`;\n tableName = helpers.fieldEscape(fields[i].table);\n\n parserFn(`result[${helpers.fieldEscape(resultTablesArray[i])}] = {};`);\n let tableName = '';\n fieldName = helpers.fieldEscape(fields[i].name);\n // parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);\n lvalue = `result[${helpers.fieldEscape(fields[i].table + options.nestTables + fields[i].name)}]`;\n tableName = helpers.fieldEscape(fields[i].table);\n\n parserFn(`if (!result[${tableName}]) result[${tableName}] = {};`);\n lvalue = `result[${tableName}][${fieldName}]`;\n { name: prop, table: '' },\n `The field name (${fields[0].name}) can't be the same as an object's private property.`,\n\nblockedFields\n .map((fields) =>\n fields.map((field) => ({ ...field, name: field.name.slice(1) })),\n )\n .forEach((fields) => {\n try {\n getBinaryParser(fields, { nestTables: '_' }, {});\n assert.fail('An error was expected');\n } catch (error) {\n assert.strictEqual(\n error.message,\n `The field name (_${fields[0].name}) can't be the same as an object's private property.`,\n `Ensure safe _${fields[0].name} for nestTables as string`,\n );\n }\n });\n\nblockedFields\n .map((fields) =>\n fields.map((field) => ({ ...field, name: '', table: field.name })),\n )\n .forEach((fields) => {\n try {\n getBinaryParser(fields, { nestTables: true }, {});\n assert.fail('An error was expected');\n } catch (error) {\n assert.strictEqual(\n error.message,\n `The field name (${fields[0].table}) can't be the same as an object's private property.`,\n `Ensure safe ${fields[0].table} for nestTables as true`,\n );\n }\n });\n { name: prop, table: '' },\n `The field name (${fields[0].name}) can't be the same as an object's private property.`,\n\nblockedFields\n .map((fields) =>\n fields.map((field) => ({ ...field, name: field.name.slice(1) })),\n )\n .forEach((fields) => {\n try {\n TextRowParser(fields, { nestTables: '_' }, {});\n assert.fail('An error was expected');\n } catch (error) {\n assert.strictEqual(\n error.message,\n `The field name (_${fields[0].name}) can't be the same as an object's private property.`,\n `Ensure safe _${fields[0].name} for nestTables as string`,\n );\n }\n });\n\nblockedFields\n .map((fields) =>\n fields.map((field) => ({ ...field, name: '', table: field.name })),\n )\n .forEach((fields) => {\n try {\n TextRowParser(fields, { nestTables: true }, {});\n assert.fail('An error was expected');\n } catch (error) {\n assert.strictEqual(\n error.message,\n `The field name (${fields[0].table}) can't be the same as an object's private property.`,\n `Ensure safe ${fields[0].table} for nestTables as true`,\n );\n }\n });"
}
|
{
"source": "CVEFixes"
}
|
CVE-2019-16347
|
C
|
{
"vulnerable_code": " * (c) 2004-2017 Thomas Bernard. All rights reserved\n\t\t\tif(context->curY >= p->height) {\n\t\t\t\tcontext->pass++;\n\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t}\n\t\t\tif(context->curY >= p->height) {\n\t\t\t\tcontext->pass++;\n\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t}\n\t\t\tif(context->curY >= p->height) {\n\t\t\t\tcontext->pass++;\n\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t}\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\t}\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\t}\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\t}"
}
|
{
"secure_code": " * (c) 2004-2019 Thomas Bernard. All rights reserved\n\t\twhile(context->pass > 0 && context->pass < 4 &&\n\t\t context->curY >= p->height) {\n\t\t\tswitch(++context->pass) {\n\t\t\tcase 2:\t/* 2nd pass : every eighth row starting from 4 */\n\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\tbreak;\n\t\t\tcase 3:\t/* 3rd pass : every fourth row starting from 2 */\n\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\tbreak;\n\t\t\tcase 4:\t/* 4th pass : every odd row */\n\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\twhile(context->pass > 0 && context->pass < 4 &&\n\t\t\t context->curY >= p->height) {\n\t\t\t\tswitch(++context->pass) {\n\t\t\t\tcase 2:\t/* 2nd pass : every eighth row starting from 4 */\n\t\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\t/* 3rd pass : every fourth row starting from 2 */\n\t\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\t/* 4th pass : every odd row */\n\t\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2014-9803
|
C
|
{
"vulnerable_code": "#define PAGE_EXECONLY\t\t__pgprot(_PAGE_DEFAULT | PTE_NG | PTE_PXN)\n#define __P100 PAGE_EXECONLY\n#define __S100 PAGE_EXECONLY\n#define pte_valid_ng(pte) \\\n\t((pte_val(pte) & (PTE_VALID | PTE_NG)) == (PTE_VALID | PTE_NG))\n\tif (pte_valid_ng(pte)) {\n\t * occurred.\n\tunsigned long vm_flags = VM_READ | VM_WRITE;"
}
|
{
"secure_code": "#define __P100 PAGE_READONLY_EXEC\n#define __S100 PAGE_READONLY_EXEC\n#define pte_valid_user(pte) \\\n\t((pte_val(pte) & (PTE_VALID | PTE_USER)) == (PTE_VALID | PTE_USER))\n\tif (pte_valid_user(pte)) {\n\t * occurred. If we encountered a write or exec fault, we must have\n\t * appropriate permissions, otherwise we allow any permission.\n\tunsigned long vm_flags = VM_READ | VM_WRITE | VM_EXEC;"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-1283
|
C
|
{
"vulnerable_code": "\twhile (true) {"
}
|
{
"secure_code": "\twhile (entries) {\n\tif (!bin->entry_table) {\n\t\treturn NULL;\n\t}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2014-3990
|
PHP
|
{
"vulnerable_code": "\t\tif (!$option) {\n\t\tif ((int)$qty && ((int)$qty > 0)) {"
}
|
{
"secure_code": "\t\tif (!$option || !is_array($option)) {\n\t\tif ((int)$qty && ((int)$qty > 0) && isset($this->session->data['cart'][$key])) {"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-21687
|
Go
|
{
"vulnerable_code": " if ! go version | egrep -q 'go(1\\.1[56])' ; then"
}
|
{
"secure_code": " if ! go version | egrep -q 'go1\\.(1[5-9]|[2-9][0-9]{1})' ; then\n\t\"net/url\"\n\n\tif err := flag.Set(\"database\", url.QueryEscape(migrationContext.DatabaseName)); err != nil {\n\t\tmigrationContext.Log.Fatale(err)\n\t}\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2024-21667
|
PHP
|
{
"vulnerable_code": "class GDPRDataController extends UserAwareController"
}
|
{
"secure_code": "use Pimcore\\Controller\\KernelControllerEventInterface;\nuse Symfony\\Component\\HttpKernel\\Event\\ControllerEvent;\nclass GDPRDataController extends UserAwareController implements KernelControllerEventInterface\n public function onKernelControllerEvent(ControllerEvent $event): void\n {\n $this->checkPermission('gdpr_data_extractor');\n }\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2016-1222
|
PHP
|
{
"vulnerable_code": "\t<form class=\"form-horizontal\" name=\"contactform\" role=\"form\" method=\"post\" action=\"<?php echo $_SERVER[\"PHP_SELF\"]; ?>\">\n\t<form class=\"form-horizontal\" name=\"contactform\" role=\"form\" method=\"post\" action=\"<?php echo $_SERVER[\"PHP_SELF\"]; ?>\" novalidate>"
}
|
{
"secure_code": "\t<form class=\"form-horizontal\" name=\"contactform\" role=\"form\" method=\"post\" action=\"<?php echo htmlspchar($_SERVER['PHP_SELF']); ?>\">\n\t<form class=\"form-horizontal\" name=\"contactform\" role=\"form\" method=\"post\" action=\"<?php echo htmlspchar($_SERVER['PHP_SELF']); ?>\" novalidate>"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-39188
|
C
|
{
"vulnerable_code": "\n#else\n\nstatic inline void\ntlb_update_vma_flags(struct mmu_gather *tlb, struct vm_area_struct *vma) { }\n\n#endif\n\n#endif /* CONFIG_MMU_GATHER_NO_RANGE */\n\n\tif (tlb->fullmm || IS_ENABLED(CONFIG_MMU_GATHER_MERGE_VMAS))\n\t * Do a TLB flush and reset the range at VMA boundaries; this avoids\n\t * the ranges growing with the unused space between consecutive VMAs,\n\t * but also the mmu_gather::vma_* flags from tlb_start_vma() rely on\n\t * this.\n\ttlb_flush_mmu_tlbonly(tlb);"
}
|
{
"secure_code": "\tunsigned int\t\tvma_pfn : 1;\n#endif\n\n#endif /* CONFIG_MMU_GATHER_NO_RANGE */\n\ttlb->vma_pfn = !!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP));\n\tif (tlb->fullmm)\n\t * VM_PFNMAP is more fragile because the core mm will not track the\n\t * page mapcount -- there might not be page-frames for these PFNs after\n\t * all. Force flush TLBs for such ranges to avoid munmap() vs\n\t * unmap_mapping_range() races.\n\tif (tlb->vma_pfn || !IS_ENABLED(CONFIG_MMU_GATHER_MERGE_VMAS)) {\n\t\t/*\n\t\t * Do a TLB flush and reset the range at VMA boundaries; this avoids\n\t\t * the ranges growing with the unused space between consecutive VMAs.\n\t\t */\n\t\ttlb_flush_mmu_tlbonly(tlb);\n\t}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-0565
|
PHP
|
{
"vulnerable_code": " if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), '<script')) {\n throw new \\Exception('Scripts in SVG files are not supported');\n }\n $storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));"
}
|
{
"secure_code": "use Symfony\\Component\\Mime\\MimeTypes;\nuse enshrined\\svgSanitize\\Sanitizer;\n\n $sourcePath = $_FILES['Filedata']['tmp_name'];\n\n $fileMimeType = MimeTypes::getDefault()->guessMimeType($sourcePath);\n\n if ($fileMimeType === 'image/svg+xml') {\n $fileContent = file_get_contents($sourcePath);\n\n $sanitizer = new Sanitizer();\n $sanitizedFileContent = $sanitizer->sanitize($fileContent);\n if ($sanitizedFileContent) {\n $storage->write(self::CUSTOM_LOGO_PATH, $sanitizedFileContent);\n }else{\n throw new \\Exception('SVG Sanitization failed, probably due badly formatted XML. Filename:'.$sourcePath);\n }\n }else {\n $storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($sourcePath, 'rb'));\n }\n<?php\n\n/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */\n\nnamespace Pimcore\\Bundle\\CoreBundle\\EventListener;\n\n\nuse Pimcore\\Event\\AssetEvents;\nuse Pimcore\\Event\\Model\\ElementEventInterface;\nuse Pimcore\\Model\\Asset;\nuse Symfony\\Component\\EventDispatcher\\EventSubscriberInterface;\nuse enshrined\\svgSanitize\\Sanitizer;\nuse Symfony\\Component\\Mime\\MimeTypes;\n\n/**\n * @internal\n */\nclass AssetSanitizationListener implements EventSubscriberInterface\n{\n public static function getSubscribedEvents()\n {\n return [\n AssetEvents::PRE_ADD => 'sanitizeAsset',\n AssetEvents::PRE_UPDATE => 'sanitizeAsset',\n ];\n }\n\n /**\n * @param ElementEventInterface $e\n */\n public function sanitizeAsset(ElementEventInterface $e)\n {\n $element = $e->getElement();\n\n if ($element instanceof Asset\\Image && $element->getDataChanged()) {\n $assetStream = $element->getStream();\n\n if (isset($assetStream)) {\n $streamMetaData = stream_get_meta_data($assetStream);\n $mime = MimeTypes::getDefault()->guessMimeType($streamMetaData['uri']);\n\n if ($mime === 'image/svg+xml') {\n $sanitizedData = $this->sanitizeSVG(stream_get_contents($assetStream));\n $element->setData($sanitizedData);\n }\n }\n }\n }\n\n /**\n * @param string $fileContent\n *\n * @return string\n *\n * @throws \\Exception\n */\n\n protected function sanitizeSVG(string $fileContent)\n {\n $sanitizer = new Sanitizer();\n $sanitizedFileContent = $sanitizer->sanitize($fileContent);\n\n if (!$sanitizedFileContent) {\n throw new \\Exception('SVG Sanitization failed, probably due badly formatted XML.');\n }\n\n return $sanitizedFileContent;\n }\n}\n\n Pimcore\\Bundle\\CoreBundle\\EventListener\\AssetSanitizationListener: ~\n \"enshrined/svg-sanitize\": \"^0.14.1\","
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-38511
|
PHP
|
{
"vulnerable_code": "\t\t$sDashboardFileSanitized = utils::RealPath($sDashboardFile, APPROOT);\n\t\t$sFile = addslashes($this->sDefinitionFile);"
}
|
{
"secure_code": "\t\t$sDashboardFileSanitized = utils::RealPath(APPROOT.$sDashboardFile, APPROOT);\n\t\t$sFile = addslashes(utils::LocalPath($this->sDefinitionFile));"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-22467
|
JavaScript
|
{
"vulnerable_code": " .replace(/\\([^)]*\\)|[\\n\\t]/g, \" \")"
}
|
{
"secure_code": " .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-24773
|
JavaScript
|
{
"vulnerable_code": " return _fromDer(bytes, bytes.length(), 0, options);\n key.verify = function(digest, signature, scheme) {\n var obj = asn1.fromDer(d);\n return digest === obj.value[1].value;"
}
|
{
"secure_code": "### Security\n- **SECURITY**: Three RSA PKCS#1 v1.5 signature verification issues were\n reported by Moosa Yahyazadeh (moosa-yahyazadeh@uiowa.edu).\n - Leniency in checking `digestAlgorithm` structure can lead to signature\n forgery.\n - The code is lenient in checking the digest algorithm structure. This can\n allow a crafted structure that steals padding bytes and uses unchecked\n portion of the PKCS#1 encoded message to forge a signature when a low\n public exponent is being used. For more information, please see\n [\"Bleichenbacher's RSA signature forgery based on implementation\n error\"](https://mailarchive.ietf.org/arch/msg/openpgp/5rnE9ZRN1AokBVj3VqblGlP63QE/)\n by Hal Finney.\n - Failing to check tailing garbage bytes can lead to signature forgery.\n - The code does not check for tailing garbage bytes after decoding a\n `DigestInfo` ASN.1 structure. This can allow padding bytes to be removed\n and garbage data added to forge a signature when a low public exponent is\n being used. For more information, please see [\"Bleichenbacher's RSA\n signature forgery based on implementation\n error\"](https://mailarchive.ietf.org/arch/msg/openpgp/5rnE9ZRN1AokBVj3VqblGlP63QE/)\n by Hal Finney.\n - Leniency in checking type octet.\n - `DigestInfo` is not properly checked for proper ASN.1 structure. This can\n lead to successful verification with signatures that contain invalid\n structures but a valid digest.\n\n- [asn1] `fromDer` is now more strict and will default to ensuring all input\n bytes are parsed or throw an error. A new option `parseAllBytes` can disable\n this behavior.\n - **NOTE**: The previous behavior is being changed since it can lead to\n security issues with crafted inputs. It is possible that code doing custom\n DER parsing may need to adapt to this new behavior and optional flag.\n- [rsa] Add and use a validator to check for proper structure of parsed ASN.1\n `RSASSA-PKCS-v1_5` `DigestInfo` data. Additionally check that the hash\n algorithm identifier is a known value. An invalid `DigestInfo` or algorithm\n identifier will now cause an error to be thrown.\n\n### Added\n- [oid] Added `1.2.840.113549.2.2` / `md2` for hash algorithm checking.\n * [parseAllBytes] true to ensure all bytes are parsed\n * (default: true)\n * @throws Will throw an error for various malformed input conditions.\n *\n parseAllBytes: true,\n parseAllBytes: true,\n if(!('parseAllBytes' in options)) {\n options.parseAllBytes = true;\n }\n var byteCount = bytes.length();\n var value = _fromDer(bytes, bytes.length(), 0, options);\n if(options.parseAllBytes && bytes.length() !== 0) {\n var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');\n error.byteCount = byteCount;\n error.remaining = bytes.length();\n throw error;\n }\n return value;\n_IN('1.2.840.113549.2.2', 'md2');\n// validator for a DigestInfo structure\nvar digestInfoValidator = {\n name: 'DigestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'algorithmIdentifier'\n }, {\n // NULL paramters\n name: 'DigestInfo.DigestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.NULL,\n constructed: false\n }]\n }, {\n // digest\n name: 'DigestInfo.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'digest'\n }]\n};\n\n * @param options optional verify options\n * _parseAllDigestBytes testing flag to control parsing of all\n * digest bytes. Unsupported and not for general usage.\n * (default: true)\n key.verify = function(digest, signature, scheme, options) {\n if(options === undefined) {\n options = {\n _parseAllDigestBytes: true\n };\n }\n if(!('_parseAllDigestBytes' in options)) {\n options._parseAllDigestBytes = true;\n }\n var obj = asn1.fromDer(d, {\n parseAllBytes: options._parseAllDigestBytes\n });\n\n // validate DigestInfo\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {\n var error = new Error(\n 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +\n 'DigestInfo value.');\n error.errors = errors;\n throw error;\n }\n // check hash algorithm identifier\n // FIXME: add support to vaidator for strict value choices\n var oid = asn1.derToOid(capture.algorithmIdentifier);\n if(!(oid === forge.oids.md2 ||\n oid === forge.oids.md5 ||\n oid === forge.oids.sha1 ||\n oid === forge.oids.sha256 ||\n oid === forge.oids.sha384 ||\n oid === forge.oids.sha512)) {\n var error = new Error(\n 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');\n error.oid = oid;\n throw error;\n }\n\n return digest === capture.digest;\nvar JSBN = require('../../lib/jsbn');\n\n describe('bad data', function() {\n // params for tests\n\n // public modulus / 256 bytes\n var N = new JSBN.BigInteger(\n 'E932AC92252F585B3A80A4DD76A897C8B7652952FE788F6EC8DD640587A1EE56' +\n '47670A8AD4C2BE0F9FA6E49C605ADF77B5174230AF7BD50E5D6D6D6D28CCF0A8' +\n '86A514CC72E51D209CC772A52EF419F6A953F3135929588EBE9B351FCA61CED7' +\n '8F346FE00DBB6306E5C2A4C6DFC3779AF85AB417371CF34D8387B9B30AE46D7A' +\n '5FF5A655B8D8455F1B94AE736989D60A6F2FD5CADBFFBD504C5A756A2E6BB5CE' +\n 'CC13BCA7503F6DF8B52ACE5C410997E98809DB4DC30D943DE4E812A47553DCE5' +\n '4844A78E36401D13F77DC650619FED88D8B3926E3D8E319C80C744779AC5D6AB' +\n 'E252896950917476ECE5E8FC27D5F053D6018D91B502C4787558A002B9283DA7',\n 16);\n\n // private exponent\n var d = new JSBN.BigInteger(\n '009b771db6c374e59227006de8f9c5ba85cf98c63754505f9f30939803afc149' +\n '8eda44b1b1e32c7eb51519edbd9591ea4fce0f8175ca528e09939e48f37088a0' +\n '7059c36332f74368c06884f718c9f8114f1b8d4cb790c63b09d46778bfdc4134' +\n '8fb4cd9feab3d24204992c6dd9ea824fbca591cd64cf68a233ad0526775c9848' +\n 'fafa31528177e1f8df9181a8b945081106fd58bd3d73799b229575c4f3b29101' +\n 'a03ee1f05472b3615784d9244ce0ed639c77e8e212ab52abddf4a928224b6b6f' +\n '74b7114786dd6071bd9113d7870c6b52c0bc8b9c102cfe321dac357e030ed6c5' +\n '80040ca41c13d6b4967811807ef2a225983ea9f88d67faa42620f42a4f5bdbe0' +\n '3b',\n 16);\n\n // public exponent\n var e = new JSBN.BigInteger('3');\n\n // hash function\n // H = SHA-256 (OID = 0x608648016503040201)\n\n // message\n var m = 'hello world!';\n\n // to-be-signed RSA PKCS#1 v1.5 signature scheme input structure\n // I\n\n // signature value obtained by I^d mod N\n // S\n\n function _checkBadTailingGarbage(publicKey, S) {\n var md = MD.sha256.create();\n md.update(m);\n\n ASSERT.throws(function() {\n publicKey.verify(md.digest().getBytes(), S);\n }, {\n message: 'Unparsed DER bytes remain after ASN.1 parsing.'\n });\n }\n\n function _checkBadDigestInfo(publicKey, S, skipTailingGarbage) {\n var md = MD.sha256.create();\n md.update(m);\n\n ASSERT.throws(function() {\n publicKey.verify(md.digest().getBytes(), S, undefined, {\n _parseAllDigestBytes: !skipTailingGarbage\n });\n }, {\n message: 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.'\n });\n }\n\n it('should check DigestInfo structure', function() {\n var publicKey = RSA.setPublicKey(N, e);\n var S = UTIL.binary.hex.decode(\n 'e7410e05bdc38d1c72fab784be41df3d3de2ae83894d9ec86cb5fe343d5dc7d45df2a36fc60363faf32f0d37ab457648af40a48a6c53ae7af0575e92cb1ffc236d55e1325af8c71b3ac313f2630fb498b8e1546093aca1ed56026a96cb525d991159a2d6ccbfd5ef63ae718f8ace2469e357ccf3f6a048bbf9760f5fb36b9dd38fb330eab504f05078b83f5d8bd95dce8fccc6b46babd56f678300f2b39083e53e04e79f503358a6222f8dd66b561fea3a51ecf3be16c9e2ea6ba8aaed9fbe6ba510ff752e4529385f759d4d6120b15f65534248ed5bbb1307a7d0a9838329697f5fbae91f48e478dcbb77190f0d173b6cb8b1299cf4202570d25d11a7862b47');\n\n _checkBadDigestInfo(publicKey, S);\n });\n\n it('should check tailing garbage and DigestInfo [1]', function() {\n var publicKey = RSA.setPublicKey(N, e);\n var S = UTIL.binary.hex.decode(\n 'c2ad2fa23c246ee98c453d69023e7ec05956b48bd0e287341ba9d342ad49b0fff2bcbb9adc50f1ccbfc54106305cc74a88db89ff94901a08359893a08426373e7949a8794798233445af6c48bc6ccbe278bdeb62c31e40c3bf0014af2faadcc9ed7885756789a5b95c2a355fbb3f04412f42e0f9ed335ab51af8f091a62aaaaf6577422220917daaece3ca2f4e66dc4e0574356762592052b406768c31c25cf4c1754e6da9dc3440e238c4f9b25cccc174dd1b17b027e0f9ce2763b86f0e6871690ddd018d2e774bc968c9c6e907a000daf5044ba31a0b9eefbd7b4b1ec466d20bc1dd3f020cb1091af6b476416da3024ea046b09fbbbc4d2355da9a2bc6ddb9');\n\n _checkBadTailingGarbage(publicKey, S);\n _checkBadDigestInfo(publicKey, S, true);\n });\n\n it('should check tailing garbage and DigestIfno [2]', function() {\n var publicKey = RSA.setPublicKey(N, e);\n var S = UTIL.binary.hex.decode(\n 'a7c5812d7fc0eef766a481aac18c8c48483daf9b5ffb6614bd98ebe4ecb746dd493cf5dd2cbe16ecaa0b52109b744930eda49316605fc823fd57a68b5b2c62e8c1b158b26e1547a2e33cdd79427d7c513f07d02261ffe43db197d8cddca2b5b43c1df85aaed6e91aadd44a46bff7f5c70f1acc1a193917e3908444632f30e69cfe95d8036d3b6ad318eefd3952804f16613c969e6d13604bb4e723dfad24c42c8d9b5b16a9f5a4b40dcf17b167d319017740f9cc0836436c14d51c3d8a697f1fa2b65196deb5c21b1559c7dea7f598007fa7320909825009f8bf376491c298d8155a382e967042db952e995d14b2f961e1b22f911d1b77895def1c7ef229c87e');\n\n _checkBadTailingGarbage(publicKey, S);\n _checkBadDigestInfo(publicKey, S, true);\n });\n\n it('should check tailing garbage and DigestInfo [e=3]', function() {\n var N = new JSBN.BigInteger(\n '29438513389594867490232201282478838726734464161887801289068585100507839535636256317277708295678804401391394313946142335874609638666081950936114152574870224034382561784743283763961349980806819078028975594777103388280272392844112380900374508170221075553517641170327441791034393719271744724924194371070527213991317221667249077972700842199037403799480569910844701030644322616045408039715278394572328099192023924503077673178227614549351191204851805076359472439160130994385433568113626206477097769842080459156024112389406200687233341779381667082591421496870666931268548504674362230725756397511775557878046572472650613407143');\n var e = new JSBN.BigInteger('3');\n var publicKey = RSA.setPublicKey(N, e);\n\n var S = UTIL.binary.hex.decode(\n '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002853ccc2cd32a8d430dd3bde37e70782ac82cdb7bce3c044219b50aefd689c20d3b840299f28e2fde6c67c8a7f9e528ac222fae947a6dee0d812e3c3b3452171717396e8bedc3132d92d8317e3593642640d1431ef');\n\n _checkBadTailingGarbage(publicKey, S);\n _checkBadDigestInfo(publicKey, S, true);\n });\n\n it('should check tailing garbage and DigestInfo [e=5]', function() {\n var N = new JSBN.BigInteger(\n '29438513389594867490232201282478838726734464161887801289068585100507839535636256317277708295678804401391394313946142335874609638666081950936114152574870224034382561784743283763961349980806819078028975594777103388280272392844112380900374508170221075553517641170327441791034393719271744724924194371070527213991317221667249077972700842199037403799480569910844701030644322616045408039715278394572328099192023924503077673178227614549351191204851805076359472439160130994385433568113626206477097769842080459156024112389406200687233341779381667082591421496870666931268548504674362230725756397511775557878046572472650613407143');\n var e = new JSBN.BigInteger('5');\n var publicKey = RSA.setPublicKey(N, e);\n\n var S = UTIL.binary.hex.decode(\n '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005475fe2681d7125972bd2c2f2c7ab7b8003b03d4a487d6dee07c14eb5212a9fe0071b93f84ba5bb4b0cfaf20c976b11d902013');\n\n _checkBadTailingGarbage(publicKey, S);\n _checkBadDigestInfo(publicKey, S, true);\n });\n\n it('should check tailing garbage and DigestInfo [e=17]', function() {\n var N = new JSBN.BigInteger(\n '928365641661298526294114382771769657905695995680009680444002258089796055192245321020911051590379097587133341820043795407471021630328875171430160513961779154294247563032373839871165519961382202811828883364651574763124699947662060849683176689286181021501400261976653416725246403933613615758181648971537689642956474563961490989544033629566558036444831495046301215543198107208071526376318961481739278769122885031686763776874806317352741548232110892401401727195758835975800106904020775937891505819798776295294696516670437057465296389148672556848624501468669295285428387365416747516180652630054765393335211528084329716917821726670549155619986875030049107668205064454104328601041931972319966348825621299693193542460060799067674344247887198933507132592770898312271636011037138984729256515515185153334743685479709085410902269777563691615719884708908509618352792737826421059819474305949001978916949447029010362775778664826653636547333219983468955600305523140183269580452792812503399042201081785972707218144968460623663922470814889738564730816412201128810370324070680245854669130551872958017494277468722193869883705529583737211815974801292292728082721785855274147991979220001018156560009927148374995236030383474031418802554714043680969417015155298092390680188406177667101020936206754551985229636814788735090951246816765035721775759652424641736739668936540450232814857289312589998505627375553038062765493408460941597629291231866042662108291164359496334978563287523685872262509560463225096226739991402761266388226652661345282274508037924611589455395655512013078629375186805951823181371561289129616028768733583565439798508002546685505512478002960132511531323264596144585611962969372672455541953777622436993987703564293487820434112162562492086865147598436647725445230861246093950020099084994990632102506848190196407855705745530407617253129971665939853842224965079537303198339986953399517682750248394628026225887174258267456078564070387327653989505416943226163989004419377363130466566387761757272563996086708621913140580687414698126490572618509858141748692837570235128900627675422927964369356691123905362222855545719945605604307263252851081309622569225811979426856464673233875589085773616373798857001344093594417138323005260179781153950803127773817702016534081581157881295739782000814998795398671806283018844936919299070562538763900037469485135699677248580365379125702903186174995651938469412191388327852955727869345476087173047665259892129895247785416834855450881318585909376917039');\n var e = new JSBN.BigInteger('17');\n var publicKey = RSA.setPublicKey(N, e);\n\n var S = UTIL.binary.hex.decode(\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001eb90acbec1bf590ba1e50960db8381fb5bdc363d46379d09956560a616b88616ce7fa4309dc45f47f5fa47d61bf66baa3d11732ce71768ded295f962');\n\n _checkBadTailingGarbage(publicKey, S);\n _checkBadDigestInfo(publicKey, S, true);\n });\n\n it('should check DigestInfo type octet [1]', function() {\n var publicKey = RSA.setPublicKey(N, e);\n var S = UTIL.binary.hex.decode(\n 'd8298a199e1b6ac18f3c0067a004bd9ff7af87be6ad857d73cc3d24ef06195b82aaddb0194f8e61fc31453b9163062255e8baf9c480200d0991a5f764f63d5f6afd283b9cd6afe54f0b7f738707b4eb6b8807539bb627e74db87a50413ab18e504e37975aad1edc612bc8ecad53b81ea249deb5a2acc27e6419c61ab9acec6608f5ae6a2985ba0b6f42d831bc6cce4b044864154b935cf179967d129e0ad8eda9bfbb638121c3ff13c64d439632e62250d4be928a3deb112ef76a025c5d918051e601878eac0049fc9d82be9ae3475deb7ca515c830c20b91b7bedf2184fef66aea0bde62ccd1659afbfd1342322b095309451b1a87e007e640e368fb68a13c9');\n\n _checkBadDigestInfo(publicKey, S);\n });\n\n it('should check DigestInfo type octet [2]', function() {\n var publicKey = RSA.setPublicKey(N, e);\n var S = UTIL.binary.hex.decode(\n 'c1acdd3aef5f0439c254980295fc0d81b628df00726310a1041d79b5dd94c11d3bcaf0236763c77c25d9ab49522ed2a7d6ea3a4e483a29838acd48f2d60a790275f4cd46e4b1d09c527a426ec373e8a21746ad3ea541d3b85ba4c303ff793ea8a0a3458e93a7ec42ed66f675d7c299b0817ac95f7f45b2f48c09b3c070171f31a33ac789da9943da5dabcda1c95b42531d45484ac1efde0fe0519077debb93183e63de8f80d7f3cbfecb03cbb44ac4a2d56699e33fca0663b79ca627755fc4fc684b4ab358a0b4ac5b7e9d0cc18b6ab6300b40781502a1c03d34f31dd19d81195f8a44bc03a2595a706f06f0cb39b8e3f4afe06675fe7439b057f1200a06f4fd');\n\n _checkBadDigestInfo(publicKey, S);\n });\n });"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-36105
|
PHP
|
{
"vulnerable_code": "class AuthenticationService extends AbstractAuthenticationService"
}
|
{
"secure_code": " // mimic user authentication to mitigate observable timing discrepancies\n // @link https://cwe.mitre.org/data/definitions/208.html\n } elseif ($activeLogin) {\n $subType = 'authUser' . $this->loginType;\n foreach ($this->getAuthServices($subType, $loginData, $authInfo) as $serviceObj) {\n if ($serviceObj instanceof MimicServiceInterface && $serviceObj->mimicAuthUser() === false) {\n break;\n }\n }\nclass AuthenticationService extends AbstractAuthenticationService implements MimicServiceInterface\n /**\n * Mimics password hashing for invalid authentication requests to mitigate\n * @link https://cwe.mitre.org/data/definitions/208.html: CWE-208: Observable Timing Discrepancy\n */\n public function mimicAuthUser(): bool\n {\n try {\n $hashFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);\n $defaultHashInstance = $hashFactory->getDefaultHashInstance($this->pObj->loginType);\n $defaultHashInstance->getHashedPassword(random_bytes(10));\n } catch (\\Exception) {\n // no further processing here\n }\n return false;\n }\n\n<?php\n\ndeclare(strict_types=1);\n\n/*\n * This file is part of the TYPO3 CMS project.\n *\n * It is free software; you can redistribute it and/or modify it under\n * the terms of the GNU General Public License, either version 2\n * of the License, or any later version.\n *\n * For the full copyright and license information, please read the\n * LICENSE.txt file that was distributed with this source code.\n *\n * The TYPO3 project - inspiring people to share!\n */\n\nnamespace TYPO3\\CMS\\Core\\Authentication;\n\ninterface MimicServiceInterface\n{\n /**\n * Mimics user authentication for known invalid authentication requests. This method can be used\n * to mitigate timing discrepancies for invalid authentication attempts, which can be used for\n * user enumeration.\n *\n * Authentication services can implement this method to simulate(!) corresponding processes that\n * would be processed during valid requests - e.g. perform password hashing (timing) or call\n * remote services (network latency).\n *\n * @return bool whether other services shall continue\n * @link https://cwe.mitre.org/data/definitions/208.html: CWE-208: Observable Timing Discrepancy\n */\n public function mimicAuthUser(): bool;\n}"
}
|
{
"source": "CVEFixes"
}
|
CVE-2023-25654
|
PHP
|
{
"vulnerable_code": "\t\tif (is_string($file)) {"
}
|
{
"secure_code": "\t\tif (!empty($file) && is_string($file)) {"
}
|
{
"source": "CVEFixes"
}
|
CVE-2017-9228
|
C
|
{
"vulnerable_code": " *state = CCS_VALUE;"
}
|
{
"secure_code": " if (*state != CCS_START)\n *state = CCS_VALUE;\n"
}
|
{
"source": "CVEFixes"
}
|
CVE-2019-14512
|
PHP
|
{
"vulnerable_code": " - <?=$model->label_name;?>"
}
|
{
"secure_code": " - <?php echo CHtml::encode($model->label_name); ?>"
}
|
{
"source": "CVEFixes"
}
|
CVE-2022-22143
|
JavaScript
|
{
"vulnerable_code": "const ALLOWED_OPTION_STRICT = 'strict'\nconst ALLOWED_OPTION_WARN = 'warn'\n\n if (!(parentKey == '__proto__' || parentKey == 'constructor' || parentKey == 'prototype')) {\n const parent = walk(this._instance, parentKey, true)\n parent[childKey] = v\n }"
}
|
{
"secure_code": "// Forbidden key paths, for protection against prototype pollution\nconst FORBIDDEN_KEY_PATHS = [\n '__proto__',\n 'this.constructor.prototype',\n]\n\nconst ALLOWED_OPTION_STRICT = 'strict'\nconst ALLOWED_OPTION_WARN = 'warn'\n\n for (const path of FORBIDDEN_KEY_PATHS) {\n if (k.startsWith(`${path}.`)) {\n return this\n }\n }\n\n const parent = walk(this._instance, parentKey, true)\n parent[childKey] = v\n'use strict'\n\nconst convict = require('../')\n\ndescribe('Convict prototype pollution resistance', function() {\n\n test('against __proto__', function() {\n const obj = {}\n const config = convict(obj)\n\n config.set('__proto__.polluted_proto_root', 'Polluted!')\n expect({}).not.toHaveProperty('polluted_proto_root')\n\n config.set('__proto__.nested.polluted_proto_nested', 'Polluted!')\n expect({}).not.toHaveProperty('nested')\n expect({}).not.toHaveProperty('nested.polluted_proto_nested')\n })\n\n test('against this.constructor.prototype', function() {\n const obj = {}\n const config = convict(obj)\n\n config.set('this.constructor.prototype.polluted_constructor_prototype_root', 'Polluted!')\n expect({}).not.toHaveProperty('polluted_constructor_prototype_root')\n\n config.set('this.constructor.prototype.nested.polluted_constructor_prototype_nested', 'Polluted!')\n expect({}).not.toHaveProperty('nested')\n expect({}).not.toHaveProperty('nested.polluted_constructor_prototype_nested')\n })\n\n})"
}
|
{
"source": "CVEFixes"
}
|
CVE-2021-43114
|
C
|
{
"vulnerable_code": "#!/bin/bash"
}
|
{
"secure_code": "#!/bin/sh\n#include <pthread.h>"
}
|
{
"source": "CVEFixes"
}
|
CVE-2021-37668
|
Python
|
{
"vulnerable_code": " \"index is out of bound as with dims\"):"
}
|
{
"secure_code": " // Make sure dims does not contain a zero\n for (int i = 0; i < dims.size(); i++) {\n OP_REQUIRES(\n ctx, dims(i) != 0,\n errors::InvalidArgument(\"Input dims cannot contain a dim of zero, \"\n \"but dims contains zero at index \",\n i));\n }\n \"dims cannot contain a dim of zero\"):"
}
|
{
"source": "CVEFixes"
}
|
CVE-2020-11958
|
C++
|
{
"vulnerable_code": " shift_ptrs_and_fpos(buf - bot);"
}
|
{
"secure_code": " shift_ptrs_and_fpos(buf - tok);\n DASSERT(lim + free <= bot + BSIZE);"
}
|
{
"source": "CVEFixes"
}
|
CVE-2011-1833
|
C
|
{
"vulnerable_code": "static int ecryptfs_parse_options(struct ecryptfs_sb_info *sbi, char *options)\n\trc = ecryptfs_parse_options(sbi, raw_data);"
}
|
{
"secure_code": " ecryptfs_opt_check_dev_ruid,\n\t{ecryptfs_opt_check_dev_ruid, \"ecryptfs_check_dev_ruid\"},\n * @check_ruid: set to 1 if device uid should be checked against the ruid\nstatic int ecryptfs_parse_options(struct ecryptfs_sb_info *sbi, char *options,\n\t\t\t\t uid_t *check_ruid)\n\t*check_ruid = 0;\n\n\t\tcase ecryptfs_opt_check_dev_ruid:\n\t\t\t*check_ruid = 1;\n\t\t\tbreak;\n\tuid_t check_ruid;\n\trc = ecryptfs_parse_options(sbi, raw_data, &check_ruid);\n\n\tif (check_ruid && path.dentry->d_inode->i_uid != current_uid()) {\n\t\trc = -EPERM;\n\t\tprintk(KERN_ERR \"Mount of device (uid: %d) not owned by \"\n\t\t \"requested user (uid: %d)\\n\",\n\t\t path.dentry->d_inode->i_uid, current_uid());\n\t\tgoto out_free;\n\t}\n"
}
|
{
"source": "CVEFixes"
}
|
Secure Code Repair (SFT)
π Overview
Secure Code Repair (SFT) is a high-quality supervised fine-tuning dataset designed to train large language models to repair vulnerable source code by transforming insecure implementations into secure and corrected versions.
Each sample consists of real-world vulnerable code paired with its corresponding secure fix. The dataset has been carefully engineered using a strict validation and filtering pipeline to ensure security relevance, correctness, and training stability.
This dataset represents the first training stage (Supervised Fine-Tuning) for secure code generation systems.
π― Motivation
Large Language Models often generate code that is syntactically correct but security-wise unsafe.
The goal of this dataset is to:
- Teach models how to fix vulnerabilities, not just detect them
- Encourage secure coding patterns across multiple languages
- Provide clean and validated examples suitable for academic research and applied security systems
ποΈ Data Sources
This dataset is derived from:
- CVEFixes β a curated collection of real-world vulnerability patches linked to CVEs
All samples were processed using a custom data engineering pipeline that removes:
- Incomplete or empty code examples
- Trivial or cosmetic-only fixes
- Destructive fixes that remove functionality instead of securing it
- Low-quality or inconsistent language samples
π§© Supported Programming Languages
This dataset supports vulnerable-to-secure code transformations for the following programming languages:
- C
- C++
- Python
- Java
- JavaScript
- PHP
- Go
- Ruby
- C#
Only allow-listed languages are included during preprocessing to ensure consistency, reliability, and high-quality training data.
π§± Dataset Structure
Each sample follows the schema below:
{
"id": "CVE-XXXX",
"language": "C",
"input": {
"vulnerable_code": "..."
},
"output": {
"secure_code": "..."
},
"metadata": {
"source": "CVEFixes"
}
}
- Downloads last month
- 22