prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>", "#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/util/util.h\"", "namespace tensorflow {", "namespace {", "// For each slice in `(start, limit)` in `value_slices`, append\n// `params_dense_values_in[start:limit] to `values_out`. `value_size` indicates\n// the number of scalars contained in each value params_dense_values_in[i].\ntemplate <typename VALUE_TYPE, typename SPLITS_TYPE>\nvoid WriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) {\n const auto& params_dense_values =\n params_dense_values_in.flat_outer_dims<VALUE_TYPE, 2>();\n auto values = values_out->flat_outer_dims<VALUE_TYPE, 2>();\n int out_pos = 0;\n for (const auto& slice : value_slices) {\n for (int i = slice.first; i < slice.second; ++i) {\n for (int j = 0; j < value_size; ++j) {\n values(out_pos, j) = params_dense_values(i, j);\n }\n ++out_pos;\n }\n }\n}", "} // namespace", "template <typename INDEX_TYPE, typename SPLITS_TYPE>\nclass RaggedGatherOpBase : public OpKernel {\n public:\n using OpKernel::OpKernel;", " void Compute(OpKernelContext* context) override {\n // Get the input Tensors.", "", " OpInputList params_nested_splits_in;\n OP_REQUIRES_OK(context, context->input_list(\"params_nested_splits\",\n &params_nested_splits_in));", "", " const Tensor& params_dense_values_in =\n context->input(params_nested_splits_in.size());\n const Tensor& indices_in =\n context->input(params_nested_splits_in.size() + 1);\n", " DCHECK_GT(params_nested_splits_in.size(), 0); // Enforced by REGISTER_OP.", " SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;\n OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));", " OP_REQUIRES(context, params_dense_values_in.dims() > 0,\n errors::InvalidArgument(\"params.rank must be nonzero\"));\n SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);", " // Calculate the `splits`, and store the value slices that we need to\n // copy in `value_slices`.\n std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>> value_slices;\n SPLITS_TYPE num_values = 0;\n std::vector<std::vector<SPLITS_TYPE>> out_splits;\n OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,\n num_params_dense_values, &out_splits,\n &value_slices, &num_values));", " // Write the output tensors.\n OP_REQUIRES_OK(context, WriteSplits(out_splits, context));\n OP_REQUIRES_OK(context,\n WriteValues(params_dense_values_in, value_slices,\n out_splits.size(), num_values, context));\n }", " private:\n using ConstFlatType = typename TTypes<SPLITS_TYPE>::ConstFlat;", " // Check if any indices are out-of-bounds.\n ::tensorflow::Status ValidateIndices(const Tensor& indices_in,\n SPLITS_TYPE num_params) {\n const auto& indices = indices_in.flat<INDEX_TYPE>();\n for (SPLITS_TYPE i = 0; i < indices.size(); ++i) {\n SPLITS_TYPE index = indices(i);\n if (index < 0 || index >= num_params) {\n return errors::InvalidArgument(\n \"indices\", SliceDebugString(indices_in.shape(), i), \" = \", index,\n \" is not in [0, \", num_params, \")\");\n }\n }\n return ::tensorflow::Status::OK();\n }", " // Construct the `splits` output tensors, encoded using a nested vector.\n // Also find the slices of values that need to be copied, and store them\n // in `value_slices`. The total number of values that will be copied (which\n // we need for allocating the output values tensor) is stored in `num_values`.\n ::tensorflow::Status MakeSplits(\n const Tensor& indices_in, const OpInputList& params_nested_splits_in,\n SPLITS_TYPE num_params_dense_values,\n std::vector<std::vector<SPLITS_TYPE>>* out_splits,\n std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>* value_slices,\n SPLITS_TYPE* num_values) {\n *num_values = 0;\n value_slices->clear();", " int num_splits = indices_in.dims() - 1 + params_nested_splits_in.size();\n out_splits->assign(num_splits, {0});", " // Get Eigen tensors.\n const auto& indices = indices_in.flat<INDEX_TYPE>();\n std::vector<ConstFlatType> params_nested_splits;\n params_nested_splits.reserve(params_nested_splits_in.size());\n for (const auto& splits_in : params_nested_splits_in) {\n params_nested_splits.push_back(splits_in.flat<SPLITS_TYPE>());\n }", " TF_RETURN_IF_ERROR(\n ValidateSplits(params_nested_splits, num_params_dense_values));", " // Add `splits` that come from all but the last dimension of the dense\n // Tensor `indices`. In particular, for each dimension D, we add a\n // splits tensor whose values are:\n // range(reduce_prod(splits.shape[:D]) + 1) * splits.shape[D+1]\n // E.g., if indices.shape=[2, 3, 4] then we will add splits tensors:\n // [0, 3, 6] # length=2+1, stride=3\n // [0, 4, 8, 12, 16, 20, 24] # length=2*3+1, stride=4\n int nrows = 1;\n for (int dim = 0; dim < indices_in.dims() - 1; ++dim) {\n nrows *= indices_in.dim_size(dim);\n int row_length = indices_in.dim_size(dim + 1);\n for (int i = 1; i < nrows + 1; ++i) {\n out_splits->at(dim).push_back(i * row_length);\n }\n }", " // Add `splits` that come from `params_nested_splits`. Starting with the\n // outermost ragged dimension (i.e., the first `splits` tensor), we work\n // our way in, finding the range of values that should be copied. As we\n // go, we update the output `splits` for each dimension with the appropriate\n // values. In particular, the *lengths* of the slices from `param_splits`\n // should be copied to generate corresponding slice lengths in the output\n // splits. E.g., if we are copying a ragged row with length 4, then we\n // should add a new split point to out_splits that is 4 greater than the\n // previous split point in out_splits.\n for (int i = 0; i < indices.size(); ++i) {\n int start = indices(i);\n int limit = indices(i) + 1;", " // Copy splits.\n for (int dim = 0; dim < params_nested_splits.size(); ++dim) {\n const auto& splits = params_nested_splits[dim];\n int out_dim = dim + indices_in.dims() - 1;\n if (out_dim >= 0) {\n SPLITS_TYPE delta = out_splits->at(out_dim).back() - splits(start);\n for (int j = start; j < limit; ++j) {\n out_splits->at(out_dim).push_back(splits(j + 1) + delta);\n }\n }\n start = splits(start);\n limit = splits(limit);\n }\n if (limit != start) {\n value_slices->emplace_back(start, limit);\n *num_values += limit - start;\n }\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status ValidateSplits(\n const std::vector<ConstFlatType>& params_nested_splits,\n SPLITS_TYPE num_params_dense_values) {\n // Validate\n for (int dim = 0; dim < params_nested_splits.size(); ++dim) {\n const auto& splits = params_nested_splits[dim];\n SPLITS_TYPE last_split = (dim == params_nested_splits.size() - 1)\n ? num_params_dense_values\n : params_nested_splits[dim + 1].size();\n if (splits.size() == 0) {\n return errors::InvalidArgument(\"Ragged splits may not be empty\");\n }\n if (splits(0) < 0) {\n return errors::InvalidArgument(\"Ragged splits must be non-negative\");\n }\n if (splits(splits.size() - 1) > last_split) {\n return errors::InvalidArgument(\n \"Ragged splits must not point past values\");\n }\n for (int i = 1; i < splits.size(); ++i) {\n if (splits(i - 1) > splits(i)) {\n return errors::InvalidArgument(\"Ragged splits must be sorted\");\n }\n }\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status WriteSplits(\n const std::vector<std::vector<SPLITS_TYPE>>& out_splits,\n OpKernelContext* context) {\n OpOutputList splits_out;\n TF_RETURN_IF_ERROR(\n context->output_list(\"output_nested_splits\", &splits_out));\n for (int i = 0; i < out_splits.size(); ++i) {\n Tensor* splits;\n SPLITS_TYPE num_splits = out_splits[i].size();\n TF_RETURN_IF_ERROR(\n splits_out.allocate(i, TensorShape({num_splits}), &splits));\n auto splits_flat = splits->flat<SPLITS_TYPE>();\n std::copy_n(out_splits[i].data(), out_splits[i].size(),\n splits_flat.data());\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status WriteValues(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n int values_index, SPLITS_TYPE num_values,\n OpKernelContext* context) const {\n Tensor* values_out = nullptr;\n TensorShape values_shape = params_dense_values_in.shape();\n values_shape.set_dim(0, num_values);\n TF_RETURN_IF_ERROR(\n context->allocate_output(values_index, values_shape, &values_out));\n const SPLITS_TYPE num_elements = params_dense_values_in.NumElements();\n const SPLITS_TYPE value_size =\n num_elements == 0 ? 0\n : (num_elements / params_dense_values_in.dim_size(0));\n CallWriteValueSlices(params_dense_values_in, value_slices, value_size,\n values_out);\n return ::tensorflow::Status::OK();\n }", " protected:\n // Call WriteValueSlices() using the appropriate VALUE_TYPE template\n // parameter. This pattern is used to reduce binary size. In particular,\n // this allows us to have two instantiations of this class (one for each\n // index type), rather than 14 (one for each index type and value type),\n // which cuts the binary size of this op from ~300k to <90k.\n virtual void CallWriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) const = 0;\n};", "template <typename INDEX_TYPE, typename VALUE_TYPE, typename SPLITS_TYPE>\nclass RaggedGatherOp : public RaggedGatherOpBase<INDEX_TYPE, SPLITS_TYPE> {\n public:\n using RaggedGatherOpBase<INDEX_TYPE, SPLITS_TYPE>::RaggedGatherOpBase;", " private:\n void CallWriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) const override {\n WriteValueSlices<VALUE_TYPE>(params_dense_values_in, value_slices,\n value_size, values_out);\n }\n};", "#define REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(index_type, value_type, \\\n splits_type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"RaggedGather\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<index_type>(\"Tindices\") \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<splits_type>(\"Tsplits\"), \\\n RaggedGatherOp<index_type, value_type, splits_type>);\n#define REGISTER_CPU_KERNEL(value_type) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int32, value_type, int32) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int64, value_type, int32) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int32, value_type, int64) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int64, value_type, int64)\nTF_CALL_POD_TYPES(REGISTER_CPU_KERNEL);\nTF_CALL_tstring(REGISTER_CPU_KERNEL);\nTF_CALL_QUANTIZED_TYPES(REGISTER_CPU_KERNEL);\nTF_CALL_quint16(REGISTER_CPU_KERNEL);\nTF_CALL_qint16(REGISTER_CPU_KERNEL);\n#undef REGISTER_CPU_KERNEL\n#undef REGISTER_CPU_KERNEL_WITH_INDEX_TYPE", "} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [70], "buggy_code_start_loc": [60], "filenames": ["tensorflow/core/kernels/ragged_gather_op.cc"], "fixing_code_end_loc": [76], "fixing_code_start_loc": [61], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas, si los argumentos \"tf.raw_ops.RaggedGather\" no determinan un tensor v\u00e1lido, el c\u00f3digo puede desencadenar una lectura desde fuera de l\u00edmites de los b\u00faferes asignados a la pila. La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) lee directamente la primera dimensi\u00f3n de una forma tensorial antes de comprobar que dicho tensor presenta un rango de al menos 1 (es decir, no es un escalar). Adem\u00e1s, la implementaci\u00f3n no comprueba que la lista dada por \"params_nested_splits\" no sea una lista vac\u00eda de tensores. Hemos parcheado el problema en el commit de GitHub a2b743f6017d7b97af1fe49087ae15f0ac634373. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.5.1, TensorFlow versi\u00f3n 2.4.3, y TensorFlow versi\u00f3n 2.3.4, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37641", "lastModified": "2021-08-18T17:00:51.547", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 3.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:P/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T21:15:07.670", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-9c8h-vvrj-w2p8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373"}, "type": "CWE-125"}
107
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>", "#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/util/util.h\"", "namespace tensorflow {", "namespace {", "// For each slice in `(start, limit)` in `value_slices`, append\n// `params_dense_values_in[start:limit] to `values_out`. `value_size` indicates\n// the number of scalars contained in each value params_dense_values_in[i].\ntemplate <typename VALUE_TYPE, typename SPLITS_TYPE>\nvoid WriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) {\n const auto& params_dense_values =\n params_dense_values_in.flat_outer_dims<VALUE_TYPE, 2>();\n auto values = values_out->flat_outer_dims<VALUE_TYPE, 2>();\n int out_pos = 0;\n for (const auto& slice : value_slices) {\n for (int i = slice.first; i < slice.second; ++i) {\n for (int j = 0; j < value_size; ++j) {\n values(out_pos, j) = params_dense_values(i, j);\n }\n ++out_pos;\n }\n }\n}", "} // namespace", "template <typename INDEX_TYPE, typename SPLITS_TYPE>\nclass RaggedGatherOpBase : public OpKernel {\n public:\n using OpKernel::OpKernel;", " void Compute(OpKernelContext* context) override {\n // Get the input Tensors.", "", " OpInputList params_nested_splits_in;\n OP_REQUIRES_OK(context, context->input_list(\"params_nested_splits\",\n &params_nested_splits_in));", " OP_REQUIRES(\n context, params_nested_splits_in.size() > 0,\n errors::InvalidArgument(\"params_nested_splits must be non empty\"));\n", " const Tensor& params_dense_values_in =\n context->input(params_nested_splits_in.size());\n const Tensor& indices_in =\n context->input(params_nested_splits_in.size() + 1);\n", " OP_REQUIRES(context, params_nested_splits_in[0].dims() > 0,\n errors::InvalidArgument(\"Split tensors must not be scalars\"));", " SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;\n OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));", " OP_REQUIRES(context, params_dense_values_in.dims() > 0,\n errors::InvalidArgument(\"params.rank must be nonzero\"));\n SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);", " // Calculate the `splits`, and store the value slices that we need to\n // copy in `value_slices`.\n std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>> value_slices;\n SPLITS_TYPE num_values = 0;\n std::vector<std::vector<SPLITS_TYPE>> out_splits;\n OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,\n num_params_dense_values, &out_splits,\n &value_slices, &num_values));", " // Write the output tensors.\n OP_REQUIRES_OK(context, WriteSplits(out_splits, context));\n OP_REQUIRES_OK(context,\n WriteValues(params_dense_values_in, value_slices,\n out_splits.size(), num_values, context));\n }", " private:\n using ConstFlatType = typename TTypes<SPLITS_TYPE>::ConstFlat;", " // Check if any indices are out-of-bounds.\n ::tensorflow::Status ValidateIndices(const Tensor& indices_in,\n SPLITS_TYPE num_params) {\n const auto& indices = indices_in.flat<INDEX_TYPE>();\n for (SPLITS_TYPE i = 0; i < indices.size(); ++i) {\n SPLITS_TYPE index = indices(i);\n if (index < 0 || index >= num_params) {\n return errors::InvalidArgument(\n \"indices\", SliceDebugString(indices_in.shape(), i), \" = \", index,\n \" is not in [0, \", num_params, \")\");\n }\n }\n return ::tensorflow::Status::OK();\n }", " // Construct the `splits` output tensors, encoded using a nested vector.\n // Also find the slices of values that need to be copied, and store them\n // in `value_slices`. The total number of values that will be copied (which\n // we need for allocating the output values tensor) is stored in `num_values`.\n ::tensorflow::Status MakeSplits(\n const Tensor& indices_in, const OpInputList& params_nested_splits_in,\n SPLITS_TYPE num_params_dense_values,\n std::vector<std::vector<SPLITS_TYPE>>* out_splits,\n std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>* value_slices,\n SPLITS_TYPE* num_values) {\n *num_values = 0;\n value_slices->clear();", " int num_splits = indices_in.dims() - 1 + params_nested_splits_in.size();\n out_splits->assign(num_splits, {0});", " // Get Eigen tensors.\n const auto& indices = indices_in.flat<INDEX_TYPE>();\n std::vector<ConstFlatType> params_nested_splits;\n params_nested_splits.reserve(params_nested_splits_in.size());\n for (const auto& splits_in : params_nested_splits_in) {\n params_nested_splits.push_back(splits_in.flat<SPLITS_TYPE>());\n }", " TF_RETURN_IF_ERROR(\n ValidateSplits(params_nested_splits, num_params_dense_values));", " // Add `splits` that come from all but the last dimension of the dense\n // Tensor `indices`. In particular, for each dimension D, we add a\n // splits tensor whose values are:\n // range(reduce_prod(splits.shape[:D]) + 1) * splits.shape[D+1]\n // E.g., if indices.shape=[2, 3, 4] then we will add splits tensors:\n // [0, 3, 6] # length=2+1, stride=3\n // [0, 4, 8, 12, 16, 20, 24] # length=2*3+1, stride=4\n int nrows = 1;\n for (int dim = 0; dim < indices_in.dims() - 1; ++dim) {\n nrows *= indices_in.dim_size(dim);\n int row_length = indices_in.dim_size(dim + 1);\n for (int i = 1; i < nrows + 1; ++i) {\n out_splits->at(dim).push_back(i * row_length);\n }\n }", " // Add `splits` that come from `params_nested_splits`. Starting with the\n // outermost ragged dimension (i.e., the first `splits` tensor), we work\n // our way in, finding the range of values that should be copied. As we\n // go, we update the output `splits` for each dimension with the appropriate\n // values. In particular, the *lengths* of the slices from `param_splits`\n // should be copied to generate corresponding slice lengths in the output\n // splits. E.g., if we are copying a ragged row with length 4, then we\n // should add a new split point to out_splits that is 4 greater than the\n // previous split point in out_splits.\n for (int i = 0; i < indices.size(); ++i) {\n int start = indices(i);\n int limit = indices(i) + 1;", " // Copy splits.\n for (int dim = 0; dim < params_nested_splits.size(); ++dim) {\n const auto& splits = params_nested_splits[dim];\n int out_dim = dim + indices_in.dims() - 1;\n if (out_dim >= 0) {\n SPLITS_TYPE delta = out_splits->at(out_dim).back() - splits(start);\n for (int j = start; j < limit; ++j) {\n out_splits->at(out_dim).push_back(splits(j + 1) + delta);\n }\n }\n start = splits(start);\n limit = splits(limit);\n }\n if (limit != start) {\n value_slices->emplace_back(start, limit);\n *num_values += limit - start;\n }\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status ValidateSplits(\n const std::vector<ConstFlatType>& params_nested_splits,\n SPLITS_TYPE num_params_dense_values) {\n // Validate\n for (int dim = 0; dim < params_nested_splits.size(); ++dim) {\n const auto& splits = params_nested_splits[dim];\n SPLITS_TYPE last_split = (dim == params_nested_splits.size() - 1)\n ? num_params_dense_values\n : params_nested_splits[dim + 1].size();\n if (splits.size() == 0) {\n return errors::InvalidArgument(\"Ragged splits may not be empty\");\n }\n if (splits(0) < 0) {\n return errors::InvalidArgument(\"Ragged splits must be non-negative\");\n }\n if (splits(splits.size() - 1) > last_split) {\n return errors::InvalidArgument(\n \"Ragged splits must not point past values\");\n }\n for (int i = 1; i < splits.size(); ++i) {\n if (splits(i - 1) > splits(i)) {\n return errors::InvalidArgument(\"Ragged splits must be sorted\");\n }\n }\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status WriteSplits(\n const std::vector<std::vector<SPLITS_TYPE>>& out_splits,\n OpKernelContext* context) {\n OpOutputList splits_out;\n TF_RETURN_IF_ERROR(\n context->output_list(\"output_nested_splits\", &splits_out));\n for (int i = 0; i < out_splits.size(); ++i) {\n Tensor* splits;\n SPLITS_TYPE num_splits = out_splits[i].size();\n TF_RETURN_IF_ERROR(\n splits_out.allocate(i, TensorShape({num_splits}), &splits));\n auto splits_flat = splits->flat<SPLITS_TYPE>();\n std::copy_n(out_splits[i].data(), out_splits[i].size(),\n splits_flat.data());\n }\n return ::tensorflow::Status::OK();\n }", " ::tensorflow::Status WriteValues(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n int values_index, SPLITS_TYPE num_values,\n OpKernelContext* context) const {\n Tensor* values_out = nullptr;\n TensorShape values_shape = params_dense_values_in.shape();\n values_shape.set_dim(0, num_values);\n TF_RETURN_IF_ERROR(\n context->allocate_output(values_index, values_shape, &values_out));\n const SPLITS_TYPE num_elements = params_dense_values_in.NumElements();\n const SPLITS_TYPE value_size =\n num_elements == 0 ? 0\n : (num_elements / params_dense_values_in.dim_size(0));\n CallWriteValueSlices(params_dense_values_in, value_slices, value_size,\n values_out);\n return ::tensorflow::Status::OK();\n }", " protected:\n // Call WriteValueSlices() using the appropriate VALUE_TYPE template\n // parameter. This pattern is used to reduce binary size. In particular,\n // this allows us to have two instantiations of this class (one for each\n // index type), rather than 14 (one for each index type and value type),\n // which cuts the binary size of this op from ~300k to <90k.\n virtual void CallWriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) const = 0;\n};", "template <typename INDEX_TYPE, typename VALUE_TYPE, typename SPLITS_TYPE>\nclass RaggedGatherOp : public RaggedGatherOpBase<INDEX_TYPE, SPLITS_TYPE> {\n public:\n using RaggedGatherOpBase<INDEX_TYPE, SPLITS_TYPE>::RaggedGatherOpBase;", " private:\n void CallWriteValueSlices(\n const Tensor& params_dense_values_in,\n const std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>>& value_slices,\n SPLITS_TYPE value_size, Tensor* values_out) const override {\n WriteValueSlices<VALUE_TYPE>(params_dense_values_in, value_slices,\n value_size, values_out);\n }\n};", "#define REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(index_type, value_type, \\\n splits_type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"RaggedGather\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<index_type>(\"Tindices\") \\\n .TypeConstraint<value_type>(\"Tvalues\") \\\n .TypeConstraint<splits_type>(\"Tsplits\"), \\\n RaggedGatherOp<index_type, value_type, splits_type>);\n#define REGISTER_CPU_KERNEL(value_type) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int32, value_type, int32) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int64, value_type, int32) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int32, value_type, int64) \\\n REGISTER_CPU_KERNEL_WITH_INDEX_TYPE(int64, value_type, int64)\nTF_CALL_POD_TYPES(REGISTER_CPU_KERNEL);\nTF_CALL_tstring(REGISTER_CPU_KERNEL);\nTF_CALL_QUANTIZED_TYPES(REGISTER_CPU_KERNEL);\nTF_CALL_quint16(REGISTER_CPU_KERNEL);\nTF_CALL_qint16(REGISTER_CPU_KERNEL);\n#undef REGISTER_CPU_KERNEL\n#undef REGISTER_CPU_KERNEL_WITH_INDEX_TYPE", "} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [70], "buggy_code_start_loc": [60], "filenames": ["tensorflow/core/kernels/ragged_gather_op.cc"], "fixing_code_end_loc": [76], "fixing_code_start_loc": [61], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions if the arguments to `tf.raw_ops.RaggedGather` don't determine a valid ragged tensor code can trigger a read from outside of bounds of heap allocated buffers. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) directly reads the first dimension of a tensor shape before checking that said tensor has rank of at least 1 (i.e., it is not a scalar). Furthermore, the implementation does not check that the list given by `params_nested_splits` is not an empty list of tensors. We have patched the issue in GitHub commit a2b743f6017d7b97af1fe49087ae15f0ac634373. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, TensorFlow 2.4.3, and TensorFlow 2.3.4, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas, si los argumentos \"tf.raw_ops.RaggedGather\" no determinan un tensor v\u00e1lido, el c\u00f3digo puede desencadenar una lectura desde fuera de l\u00edmites de los b\u00faferes asignados a la pila. La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/ragged_gather_op.cc#L70) lee directamente la primera dimensi\u00f3n de una forma tensorial antes de comprobar que dicho tensor presenta un rango de al menos 1 (es decir, no es un escalar). Adem\u00e1s, la implementaci\u00f3n no comprueba que la lista dada por \"params_nested_splits\" no sea una lista vac\u00eda de tensores. Hemos parcheado el problema en el commit de GitHub a2b743f6017d7b97af1fe49087ae15f0ac634373. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow versi\u00f3n 2.5.1, TensorFlow versi\u00f3n 2.4.3, y TensorFlow versi\u00f3n 2.3.4, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37641", "lastModified": "2021-08-18T17:00:51.547", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 3.6, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:P/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T21:15:07.670", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-9c8h-vvrj-w2p8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/a2b743f6017d7b97af1fe49087ae15f0ac634373"}, "type": "CWE-125"}
107
Determine whether the {function_name} code is vulnerable or not.
[ ".. currentmodule:: werkzeug", "Version 0.15.3\n--------------", "Unreleased", "- Properly handle multi-line header folding in development server in\n Python 2.7. (:issue:`1080`)\n- Restore the ``response`` argument to :exc:`~exceptions.Unauthorized`.\n (:pr:`1527`)\n- :exc:`~exceptions.Unauthorized` doesn't add the ``WWW-Authenticate``\n header if ``www_authenticate`` is not given. (:issue:`1516`)\n- The default URL converter correctly encodes bytes to string rather\n than representing them with ``b''``. (:issue:`1502`)\n- Fix the filename format string in\n :class:`~middleware.profiler.ProfilerMiddleware` to correctly handle\n float values. (:issue:`1511`)\n- Update :class:`~middleware.lint.LintMiddleware` to work on Python 3.\n (:issue:`1510`)\n- The debugger detects cycles in chained exceptions and does not time\n out in that case. (:issue:`1536`)", "", "", "Version 0.15.2\n--------------", "Released 2019-04-02", "- ``Rule`` code generation uses a filename that coverage will ignore.\n The previous value, \"generated\", was causing coverage to fail.\n (:issue:`1487`)\n- The test client removes the cookie header if there are no persisted\n cookies. This fixes an issue introduced in 0.15.0 where the cookies\n from the original request were used for redirects, causing functions\n such as logout to fail. (:issue:`1491`)\n- The test client copies the environ before passing it to the app, to\n prevent in-place modifications from affecting redirect requests.\n (:issue:`1498`)\n- The ``\"werkzeug\"`` logger only adds a handler if there is no handler\n configured for its level in the logging chain. This avoids double\n logging if other code configures logging first. (:issue:`1492`)", "\nVersion 0.15.1\n--------------", "Released 2019-03-21", "- :exc:`~exceptions.Unauthorized` takes ``description`` as the first\n argument, restoring previous behavior. The new ``www_authenticate``\n argument is listed second. (:issue:`1483`)", "\nVersion 0.15.0\n--------------", "Released 2019-03-19", "- Building URLs is ~7x faster. Each :class:`~routing.Rule` compiles\n an optimized function for building itself. (:pr:`1281`)\n- :meth:`MapAdapter.build() <routing.MapAdapter.build>` can be passed\n a :class:`~datastructures.MultiDict` to represent multiple values\n for a key. It already did this when passing a dict with a list\n value. (:pr:`724`)\n- ``path_info`` defaults to ``'/'`` for\n :meth:`Map.bind() <routing.Map.bind>`. (:issue:`740`, :pr:`768`,\n :pr:`1316`)\n- Change ``RequestRedirect`` code from 301 to 308, preserving the verb\n and request body (form data) during redirect. (:pr:`1342`)\n- ``int`` and ``float`` converters in URL rules will handle negative\n values if passed the ``signed=True`` parameter. For example,\n ``/jump/<int(signed=True):count>``. (:pr:`1355`)\n- ``Location`` autocorrection in :func:`Response.get_wsgi_headers()\n <wrappers.BaseResponse.get_wsgi_headers>` is relative to the current\n path rather than the root path. (:issue:`693`, :pr:`718`,\n :pr:`1315`)\n- 412 responses once again include entity headers and an error message\n in the body. They were originally omitted when implementing\n ``If-Match`` (:pr:`1233`), but the spec doesn't seem to disallow it.\n (:issue:`1231`, :pr:`1255`)\n- The Content-Length header is removed for 1xx and 204 responses. This\n fixes a previous change where no body would be sent, but the header\n would still be present. The new behavior matches RFC 7230.\n (:pr:`1294`)\n- :class:`~exceptions.Unauthorized` takes a ``www_authenticate``\n parameter to set the ``WWW-Authenticate`` header for the response,\n which is technically required for a valid 401 response.\n (:issue:`772`, :pr:`795`)\n- Add support for status code 424 :exc:`~exceptions.FailedDependency`.\n (:pr:`1358`)\n- :func:`http.parse_cookie` ignores empty segments rather than\n producing a cookie with no key or value. (:issue:`1245`, :pr:`1301`)\n- :func:`~http.parse_authorization_header` (and\n :class:`~datastructures.Authorization`,\n :attr:`~wrappers.Request.authorization`) treats the authorization\n header as UTF-8. On Python 2, basic auth username and password are\n ``unicode``. (:pr:`1325`)\n- :func:`~http.parse_options_header` understands :rfc:`2231` parameter\n continuations. (:pr:`1417`)\n- :func:`~urls.uri_to_iri` does not unquote ASCII characters in the\n unreserved class, such as space, and leaves invalid bytes quoted\n when decoding. :func:`~urls.iri_to_uri` does not quote reserved\n characters. See :rfc:`3987` for these character classes.\n (:pr:`1433`)\n- ``get_content_type`` appends a charset for any mimetype that ends\n with ``+xml``, not just those that start with ``application/``.\n Known text types such as ``application/javascript`` are also given\n charsets. (:pr:`1439`)\n- Clean up ``werkzeug.security`` module, remove outdated hashlib\n support. (:pr:`1282`)\n- In :func:`~security.generate_password_hash`, PBKDF2 uses 150000\n iterations by default, increased from 50000. (:pr:`1377`)\n- :class:`~wsgi.ClosingIterator` calls ``close`` on the wrapped\n *iterable*, not the internal iterator. This doesn't affect objects\n where ``__iter__`` returned ``self``. For other objects, the method\n was not called before. (:issue:`1259`, :pr:`1260`)\n- Bytes may be used as keys in :class:`~datastructures.Headers`, they\n will be decoded as Latin-1 like values are. (:pr:`1346`)\n- :class:`~datastructures.Range` validates that list of range tuples\n passed to it would produce a valid ``Range`` header. (:pr:`1412`)\n- :class:`~datastructures.FileStorage` looks up attributes on\n ``stream._file`` if they don't exist on ``stream``, working around\n an issue where :func:`tempfile.SpooledTemporaryFile` didn't\n implement all of :class:`io.IOBase`. See\n https://github.com/python/cpython/pull/3249. (:pr:`1409`)\n- :class:`CombinedMultiDict.copy() <datastructures.CombinedMultiDict>`\n returns a shallow mutable copy as a\n :class:`~datastructures.MultiDict`. The copy no longer reflects\n changes to the combined dicts, but is more generally useful.\n (:pr:`1420`)\n- The version of jQuery used by the debugger is updated to 3.3.1.\n (:pr:`1390`)\n- The debugger correctly renders long ``markupsafe.Markup`` instances.\n (:pr:`1393`)\n- The debugger can serve resources when Werkzeug is installed as a\n zip file. ``DebuggedApplication.get_resource`` uses\n ``pkgutil.get_data``. (:pr:`1401`)\n- The debugger and server log support Python 3's chained exceptions.\n (:pr:`1396`)\n- The interactive debugger highlights frames that come from user code\n to make them easy to pick out in a long stack trace. Note that if an\n env was created with virtualenv instead of venv, the debugger may\n incorrectly classify some frames. (:pr:`1421`)\n- Clicking the error message at the top of the interactive debugger\n will jump down to the bottom of the traceback. (:pr:`1422`)\n- When generating a PIN, the debugger will ignore a ``KeyError``\n raised when the current UID doesn't have an associated username,\n which can happen in Docker. (:issue:`1471`)\n- :class:`~exceptions.BadRequestKeyError` adds the ``KeyError``\n message to the description, making it clearer what caused the 400\n error. Frameworks like Flask can omit this information in production\n by setting ``e.args = ()``. (:pr:`1395`)\n- If a nested ``ImportError`` occurs from :func:`~utils.import_string`\n the traceback mentions the nested import. Removes an untested code\n path for handling \"modules not yet set up by the parent.\"\n (:pr:`735`)\n- Triggering a reload while using a tool such as PDB no longer hides\n input. (:pr:`1318`)\n- The reloader will not prepend the Python executable to the command\n line if the Python file is marked executable. This allows the\n reloader to work on NixOS. (:pr:`1242`)\n- Fix an issue where ``sys.path`` would change between reloads when\n running with ``python -m app``. The reloader can detect that a\n module was run with \"-m\" and reconstructs that instead of the file\n path in ``sys.argv`` when reloading. (:pr:`1416`)\n- The dev server can bind to a Unix socket by passing a hostname like\n ``unix://app.socket``. (:pr:`209`, :pr:`1019`)\n- Server uses ``IPPROTO_TCP`` constant instead of ``SOL_TCP`` for\n Jython compatibility. (:pr:`1375`)\n- When using an adhoc SSL cert with :func:`~serving.run_simple`, the\n cert is shown as self-signed rather than signed by an invalid\n authority. (:pr:`1430`)\n- The development server logs the unquoted IRI rather than the raw\n request line, to make it easier to work with Unicode in request\n paths during development. (:issue:`1115`)\n- The development server recognizes ``ConnectionError`` on Python 3 to\n silence client disconnects, and does not silence other ``OSErrors``\n that may have been raised inside the application. (:pr:`1418`)\n- The environ keys ``REQUEST_URI`` and ``RAW_URI`` contain the raw\n path before it was percent-decoded. This is non-standard, but many\n WSGI servers add them. Middleware could replace ``PATH_INFO`` with\n this to route based on the raw value. (:pr:`1419`)\n- :class:`~test.EnvironBuilder` doesn't set ``CONTENT_TYPE`` or\n ``CONTENT_LENGTH`` in the environ if they aren't set. Previously\n these used default values if they weren't set. Now it's possible to\n distinguish between empty and unset values. (:pr:`1308`)\n- The test client raises a ``ValueError`` if a query string argument\n would overwrite a query string in the path. (:pr:`1338`)\n- :class:`test.EnvironBuilder` and :class:`test.Client` take a\n ``json`` argument instead of manually passing ``data`` and\n ``content_type``. This is serialized using the\n :meth:`test.EnvironBuilder.json_dumps` method. (:pr:`1404`)\n- :class:`test.Client` redirect handling is rewritten. (:pr:`1402`)", " - The redirect environ is copied from the initial request environ.\n - Script root and path are correctly distinguished when\n redirecting to a path under the root.\n - The HEAD method is not changed to GET.\n - 307 and 308 codes preserve the method and body. All others\n ignore the body and related headers.\n - Headers are passed to the new request for all codes, following\n what browsers do.\n - :class:`test.EnvironBuilder` sets the content type and length\n headers in addition to the WSGI keys when detecting them from\n the data.\n - Intermediate response bodies are iterated over even when\n ``buffered=False`` to ensure iterator middleware can run cleanup\n code safely. Only the last response is not buffered. (:pr:`988`)", "- :class:`~test.EnvironBuilder`, :class:`~datastructures.FileStorage`,\n and :func:`wsgi.get_input_stream` no longer share a global\n ``_empty_stream`` instance. This improves test isolation by\n preventing cases where closing the stream in one request would\n affect other usages. (:pr:`1340`)\n- The default :attr:`SecureCookie.serialization_method\n <contrib.securecookie.SecureCookie.serialization_method>` will\n change from :mod:`pickle` to :mod:`json` in 1.0. To upgrade existing\n tokens, override :meth:`~contrib.securecookie.SecureCookie.unquote`\n to try ``pickle`` if ``json`` fails. (:pr:`1413`)\n- ``CGIRootFix`` no longer modifies ``PATH_INFO`` for very old\n versions of Lighttpd. ``LighttpdCGIRootFix`` was renamed to\n ``CGIRootFix`` in 0.9. Both are deprecated and will be removed in\n version 1.0. (:pr:`1141`)\n- :class:`werkzeug.wrappers.json.JSONMixin` has been replaced with\n Flask's implementation. Check the docs for the full API.\n (:pr:`1445`)\n- The :doc:`contrib modules </contrib/index>` are deprecated and will\n either be moved into ``werkzeug`` core or removed completely in\n version 1.0. Some modules that already issued deprecation warnings\n have been removed. Be sure to run or test your code with\n ``python -W default::DeprecationWarning`` to catch any deprecated\n code you're using. (:issue:`4`)", " - ``LintMiddleware`` has moved to :mod:`werkzeug.middleware.lint`.\n - ``ProfilerMiddleware`` has moved to\n :mod:`werkzeug.middleware.profiler`.\n - ``ProxyFix`` has moved to :mod:`werkzeug.middleware.proxy_fix`.\n - ``JSONRequestMixin`` has moved to :mod:`werkzeug.wrappers.json`.\n - ``cache`` has been extracted into a separate project,\n `cachelib <https://github.com/pallets/cachelib>`_. The version\n in Werkzeug is deprecated.\n - ``securecookie`` and ``sessions`` have been extracted into a\n separate project,\n `secure-cookie <https://github.com/pallets/secure-cookie>`_. The\n version in Werkzeug is deprecated.\n - Everything in ``fixers``, except ``ProxyFix``, is deprecated.\n - Everything in ``wrappers``, except ``JSONMixin``, is deprecated.\n - ``atom`` is deprecated. This did not fit in with the rest of\n Werkzeug, and is better served by a dedicated library in the\n community.\n - ``jsrouting`` is removed. Set URLs when rendering templates\n or JSON responses instead.\n - ``limiter`` is removed. Its specific use is handled by Werkzeug\n directly, but stream limiting is better handled by the WSGI\n server in general.\n - ``testtools`` is removed. It did not offer significant benefit\n over the default test client.\n - ``iterio`` is deprecated.", "- :func:`wsgi.get_host` no longer looks at ``X-Forwarded-For``. Use\n :class:`~middleware.proxy_fix.ProxyFix` to handle that.\n (:issue:`609`, :pr:`1303`)\n- :class:`~middleware.proxy_fix.ProxyFix` is refactored to support\n more headers, multiple values, and more secure configuration.", " - Each header supports multiple values. The trusted number of\n proxies is configured separately for each header. The\n ``num_proxies`` argument is deprecated. (:pr:`1314`)\n - Sets ``SERVER_NAME`` and ``SERVER_PORT`` based on\n ``X-Forwarded-Host``. (:pr:`1314`)\n - Sets ``SERVER_PORT`` and modifies ``HTTP_HOST`` based on\n ``X-Forwarded-Port``. (:issue:`1023`, :pr:`1304`)\n - Sets ``SCRIPT_NAME`` based on ``X-Forwarded-Prefix``.\n (:issue:`1237`)\n - The original WSGI environment values are stored in the\n ``werkzeug.proxy_fix.orig`` key, a dict. The individual keys\n ``werkzeug.proxy_fix.orig_remote_addr``,\n ``werkzeug.proxy_fix.orig_wsgi_url_scheme``, and\n ``werkzeug.proxy_fix.orig_http_host`` are deprecated.", "- Middleware from ``werkzeug.wsgi`` has moved to separate modules\n under ``werkzeug.middleware``, along with the middleware moved from\n ``werkzeug.contrib``. The old ``werkzeug.wsgi`` imports are\n deprecated and will be removed in version 1.0. (:pr:`1452`)", " - ``werkzeug.wsgi.DispatcherMiddleware`` has moved to\n :class:`werkzeug.middleware.dispatcher.DispatcherMiddleware`.\n - ``werkzeug.wsgi.ProxyMiddleware`` as moved to\n :class:`werkzeug.middleware.http_proxy.ProxyMiddleware`.\n - ``werkzeug.wsgi.SharedDataMiddleware`` has moved to\n :class:`werkzeug.middleware.shared_data.SharedDataMiddleware`.", "- :class:`~middleware.http_proxy.ProxyMiddleware` proxies the query\n string. (:pr:`1252`)\n- The filenames generated by\n :class:`~middleware.profiler.ProfilerMiddleware` can be customized.\n (:issue:`1283`)\n- The ``werkzeug.wrappers`` module has been converted to a package,\n and its various classes have been organized into separate modules.\n Any previously documented classes, understood to be the existing\n public API, are still importable from ``werkzeug.wrappers``, or may\n be imported from their specific modules. (:pr:`1456`)", "\nVersion 0.14.1\n--------------", "Released on December 31st 2017", "- Resolved a regression with status code handling in the integrated\n development server.", "Version 0.14\n------------", "Released on December 31st 2017", "- HTTP exceptions are now automatically caught by\n ``Request.application``.\n- Added support for edge as browser.\n- Added support for platforms that lack ``SpooledTemporaryFile``.\n- Add support for etag handling through if-match\n- Added support for the SameSite cookie attribute.\n- Added ``werkzeug.wsgi.ProxyMiddleware``\n- Implemented ``has`` for ``NullCache``\n- ``get_multi`` on cache clients now returns lists all the time.\n- Improved the watchdog observer shutdown for the reloader to not crash\n on exit on older Python versions.\n- Added support for ``filename*`` filename attributes according to\n RFC 2231\n- Resolved an issue where machine ID for the reloader PIN was not\n read accurately on windows.\n- Added a workaround for syntax errors in init files in the reloader.\n- Added support for using the reloader with console scripts on windows.\n- The built-in HTTP server will no longer close a connection in cases\n where no HTTP body is expected (204, 204, HEAD requests etc.)\n- The ``EnvironHeaders`` object now skips over empty content type and\n lengths if they are set to falsy values.\n- Werkzeug will no longer send the content-length header on 1xx or\n 204/304 responses.\n- Cookie values are now also permitted to include slashes and equal\n signs without quoting.\n- Relaxed the regex for the routing converter arguments.\n- If cookies are sent without values they are now assumed to have an\n empty value and the parser accepts this. Previously this could have\n corrupted cookies that followed the value.\n- The test ``Client`` and ``EnvironBuilder`` now support mimetypes like\n the request object does.\n- Added support for static weights in URL rules.\n- Better handle some more complex reloader scenarios where sys.path\n contained non directory paths.\n- ``EnvironHeaders`` no longer raises weird errors if non string keys\n are passed to it.", "\nVersion 0.13\n------------", "Released on December 7th 2017", "- **Deprecate support for Python 2.6 and 3.3.** CI tests will not run\n for these versions, and support will be dropped completely in the next\n version. (:issue:`pallets/meta#24`)\n- Raise ``TypeError`` when port is not an integer. (:pr:`1088`)\n- Fully deprecate ``werkzeug.script``. Use `Click`_ instead.\n (:pr:`1090`)\n- ``response.age`` is parsed as a ``timedelta``. Previously, it was\n incorrectly treated as a ``datetime``. The header value is an integer\n number of seconds, not a date string. (:pr:`414`)\n- Fix a bug in ``TypeConversionDict`` where errors are not propagated\n when using the converter. (:issue:`1102`)\n- ``Authorization.qop`` is a string instead of a set, to comply with\n RFC 2617. (:pr:`984`)\n- An exception is raised when an encoded cookie is larger than, by\n default, 4093 bytes. Browsers may silently ignore cookies larger than\n this. ``BaseResponse`` has a new attribute ``max_cookie_size`` and\n ``dump_cookie`` has a new argument ``max_size`` to configure this.\n (:pr:`780`, :pr:`1109`)\n- Fix a TypeError in ``werkzeug.contrib.lint.GuardedIterator.close``.\n (:pr:`1116`)\n- ``BaseResponse.calculate_content_length`` now correctly works for\n Unicode responses on Python 3. It first encodes using\n ``iter_encoded``. (:issue:`705`)\n- Secure cookie contrib works with string secret key on Python 3.\n (:pr:`1205`)\n- Shared data middleware accepts a list instead of a dict of static\n locations to preserve lookup order. (:pr:`1197`)\n- HTTP header values without encoding can contain single quotes.\n (:pr:`1208`)\n- The built-in dev server supports receiving requests with chunked\n transfer encoding. (:pr:`1198`)", ".. _Click: https://palletsprojects.com/p/click/", "\nVersion 0.12.2\n--------------", "Released on May 16 2017", "- Fix regression: Pull request ``#892`` prevented Werkzeug from correctly\n logging the IP of a remote client behind a reverse proxy, even when using\n `ProxyFix`.\n- Fix a bug in `safe_join` on Windows.", "Version 0.12.1\n--------------", "Released on March 15th 2017", "- Fix crash of reloader (used on debug mode) on Windows.\n (`OSError: [WinError 10038]`). See pull request ``#1081``\n- Partially revert change to class hierarchy of `Headers`. See ``#1084``.", "Version 0.12\n------------", "Released on March 10th 2017", "- Spit out big deprecation warnings for werkzeug.script\n- Use `inspect.getfullargspec` internally when available as\n `inspect.getargspec` is gone in 3.6\n- Added support for status code 451 and 423\n- Improved the build error suggestions. In particular only if\n someone stringifies the error will the suggestions be calculated.\n- Added support for uWSGI's caching backend.\n- Fix a bug where iterating over a `FileStorage` would result in an infinite\n loop.\n- Datastructures now inherit from the relevant baseclasses from the\n `collections` module in the stdlib. See #794.\n- Add support for recognizing NetBSD, OpenBSD, FreeBSD, DragonFlyBSD platforms\n in the user agent string.\n- Recognize SeaMonkey browser name and version correctly\n- Recognize Baiduspider, and bingbot user agents\n- If `LocalProxy`'s wrapped object is a function, refer to it with __wrapped__\n attribute.\n- The defaults of ``generate_password_hash`` have been changed to more secure\n ones, see pull request ``#753``.\n- Add support for encoding in options header parsing, see pull request\n ``#933``.\n- ``test.Client`` now properly handles Location headers with relative URLs, see\n pull request ``#879``.\n- When `HTTPException` is raised, it now prints the description, for easier\n debugging.\n- Werkzeug's dict-like datastructures now have ``view``-methods under Python 2,\n see pull request ``#968``.\n- Fix a bug in ``MultiPartParser`` when no ``stream_factory`` was provided\n during initialization, see pull request ``#973``.\n- Disable autocorrect and spellchecker in the debugger middleware's Python\n prompt, see pull request ``#994``.\n- Don't redirect to slash route when method doesn't match, see pull request\n ``#907``.\n- Fix a bug when using ``SharedDataMiddleware`` with frozen packages, see pull\n request ``#959``.\n- `Range` header parsing function fixed for invalid values ``#974``.\n- Add support for byte Range Requests, see pull request ``#978``.\n- Use modern cryptographic defaults in the dev servers ``#1004``.\n- the post() method of the test client now accept file object through the data\n parameter.\n- Color run_simple's terminal output based on HTTP codes ``#1013``.\n- Fix self-XSS in debugger console, see ``#1031``.\n- Fix IPython 5.x shell support, see ``#1033``.\n- Change Accept datastructure to sort by specificity first, allowing for more\n accurate results when using ``best_match`` for mime types (for example in\n ``requests.accept_mimetypes.best_match``)", "Version 0.11.16\n---------------", "- werkzeug.serving: set CONTENT_TYPE / CONTENT_LENGTH if only they're provided by the client\n- werkzeug.serving: Fix crash of reloader when using `python -m werkzeug.serving`.", "Version 0.11.15\n---------------", "Released on December 30th 2016.", "- Bugfix for the bugfix in the previous release.", "Version 0.11.14\n---------------", "Released on December 30th 2016.", "- Check if platform can fork before importing ``ForkingMixIn``, raise exception\n when creating ``ForkingWSGIServer`` on such a platform, see PR ``#999``.", "Version 0.11.13\n---------------", "Released on December 26th 2016.", "- Correct fix for the reloader issuer on certain Windows installations.", "Version 0.11.12\n---------------", "Released on December 26th 2016.", "- Fix more bugs in multidicts regarding empty lists. See ``#1000``.\n- Add some docstrings to some `EnvironBuilder` properties that were previously\n unintentionally missing.\n- Added a workaround for the reloader on windows.", "Version 0.11.11\n---------------", "Released on August 31st 2016.", "- Fix JSONRequestMixin for Python3. See #731\n- Fix broken string handling in test client when passing integers. See #852\n- Fix a bug in ``parse_options_header`` where an invalid content type\n starting with comma or semi-colon would result in an invalid return value,\n see issue ``#995``.\n- Fix a bug in multidicts when passing empty lists as values, see issue\n ``#979``.\n- Fix a security issue that allows XSS on the Werkzeug debugger. See ``#1001``.", "Version 0.11.10\n---------------", "Released on May 24th 2016.", "- Fixed a bug that occurs when running on Python 2.6 and using a broken locale.\n See pull request #912.\n- Fixed a crash when running the debugger on Google App Engine. See issue #925.\n- Fixed an issue with multipart parsing that could cause memory exhaustion.", "Version 0.11.9\n--------------", "Released on April 24th 2016.", "- Corrected an issue that caused the debugger not to use the\n machine GUID on POSIX systems.\n- Corrected a Unicode error on Python 3 for the debugger's\n PIN usage.\n- Corrected the timestamp verification in the pin debug code.\n Without this fix the pin was remembered for too long.", "Version 0.11.8\n--------------", "Released on April 15th 2016.", "- fixed a problem with the machine GUID detection code on OS X\n on Python 3.", "Version 0.11.7\n--------------", "Released on April 14th 2016.", "- fixed a regression on Python 3 for the debugger.", "Version 0.11.6\n--------------", "Released on April 14th 2016.", "- werkzeug.serving: Still show the client address on bad requests.\n- improved the PIN based protection for the debugger to make it harder to\n brute force via trying cookies. Please keep in mind that the debugger\n *is not intended for running on production environments*\n- increased the pin timeout to a week to make it less annoying for people\n which should decrease the chance that users disable the pin check\n entirely.\n- werkzeug.serving: Fix broken HTTP_HOST when path starts with double slash.", "Version 0.11.5\n--------------", "Released on March 22nd 2016.", "- werkzeug.serving: Fix crash when attempting SSL connection to HTTP server.", "Version 0.11.4\n--------------", "Released on February 14th 2016.", "- Fixed werkzeug.serving not working from -m flag.\n- Fixed incorrect weak etag handling.", "Version 0.11.3\n--------------", "Released on December 20th 2015.", "- Fixed an issue with copy operations not working against\n proxies.\n- Changed the logging operations of the development server to\n correctly log where the server is running in all situations\n again.\n- Fixed another regression with SSL wrapping similar to the\n fix in 0.11.2 but for a different code path.", "Version 0.11.2\n--------------", "Released on November 12th 2015.", "- Fix inheritable sockets on Windows on Python 3.\n- Fixed an issue with the forking server not starting any longer.\n- Fixed SSL wrapping on platforms that supported opening sockets\n by file descriptor.\n- No longer log from the watchdog reloader.\n- Unicode errors in hosts are now better caught or converted into\n bad request errors.", "Version 0.11.1\n--------------", "Released on November 10th 2015.", "- Fixed a regression on Python 3 in the debugger.", "Version 0.11\n------------", "Released on November 8th 2015, codename Gleisbaumaschine.", "- Added ``reloader_paths`` option to ``run_simple`` and other functions in\n ``werkzeug.serving``. This allows the user to completely override the Python\n module watching of Werkzeug with custom paths.\n- Many custom cached properties of Werkzeug's classes are now subclasses of\n Python's ``property`` type (issue ``#616``).\n- ``bind_to_environ`` now doesn't differentiate between implicit and explicit\n default port numbers in ``HTTP_HOST`` (pull request ``#204``).\n- ``BuildErrors`` are now more informative. They come with a complete sentence\n as error message, and also provide suggestions (pull request ``#691``).\n- Fix a bug in the user agent parser where Safari's build number instead of\n version would be extracted (pull request ``#703``).\n- Fixed issue where RedisCache set_many was broken for twemproxy, which doesn't\n support the default MULTI command (pull request ``#702``).\n- ``mimetype`` parameters on request and response classes are now always\n converted to lowercase.\n- Changed cache so that cache never expires if timeout is 0. This also fixes\n an issue with redis setex (issue ``#550``)\n- Werkzeug now assumes ``UTF-8`` as filesystem encoding on Unix if Python\n detected it as ASCII.\n- New optional `has` method on caches.\n- Fixed various bugs in `parse_options_header` (pull request ``#643``).\n- If the reloader is enabled the server will now open the socket in the parent\n process if this is possible. This means that when the reloader kicks in\n the connection from client will wait instead of tearing down. This does\n not work on all Python versions.\n- Implemented PIN based authentication for the debugger. This can optionally\n be disabled but is discouraged. This change was necessary as it has been\n discovered that too many people run the debugger in production.\n- Devserver no longer requires SSL module to be installed.", "Version 0.10.5\n--------------", "(bugfix release, release date yet to be decided)", "- Reloader: Correctly detect file changes made by moving temporary files over\n the original, which is e.g. the case with PyCharm (pull request ``#722``).\n- Fix bool behavior of ``werkzeug.datastructures.ETags`` under Python 3 (issue\n ``#744``).", "Version 0.10.4\n--------------", "(bugfix release, released on March 26th 2015)", "- Re-release of 0.10.3 with packaging artifacts manually removed.", "Version 0.10.3\n--------------", "(bugfix release, released on March 26th 2015)", "- Re-release of 0.10.2 without packaging artifacts.", "Version 0.10.2\n--------------", "(bugfix release, released on March 26th 2015)", "- Fixed issue where ``empty`` could break third-party libraries that relied on\n keyword arguments (pull request ``#675``)\n- Improved ``Rule.empty`` by providing a ```get_empty_kwargs`` to allow setting\n custom kwargs without having to override entire ``empty`` method. (pull\n request ``#675``)\n- Fixed ```extra_files``` parameter for reloader to not cause startup\n to crash when included in server params\n- Using `MultiDict` when building URLs is now not supported again. The behavior\n introduced several regressions.\n- Fix performance problems with stat-reloader (pull request ``#715``).", "Version 0.10.1\n--------------", "(bugfix release, released on February 3rd 2015)", "- Fixed regression with multiple query values for URLs (pull request ``#667``).\n- Fix issues with eventlet's monkeypatching and the builtin server (pull\n request ``#663``).", "Version 0.10\n------------", "Released on January 30th 2015, codename Bagger.", "- Changed the error handling of and improved testsuite for the caches in\n ``contrib.cache``.\n- Fixed a bug on Python 3 when creating adhoc ssl contexts, due to `sys.maxint`\n not being defined.\n- Fixed a bug on Python 3, that caused\n :func:`~werkzeug.serving.make_ssl_devcert` to fail with an exception.\n- Added exceptions for 504 and 505.\n- Added support for ChromeOS detection.\n- Added UUID converter to the routing system.\n- Added message that explains how to quit the server.\n- Fixed a bug on Python 2, that caused ``len`` for\n :class:`werkzeug.datastructures.CombinedMultiDict` to crash.\n- Added support for stdlib pbkdf2 hmac if a compatible digest\n is found.\n- Ported testsuite to use ``py.test``.\n- Minor optimizations to various middlewares (pull requests ``#496`` and\n ``#571``).\n- Use stdlib ``ssl`` module instead of ``OpenSSL`` for the builtin server\n (issue ``#434``). This means that OpenSSL contexts are not supported anymore,\n but instead ``ssl.SSLContext`` from the stdlib.\n- Allow protocol-relative URLs when building external URLs.\n- Fixed Atom syndication to print time zone offset for tz-aware datetime\n objects (pull request ``#254``).\n- Improved reloader to track added files and to recover from broken\n sys.modules setups with syntax errors in packages.\n- ``cache.RedisCache`` now supports arbitrary ``**kwargs`` for the redis\n object.\n- ``werkzeug.test.Client`` now uses the original request method when resolving\n 307 redirects (pull request ``#556``).\n- ``werkzeug.datastructures.MIMEAccept`` now properly deals with mimetype\n parameters (pull request ``#205``).\n- ``werkzeug.datastructures.Accept`` now handles a quality of ``0`` as\n intolerable, as per RFC 2616 (pull request ``#536``).\n- ``werkzeug.urls.url_fix`` now properly encodes hostnames with ``idna``\n encoding (issue ``#559``). It also doesn't crash on malformed URLs anymore\n (issue ``#582``).\n- ``werkzeug.routing.MapAdapter.match`` now recognizes the difference between\n the path ``/`` and an empty one (issue ``#360``).\n- The interactive debugger now tries to decode non-ascii filenames (issue\n ``#469``).\n- Increased default key size of generated SSL certificates to 1024 bits (issue\n ``#611``).\n- Added support for specifying a ``Response`` subclass to use when calling\n :func:`~werkzeug.utils.redirect`\\ .\n- ``werkzeug.test.EnvironBuilder`` now doesn't use the request method anymore\n to guess the content type, and purely relies on the ``form``, ``files`` and\n ``input_stream`` properties (issue ``#620``).\n- Added Symbian to the user agent platform list.\n- Fixed make_conditional to respect automatically_set_content_length\n- Unset ``Content-Length`` when writing to response.stream (issue ``#451``)\n- ``wrappers.Request.method`` is now always uppercase, eliminating\n inconsistencies of the WSGI environment (issue ``647``).\n- ``routing.Rule.empty`` now works correctly with subclasses of ``Rule`` (pull\n request ``#645``).\n- Made map updating safe in light of concurrent updates.\n- Allow multiple values for the same field for url building (issue ``#658``).", "Version 0.9.7\n-------------", "(bugfix release, release date to be decided)", "- Fix unicode problems in ``werkzeug.debug.tbtools``.\n- Fix Python 3-compatibility problems in ``werkzeug.posixemulation``.\n- Backport fix of fatal typo for ``ImmutableList`` (issue ``#492``).\n- Make creation of the cache dir for ``FileSystemCache`` atomic (issue\n ``#468``).\n- Use native strings for memcached keys to work with Python 3 client (issue\n ``#539``).\n- Fix charset detection for ``werkzeug.debug.tbtools.Frame`` objects (issues\n ``#547`` and ``#532``).\n- Fix ``AttributeError`` masking in ``werkzeug.utils.import_string`` (issue\n ``#182``).\n- Explicitly shut down server (issue ``#519``).\n- Fix timeouts greater than 2592000 being misinterpreted as UNIX timestamps in\n ``werkzeug.contrib.cache.MemcachedCache`` (issue ``#533``).\n- Fix bug where ``werkzeug.exceptions.abort`` would raise an arbitrary subclass\n of the expected class (issue ``#422``).\n- Fix broken ``jsrouting`` (due to removal of ``werkzeug.templates``)\n- ``werkzeug.urls.url_fix`` now doesn't crash on malformed URLs anymore, but\n returns them unmodified. This is a cheap workaround for ``#582``, the proper\n fix is included in version 0.10.\n- The repr of ``werkzeug.wrappers.Request`` doesn't crash on non-ASCII-values\n anymore (pull request ``#466``).\n- Fix bug in ``cache.RedisCache`` when combined with ``redis.StrictRedis``\n object (pull request ``#583``).\n- The ``qop`` parameter for ``WWW-Authenticate`` headers is now always quoted,\n as required by RFC 2617 (issue ``#633``).\n- Fix bug in ``werkzeug.contrib.cache.SimpleCache`` with Python 3 where add/set\n may throw an exception when pruning old entries from the cache (pull request\n ``#651``).", "Version 0.9.6\n-------------", "(bugfix release, released on June 7th 2014)", "- Added a safe conversion for IRI to URI conversion and use that\n internally to work around issues with spec violations for\n protocols such as ``itms-service``.", "Version 0.9.7\n-------------", "- Fixed uri_to_iri() not re-encoding hashes in query string parameters.", "Version 0.9.5\n-------------", "(bugfix release, released on June 7th 2014)", "- Forward charset argument from request objects to the environ\n builder.\n- Fixed error handling for missing boundaries in multipart data.\n- Fixed session creation on systems without ``os.urandom()``.\n- Fixed pluses in dictionary keys not being properly URL encoded.\n- Fixed a problem with deepcopy not working for multi dicts.\n- Fixed a double quoting issue on redirects.\n- Fixed a problem with unicode keys appearing in headers on 2.x.\n- Fixed a bug with unicode strings in the test builder.\n- Fixed a unicode bug on Python 3 in the WSGI profiler.\n- Fixed an issue with the safe string compare function on\n Python 2.7.7 and Python 3.4.", "Version 0.9.4\n-------------", "(bugfix release, released on August 26th 2013)", "- Fixed an issue with Python 3.3 and an edge case in cookie parsing.\n- Fixed decoding errors not handled properly through the WSGI\n decoding dance.\n- Fixed URI to IRI conversion incorrectly decoding percent signs.", "Version 0.9.3\n-------------", "(bugfix release, released on July 25th 2013)", "- Restored behavior of the ``data`` descriptor of the request class to pre 0.9\n behavior. This now also means that ``.data`` and ``.get_data()`` have\n different behavior. New code should use ``.get_data()`` always.", " In addition to that there is now a flag for the ``.get_data()`` method that\n controls what should happen with form data parsing and the form parser will\n honor cached data. This makes dealing with custom form data more consistent.", "Version 0.9.2\n-------------", "(bugfix release, released on July 18th 2013)", "- Added `unsafe` parameter to :func:`~werkzeug.urls.url_quote`.\n- Fixed an issue with :func:`~werkzeug.urls.url_quote_plus` not quoting\n `'+'` correctly.\n- Ported remaining parts of :class:`~werkzeug.contrib.RedisCache` to\n Python 3.3.\n- Ported remaining parts of :class:`~werkzeug.contrib.MemcachedCache` to\n Python 3.3\n- Fixed a deprecation warning in the contrib atom module.\n- Fixed a regression with setting of content types through the\n headers dictionary instead with the content type parameter.\n- Use correct name for stdlib secure string comparison function.\n- Fixed a wrong reference in the docstring of\n :func:`~werkzeug.local.release_local`.\n- Fixed an `AttributeError` that sometimes occurred when accessing the\n :attr:`werkzeug.wrappers.BaseResponse.is_streamed` attribute.", "Version 0.9.1\n-------------", "(bugfix release, released on June 14th 2013)", "- Fixed an issue with integers no longer being accepted in certain\n parts of the routing system or URL quoting functions.\n- Fixed an issue with `url_quote` not producing the right escape\n codes for single digit codepoints.\n- Fixed an issue with :class:`~werkzeug.wsgi.SharedDataMiddleware` not\n reading the path correctly and breaking on etag generation in some\n cases.\n- Properly handle `Expect: 100-continue` in the development server\n to resolve issues with curl.\n- Automatically exhaust the input stream on request close. This should\n fix issues where not touching request files results in a timeout.\n- Fixed exhausting of streams not doing anything if a non-limited\n stream was passed into the multipart parser.\n- Raised the buffer sizes for the multipart parser.", "Version 0.9\n-----------", "Released on June 13nd 2013, codename Planierraupe.", "- Added support for :meth:`~werkzeug.wsgi.LimitedStream.tell`\n on the limited stream.\n- :class:`~werkzeug.datastructures.ETags` now is nonzero if it\n contains at least one etag of any kind, including weak ones.\n- Added a workaround for a bug in the stdlib for SSL servers.\n- Improved SSL interface of the devserver so that it can generate\n certificates easily and load them from files.\n- Refactored test client to invoke the open method on the class\n for redirects. This makes subclassing more powerful.\n- :func:`werkzeug.wsgi.make_chunk_iter` and\n :func:`werkzeug.wsgi.make_line_iter` now support processing of\n iterators and streams.\n- URL generation by the routing system now no longer quotes\n ``+``.\n- URL fixing now no longer quotes certain reserved characters.\n- The :func:`werkzeug.security.generate_password_hash` and\n check functions now support any of the hashlib algorithms.\n- `wsgi.get_current_url` is now ascii safe for browsers sending\n non-ascii data in query strings.\n- improved parsing behavior for :func:`werkzeug.http.parse_options_header`\n- added more operators to local proxies.\n- added a hook to override the default converter in the routing\n system.\n- The description field of HTTP exceptions is now always escaped.\n Use markup objects to disable that.\n- Added number of proxy argument to the proxy fix to make it more\n secure out of the box on common proxy setups. It will by default\n no longer trust the x-forwarded-for header as much as it did\n before.\n- Added support for fragment handling in URI/IRI functions.\n- Added custom class support for :func:`werkzeug.http.parse_dict_header`.\n- Renamed `LighttpdCGIRootFix` to `CGIRootFix`.\n- Always treat `+` as safe when fixing URLs as people love misusing them.\n- Added support to profiling into directories in the contrib profiler.\n- The escape function now by default escapes quotes.\n- Changed repr of exceptions to be less magical.\n- Simplified exception interface to no longer require environments\n to be passed to receive the response object.\n- Added sentinel argument to IterIO objects.\n- Added pbkdf2 support for the security module.\n- Added a plain request type that disables all form parsing to only\n leave the stream behind.\n- Removed support for deprecated `fix_headers`.\n- Removed support for deprecated `header_list`.\n- Removed support for deprecated parameter for `iter_encoded`.\n- Removed support for deprecated non-silent usage of the limited\n stream object.\n- Removed support for previous dummy `writable` parameter on\n the cached property.\n- Added support for explicitly closing request objects to close\n associated resources.\n- Conditional request handling or access to the data property on responses no\n longer ignores direct passthrough mode.\n- Removed werkzeug.templates and werkzeug.contrib.kickstart.\n- Changed host lookup logic for forwarded hosts to allow lists of\n hosts in which case only the first one is picked up.\n- Added `wsgi.get_query_string`, `wsgi.get_path_info` and\n `wsgi.get_script_name` and made the `wsgi.pop_path_info` and\n `wsgi.peek_path_info` functions perform unicode decoding. This\n was necessary to avoid having to expose the WSGI encoding dance\n on Python 3.\n- Added `content_encoding` and `content_md5` to the request object's\n common request descriptor mixin.\n- added `options` and `trace` to the test client.\n- Overhauled the utilization of the input stream to be easier to use\n and better to extend. The detection of content payload on the input\n side is now more compliant with HTTP by detecting off the content\n type header instead of the request method. This also now means that\n the stream property on the request class is always available instead\n of just when the parsing fails.\n- Added support for using :class:`werkzeug.wrappers.BaseResponse` in a with\n statement.\n- Changed `get_app_iter` to fetch the response early so that it does not\n fail when wrapping a response iterable. This makes filtering easier.\n- Introduced `get_data` and `set_data` methods for responses.\n- Introduced `get_data` for requests.\n- Soft deprecated the `data` descriptors for request and response objects.\n- Added `as_bytes` operations to some of the headers to simplify working\n with things like cookies.\n- Made the debugger paste tracebacks into github's gist service as\n private pastes.", "Version 0.8.4\n-------------", "(bugfix release, release date to be announced)", "- Added a favicon to the debugger which fixes problem with\n state changes being triggered through a request to\n /favicon.ico in Google Chrome. This should fix some\n problems with Flask and other frameworks that use\n context local objects on a stack with context preservation\n on errors.\n- Fixed an issue with scrolling up in the debugger.\n- Fixed an issue with debuggers running on a different URL\n than the URL root.\n- Fixed a problem with proxies not forwarding some rarely\n used special methods properly.\n- Added a workaround to prevent the XSS protection from Chrome\n breaking the debugger.\n- Skip redis tests if redis is not running.\n- Fixed a typo in the multipart parser that caused content-type\n to not be picked up properly.", "Version 0.8.3\n-------------", "(bugfix release, released on February 5th 2012)", "- Fixed another issue with :func:`werkzeug.wsgi.make_line_iter`\n where lines longer than the buffer size were not handled\n properly.\n- Restore stdout after debug console finished executing so\n that the debugger can be used on GAE better.\n- Fixed a bug with the redis cache for int subclasses\n (affects bool caching).\n- Fixed an XSS problem with redirect targets coming from\n untrusted sources.\n- Redis cache backend now supports password authentication.", "Version 0.8.2\n-------------", "(bugfix release, released on December 16th 2011)", "- Fixed a problem with request handling of the builtin server\n not responding to socket errors properly.\n- The routing request redirect exception's code attribute is now\n used properly.\n- Fixed a bug with shutdowns on Windows.\n- Fixed a few unicode issues with non-ascii characters being\n hardcoded in URL rules.\n- Fixed two property docstrings being assigned to fdel instead\n of ``__doc__``.\n- Fixed an issue where CRLF line endings could be split into two\n by the line iter function, causing problems with multipart file\n uploads.", "Version 0.8.1\n-------------", "(bugfix release, released on September 30th 2011)", "- Fixed an issue with the memcache not working properly.\n- Fixed an issue for Python 2.7.1 and higher that broke\n copying of multidicts with :func:`copy.copy`.\n- Changed hashing methodology of immutable ordered multi dicts\n for a potential problem with alternative Python implementations.", "Version 0.8\n-----------", "Released on September 29th 2011, codename Lötkolben", "- Removed data structure specific KeyErrors for a general\n purpose :exc:`~werkzeug.exceptions.BadRequestKeyError`.\n- Documented :meth:`werkzeug.wrappers.BaseRequest._load_form_data`.\n- The routing system now also accepts strings instead of\n dictionaries for the `query_args` parameter since we're only\n passing them through for redirects.\n- Werkzeug now automatically sets the content length immediately when\n the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute is set\n for efficiency and simplicity reasons.\n- The routing system will now normalize server names to lowercase.\n- The routing system will no longer raise ValueErrors in case the\n configuration for the server name was incorrect. This should make\n deployment much easier because you can ignore that factor now.\n- Fixed a bug with parsing HTTP digest headers. It rejected headers\n with missing nc and nonce params.\n- Proxy fix now also updates wsgi.url_scheme based on X-Forwarded-Proto.\n- Added support for key prefixes to the redis cache.\n- Added the ability to suppress some auto corrections in the wrappers\n that are now controlled via `autocorrect_location_header` and\n `automatically_set_content_length` on the response objects.\n- Werkzeug now uses a new method to check that the length of incoming\n data is complete and will raise IO errors by itself if the server\n fails to do so.\n- :func:`~werkzeug.wsgi.make_line_iter` now requires a limit that is\n not higher than the length the stream can provide.\n- Refactored form parsing into a form parser class that makes it possible\n to hook into individual parts of the parsing process for debugging and\n extending.\n- For conditional responses the content length is no longer set when it\n is already there and added if missing.\n- Immutable datastructures are hashable now.\n- Headers datastructure no longer allows newlines in values to avoid\n header injection attacks.\n- Made it possible through subclassing to select a different remote\n addr in the proxy fix.\n- Added stream based URL decoding. This reduces memory usage on large\n transmitted form data that is URL decoded since Werkzeug will no longer\n load all the unparsed data into memory.\n- Memcache client now no longer uses the buggy cmemcache module and\n supports pylibmc. GAE is not tried automatically and the dedicated\n class is no longer necessary.\n- Redis cache now properly serializes data.\n- Removed support for Python 2.4", "Version 0.7.2\n-------------", "(bugfix release, released on September 30th 2011)", "- Fixed a CSRF problem with the debugger.\n- The debugger is now generating private pastes on lodgeit.\n- If URL maps are now bound to environments the query arguments\n are properly decoded from it for redirects.", "Version 0.7.1\n-------------", "(bugfix release, released on July 26th 2011)", "- Fixed a problem with newer versions of IPython.\n- Disabled pyinotify based reloader which does not work reliably.", "Version 0.7\n-----------", "Released on July 24th 2011, codename Schraubschlüssel", "- Add support for python-libmemcached to the Werkzeug cache abstraction\n layer.\n- Improved :func:`url_decode` and :func:`url_encode` performance.\n- Fixed an issue where the SharedDataMiddleware could cause an\n internal server error on weird paths when loading via pkg_resources.\n- Fixed an URL generation bug that caused URLs to be invalid if a\n generated component contains a colon.\n- :func:`werkzeug.import_string` now works with partially set up\n packages properly.\n- Disabled automatic socket switching for IPv6 on the development\n server due to problems it caused.\n- Werkzeug no longer overrides the Date header when creating a\n conditional HTTP response.\n- The routing system provides a method to retrieve the matching\n methods for a given path.\n- The routing system now accepts a parameter to change the encoding\n error behaviour.\n- The local manager can now accept custom ident functions in the\n constructor that are forwarded to the wrapped local objects.\n- url_unquote_plus now accepts unicode strings again.\n- Fixed an issue with the filesystem session support's prune\n function and concurrent usage.\n- Fixed a problem with external URL generation discarding the port.\n- Added support for pylibmc to the Werkzeug cache abstraction layer.\n- Fixed an issue with the new multipart parser that happened when\n a linebreak happened to be on the chunk limit.\n- Cookies are now set properly if ports are in use. A runtime error\n is raised if one tries to set a cookie for a domain without a dot.\n- Fixed an issue with Template.from_file not working for file\n descriptors.\n- Reloader can now use inotify to track reloads. This requires the\n pyinotify library to be installed.\n- Werkzeug debugger can now submit to custom lodgeit installations.\n- redirect function's status code assertion now allows 201 to be used\n as redirection code. While it's not a real redirect, it shares\n enough with redirects for the function to still be useful.\n- Fixed securecookie for pypy.\n- Fixed `ValueErrors` being raised on calls to `best_match` on\n `MIMEAccept` objects when invalid user data was supplied.\n- Deprecated `werkzeug.contrib.kickstart` and `werkzeug.contrib.testtools`\n- URL routing now can be passed the URL arguments to keep them for\n redirects. In the future matching on URL arguments might also be\n possible.\n- Header encoding changed from utf-8 to latin1 to support a port to\n Python 3. Bytestrings passed to the object stay untouched which\n makes it possible to have utf-8 cookies. This is a part where\n the Python 3 version will later change in that it will always\n operate on latin1 values.\n- Fixed a bug in the form parser that caused the last character to\n be dropped off if certain values in multipart data are used.\n- Multipart parser now looks at the part-individual content type\n header to override the global charset.\n- Introduced mimetype and mimetype_params attribute for the file\n storage object.\n- Changed FileStorage filename fallback logic to skip special filenames\n that Python uses for marking special files like stdin.\n- Introduced more HTTP exception classes.\n- `call_on_close` now can be used as a decorator.\n- Support for redis as cache backend.\n- Added `BaseRequest.scheme`.\n- Support for the RFC 5789 PATCH method.\n- New custom routing parser and better ordering.\n- Removed support for `is_behind_proxy`. Use a WSGI middleware\n instead that rewrites the `REMOTE_ADDR` according to your setup.\n Also see the :class:`werkzeug.contrib.fixers.ProxyFix` for\n a drop-in replacement.\n- Added cookie forging support to the test client.\n- Added support for host based matching in the routing system.\n- Switched from the default 'ignore' to the better 'replace'\n unicode error handling mode.\n- The builtin server now adds a function named 'werkzeug.server.shutdown'\n into the WSGI env to initiate a shutdown. This currently only works\n in Python 2.6 and later.\n- Headers are now assumed to be latin1 for better compatibility with\n Python 3 once we have support.\n- Added :func:`werkzeug.security.safe_join`.\n- Added `accept_json` property analogous to `accept_html` on the\n :class:`werkzeug.datastructures.MIMEAccept`.\n- :func:`werkzeug.utils.import_string` now fails with much better\n error messages that pinpoint to the problem.\n- Added support for parsing of the `If-Range` header\n (:func:`werkzeug.http.parse_if_range_header` and\n :class:`werkzeug.datastructures.IfRange`).\n- Added support for parsing of the `Range` header\n (:func:`werkzeug.http.parse_range_header` and\n :class:`werkzeug.datastructures.Range`).\n- Added support for parsing of the `Content-Range` header of responses\n and provided an accessor object for it\n (:func:`werkzeug.http.parse_content_range_header` and\n :class:`werkzeug.datastructures.ContentRange`).", "Version 0.6.2\n-------------", "(bugfix release, released on April 23th 2010)", "- renamed the attribute `implicit_seqence_conversion` attribute of the\n request object to `implicit_sequence_conversion`.", "Version 0.6.1\n-------------", "(bugfix release, released on April 13th 2010)", "- heavily improved local objects. Should pick up standalone greenlet\n builds now and support proxies to free callables as well. There is\n also a stacked local now that makes it possible to invoke the same\n application from within itself by pushing current request/response\n on top of the stack.\n- routing build method will also build non-default method rules properly\n if no method is provided.\n- added proper IPv6 support for the builtin server.\n- windows specific filesystem session store fixes.\n (should now be more stable under high concurrency)\n- fixed a `NameError` in the session system.\n- fixed a bug with empty arguments in the werkzeug.script system.\n- fixed a bug where log lines will be duplicated if an application uses\n :meth:`logging.basicConfig` (#499)\n- added secure password hashing and checking functions.\n- `HEAD` is now implicitly added as method in the routing system if\n `GET` is present. Not doing that was considered a bug because often\n code assumed that this is the case and in web servers that do not\n normalize `HEAD` to `GET` this could break `HEAD` requests.\n- the script support can start SSL servers now.", "Version 0.6\n-----------", "Released on Feb 19th 2010, codename Hammer.", "- removed pending deprecations\n- sys.path is now printed from the testapp.\n- fixed an RFC 2068 incompatibility with cookie value quoting.\n- the :class:`FileStorage` now gives access to the multipart headers.\n- `cached_property.writeable` has been deprecated.\n- :meth:`MapAdapter.match` now accepts a `return_rule` keyword argument\n that returns the matched `Rule` instead of just the `endpoint`\n- :meth:`routing.Map.bind_to_environ` raises a more correct error message\n now if the map was bound to an invalid WSGI environment.\n- added support for SSL to the builtin development server.\n- Response objects are no longer modified in place when they are evaluated\n as WSGI applications. For backwards compatibility the `fix_headers`\n function is still called in case it was overridden.\n You should however change your application to use `get_wsgi_headers` if\n you need header modifications before responses are sent as the backwards\n compatibility support will go away in future versions.\n- :func:`append_slash_redirect` no longer requires the QUERY_STRING to be\n in the WSGI environment.\n- added :class:`~werkzeug.contrib.wrappers.DynamicCharsetResponseMixin`\n- added :class:`~werkzeug.contrib.wrappers.DynamicCharsetRequestMixin`\n- added :attr:`BaseRequest.url_charset`\n- request and response objects have a default `__repr__` now.\n- builtin data structures can be pickled now.\n- the form data parser will now look at the filename instead the\n content type to figure out if it should treat the upload as regular\n form data or file upload. This fixes a bug with Google Chrome.\n- improved performance of `make_line_iter` and the multipart parser\n for binary uploads.\n- fixed :attr:`~werkzeug.BaseResponse.is_streamed`\n- fixed a path quoting bug in `EnvironBuilder` that caused PATH_INFO and\n SCRIPT_NAME to end up in the environ unquoted.\n- :meth:`werkzeug.BaseResponse.freeze` now sets the content length.\n- for unknown HTTP methods the request stream is now always limited\n instead of being empty. This makes it easier to implement DAV\n and other protocols on top of Werkzeug.\n- added :meth:`werkzeug.MIMEAccept.best_match`\n- multi-value test-client posts from a standard dictionary are now\n supported. Previously you had to use a multi dict.\n- rule templates properly work with submounts, subdomains and\n other rule factories now.\n- deprecated non-silent usage of the :class:`werkzeug.LimitedStream`.\n- added support for IRI handling to many parts of Werkzeug.\n- development server properly logs to the werkzeug logger now.\n- added :func:`werkzeug.extract_path_info`\n- fixed a querystring quoting bug in :func:`url_fix`\n- added `fallback_mimetype` to :class:`werkzeug.SharedDataMiddleware`.\n- deprecated :meth:`BaseResponse.iter_encoded`'s charset parameter.\n- added :meth:`BaseResponse.make_sequence`,\n :attr:`BaseResponse.is_sequence` and\n :meth:`BaseResponse._ensure_sequence`.\n- added better __repr__ of :class:`werkzeug.Map`\n- `import_string` accepts unicode strings as well now.\n- development server doesn't break on double slashes after the host name.\n- better `__repr__` and `__str__` of\n :exc:`werkzeug.exceptions.HTTPException`\n- test client works correctly with multiple cookies now.\n- the :class:`werkzeug.routing.Map` now has a class attribute with\n the default converter mapping. This helps subclasses to override\n the converters without passing them to the constructor.\n- implemented :class:`OrderedMultiDict`\n- improved the session support for more efficient session storing\n on the filesystem. Also added support for listing of sessions\n currently stored in the filesystem session store.\n- werkzeug no longer utilizes the Python time module for parsing\n which means that dates in a broader range can be parsed.\n- the wrappers have no class attributes that make it possible to\n swap out the dict and list types it uses.\n- werkzeug debugger should work on the appengine dev server now.\n- the URL builder supports dropping of unexpected arguments now.\n Previously they were always appended to the URL as query string.\n- profiler now writes to the correct stream.", "Version 0.5.1\n-------------\n(bugfix release for 0.5, released on July 9th 2009)", "- fixed boolean check of :class:`FileStorage`\n- url routing system properly supports unicode URL rules now.\n- file upload streams no longer have to provide a truncate()\n method.\n- implemented :meth:`BaseRequest._form_parsing_failed`.\n- fixed #394\n- :meth:`ImmutableDict.copy`, :meth:`ImmutableMultiDict.copy` and\n :meth:`ImmutableTypeConversionDict.copy` return mutable shallow\n copies.\n- fixed a bug with the `make_runserver` script action.\n- :meth:`MultiDict.items` and :meth:`MutiDict.iteritems` now accept an\n argument to return a pair for each value of each key.\n- the multipart parser works better with hand-crafted multipart\n requests now that have extra newlines added. This fixes a bug\n with setuptools uploads not handled properly (#390)\n- fixed some minor bugs in the atom feed generator.\n- fixed a bug with client cookie header parsing being case sensitive.\n- fixed a not-working deprecation warning.\n- fixed package loading for :class:`SharedDataMiddleware`.\n- fixed a bug in the secure cookie that made server-side expiration\n on servers with a local time that was not set to UTC impossible.\n- fixed console of the interactive debugger.", "\nVersion 0.5\n-----------", "Released on April 24th, codename Schlagbohrer.", "- requires Python 2.4 now\n- fixed a bug in :class:`~contrib.IterIO`\n- added :class:`MIMEAccept` and :class:`CharsetAccept` that work like the\n regular :class:`Accept` but have extra special normalization for mimetypes\n and charsets and extra convenience methods.\n- switched the serving system from wsgiref to something homebrew.\n- the :class:`Client` now supports cookies.\n- added the :mod:`~werkzeug.contrib.fixers` module with various\n fixes for webserver bugs and hosting setup side-effects.\n- added :mod:`werkzeug.contrib.wrappers`\n- added :func:`is_hop_by_hop_header`\n- added :func:`is_entity_header`\n- added :func:`remove_hop_by_hop_headers`\n- added :func:`pop_path_info`\n- added :func:`peek_path_info`\n- added :func:`wrap_file` and :class:`FileWrapper`\n- moved `LimitedStream` from the contrib package into the regular\n werkzeug one and changed the default behavior to raise exceptions\n rather than stopping without warning. The old class will stick in\n the module until 0.6.\n- implemented experimental multipart parser that replaces the old CGI hack.\n- added :func:`dump_options_header` and :func:`parse_options_header`\n- added :func:`quote_header_value` and :func:`unquote_header_value`\n- :func:`url_encode` and :func:`url_decode` now accept a separator\n argument to switch between `&` and `;` as pair separator. The magic\n switch is no longer in place.\n- all form data parsing functions as well as the :class:`BaseRequest`\n object have parameters (or attributes) to limit the number of\n incoming bytes (either totally or per field).\n- added :class:`LanguageAccept`\n- request objects are now enforced to be read only for all collections.\n- added many new collection classes, refactored collections in general.\n- test support was refactored, semi-undocumented `werkzeug.test.File`\n was replaced by :class:`werkzeug.FileStorage`.\n- :class:`EnvironBuilder` was added and unifies the previous distinct\n :func:`create_environ`, :class:`Client` and\n :meth:`BaseRequest.from_values`. They all work the same now which\n is less confusing.\n- officially documented imports from the internal modules as undefined\n behavior. These modules were never exposed as public interfaces.\n- removed `FileStorage.__len__` which previously made the object\n falsy for browsers not sending the content length which all browsers\n do.\n- :class:`SharedDataMiddleware` uses `wrap_file` now and has a\n configurable cache timeout.\n- added :class:`CommonRequestDescriptorsMixin`\n- added :attr:`CommonResponseDescriptorsMixin.mimetype_params`\n- added :mod:`werkzeug.contrib.lint`\n- added `passthrough_errors` to `run_simple`.\n- added `secure_filename`\n- added :func:`make_line_iter`\n- :class:`MultiDict` copies now instead of revealing internal\n lists to the caller for `getlist` and iteration functions that\n return lists.\n- added :attr:`follow_redirect` to the :func:`open` of :class:`Client`.\n- added support for `extra_files` in\n :func:`~werkzeug.script.make_runserver`", "Version 0.4.1\n-------------", "(Bugfix release, released on January 11th 2009)", "- `werkzeug.contrib.cache.Memcached` accepts now objects that\n implement the memcache.Client interface as alternative to a list of\n strings with server addresses.\n There is also now a `GAEMemcachedCache` that connects to the Google\n appengine cache.\n- explicitly convert secret keys to bytestrings now because Python\n 2.6 no longer does that.\n- `url_encode` and all interfaces that call it, support ordering of\n options now which however is disabled by default.\n- the development server no longer resolves the addresses of clients.\n- Fixed a typo in `werkzeug.test` that broke `File`.\n- `Map.bind_to_environ` uses the `Host` header now if available.\n- Fixed `BaseCache.get_dict` (#345)\n- `werkzeug.test.Client` can now run the application buffered in which\n case the application is properly closed automatically.\n- Fixed `Headers.set` (#354). Caused header duplication before.\n- Fixed `Headers.pop` (#349). default parameter was not properly\n handled.\n- Fixed UnboundLocalError in `create_environ` (#351)\n- `Headers` is more compatible with wsgiref now.\n- `Template.render` accepts multidicts now.\n- dropped support for Python 2.3", "Version 0.4\n-----------", "Released on November 23rd 2008, codename Schraubenzieher.", "- `Client` supports an empty `data` argument now.\n- fixed a bug in `Response.application` that made it impossible to use it\n as method decorator.\n- the session system should work on appengine now\n- the secure cookie works properly in load balanced environments with\n different cpu architectures now.\n- `CacheControl.no_cache` and `CacheControl.private` behavior changed to\n reflect the possibilities of the HTTP RFC. Setting these attributes to\n `None` or `True` now sets the value to \"the empty value\".\n More details in the documentation.\n- fixed `werkzeug.contrib.atom.AtomFeed.__call__`. (#338)\n- `BaseResponse.make_conditional` now always returns `self`. Previously\n it didn't for post requests and such.\n- fixed a bug in boolean attribute handling of `html` and `xhtml`.\n- added graceful error handling to the debugger pastebin feature.\n- added a more list like interface to `Headers` (slicing and indexing\n works now)\n- fixed a bug with the `__setitem__` method of `Headers` that didn't\n properly remove all keys on replacing.\n- added `remove_entity_headers` which removes all entity headers from\n a list of headers (or a `Headers` object)\n- the responses now automatically call `remove_entity_headers` if the\n status code is 304.\n- fixed a bug with `Href` query parameter handling. Previously the last\n item of a call to `Href` was not handled properly if it was a dict.\n- headers now support a `pop` operation to better work with environ\n properties.", "\nVersion 0.3.1\n-------------", "(bugfix release, released on June 24th 2008)", "- fixed a security problem with `werkzeug.contrib.SecureCookie`.", "\nVersion 0.3\n-----------", "Released on June 14th 2008, codename EUR325CAT6.", "- added support for redirecting in url routing.\n- added `Authorization` and `AuthorizationMixin`\n- added `WWWAuthenticate` and `WWWAuthenticateMixin`\n- added `parse_list_header`\n- added `parse_dict_header`\n- added `parse_authorization_header`\n- added `parse_www_authenticate_header`\n- added `_get_current_object` method to `LocalProxy` objects\n- added `parse_form_data`\n- `MultiDict`, `CombinedMultiDict`, `Headers`, and `EnvironHeaders` raise\n special key errors now that are subclasses of `BadRequest` so if you\n don't catch them they give meaningful HTTP responses.\n- added support for alternative encoding error handling and the new\n `HTTPUnicodeError` which (if not caught) behaves like a `BadRequest`.\n- added `BadRequest.wrap`.\n- added ETag support to the SharedDataMiddleware and added an option\n to disable caching.\n- fixed `is_xhr` on the request objects.\n- fixed error handling of the url adapter's `dispatch` method. (#318)\n- fixed bug with `SharedDataMiddleware`.\n- fixed `Accept.values`.\n- `EnvironHeaders` contain content-type and content-length now\n- `url_encode` treats lists and tuples in dicts passed to it as multiple\n values for the same key so that one doesn't have to pass a `MultiDict`\n to the function.\n- added `validate_arguments`\n- added `BaseRequest.application`\n- improved Python 2.3 support\n- `run_simple` accepts `use_debugger` and `use_evalex` parameters now,\n like the `make_runserver` factory function from the script module.\n- the `environ_property` is now read-only by default\n- it's now possible to initialize requests as \"shallow\" requests which\n causes runtime errors if the request object tries to consume the\n input stream.", "\nVersion 0.2\n-----------", "Released Feb 14th 2008, codename Faustkeil.", "- Added `AnyConverter` to the routing system.\n- Added `werkzeug.contrib.securecookie`\n- Exceptions have a ``get_response()`` method that return a response object\n- fixed the path ordering bug (#293), thanks Thomas Johansson\n- `BaseReporterStream` is now part of the werkzeug contrib module. From\n Werkzeug 0.3 onwards you will have to import it from there.\n- added `DispatcherMiddleware`.\n- `RequestRedirect` is now a subclass of `HTTPException` and uses a\n 301 status code instead of 302.\n- `url_encode` and `url_decode` can optionally treat keys as unicode strings\n now, too.\n- `werkzeug.script` has a different caller format for boolean arguments now.\n- renamed `lazy_property` to `cached_property`.\n- added `import_string`.\n- added is_* properties to request objects.\n- added `empty()` method to routing rules.\n- added `werkzeug.contrib.profiler`.\n- added `extends` to `Headers`.\n- added `dump_cookie` and `parse_cookie`.\n- added `as_tuple` to the `Client`.\n- added `werkzeug.contrib.testtools`.\n- added `werkzeug.unescape`\n- added `BaseResponse.freeze`\n- added `werkzeug.contrib.atom`\n- the HTTPExceptions accept an argument `description` now which overrides the\n default description.\n- the `MapAdapter` has a default for path info now. If you use\n `bind_to_environ` you don't have to pass the path later.\n- the wsgiref subclass werkzeug uses for the dev server does not use direct\n sys.stderr logging any more but a logger called \"werkzeug\".\n- implemented `Href`.\n- implemented `find_modules`\n- refactored request and response objects into base objects, mixins and\n full featured subclasses that implement all mixins.\n- added simple user agent parser\n- werkzeug's routing raises `MethodNotAllowed` now if it matches a\n rule but for a different method.\n- many fixes and small improvements", "\nVersion 0.1\n-----------", "Released on Dec 9th 2007, codename Wictorinoxger.", "- Initial release" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 69], "buggy_code_start_loc": [22, 69], "filenames": ["CHANGES.rst", "src/werkzeug/debug/__init__.py"], "fixing_code_end_loc": [25, 83], "fixing_code_start_loc": [23, 70], "message": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:palletsprojects:werkzeug:*:*:*:*:*:*:*:*", "matchCriteriaId": "2BEABB52-D59B-4CBF-AD1B-47B7F8909E70", "versionEndExcluding": "0.15.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id."}, {"lang": "es", "value": "Pallets Werkzeug en versiones anteriores a 0.15.3, cuando es usado con Docker, presenta una aleatoriedad insuficiente del PIN del depurador porque los contenedores Docker comparten la mismo id de m\u00e1quina."}], "evaluatorComment": null, "id": "CVE-2019-14806", "lastModified": "2023-03-03T19:34:49.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-08-09T15:15:12.917", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00047.html"}, {"source": "cve@mitre.org", "tags": ["Product"], "url": "https://github.com/pallets/werkzeug/blob/7fef41b120327d3912fbe12fb64f1951496fcf3e/src/werkzeug/debug/__init__.py#L168"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://palletsprojects.com/blog/werkzeug-0-15-3-released/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-331"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, "type": "CWE-331"}
108
Determine whether the {function_name} code is vulnerable or not.
[ ".. currentmodule:: werkzeug", "Version 0.15.3\n--------------", "Unreleased", "- Properly handle multi-line header folding in development server in\n Python 2.7. (:issue:`1080`)\n- Restore the ``response`` argument to :exc:`~exceptions.Unauthorized`.\n (:pr:`1527`)\n- :exc:`~exceptions.Unauthorized` doesn't add the ``WWW-Authenticate``\n header if ``www_authenticate`` is not given. (:issue:`1516`)\n- The default URL converter correctly encodes bytes to string rather\n than representing them with ``b''``. (:issue:`1502`)\n- Fix the filename format string in\n :class:`~middleware.profiler.ProfilerMiddleware` to correctly handle\n float values. (:issue:`1511`)\n- Update :class:`~middleware.lint.LintMiddleware` to work on Python 3.\n (:issue:`1510`)\n- The debugger detects cycles in chained exceptions and does not time\n out in that case. (:issue:`1536`)", "- When running the development server in Docker, the debugger security\n pin is now unique per container.", "", "Version 0.15.2\n--------------", "Released 2019-04-02", "- ``Rule`` code generation uses a filename that coverage will ignore.\n The previous value, \"generated\", was causing coverage to fail.\n (:issue:`1487`)\n- The test client removes the cookie header if there are no persisted\n cookies. This fixes an issue introduced in 0.15.0 where the cookies\n from the original request were used for redirects, causing functions\n such as logout to fail. (:issue:`1491`)\n- The test client copies the environ before passing it to the app, to\n prevent in-place modifications from affecting redirect requests.\n (:issue:`1498`)\n- The ``\"werkzeug\"`` logger only adds a handler if there is no handler\n configured for its level in the logging chain. This avoids double\n logging if other code configures logging first. (:issue:`1492`)", "\nVersion 0.15.1\n--------------", "Released 2019-03-21", "- :exc:`~exceptions.Unauthorized` takes ``description`` as the first\n argument, restoring previous behavior. The new ``www_authenticate``\n argument is listed second. (:issue:`1483`)", "\nVersion 0.15.0\n--------------", "Released 2019-03-19", "- Building URLs is ~7x faster. Each :class:`~routing.Rule` compiles\n an optimized function for building itself. (:pr:`1281`)\n- :meth:`MapAdapter.build() <routing.MapAdapter.build>` can be passed\n a :class:`~datastructures.MultiDict` to represent multiple values\n for a key. It already did this when passing a dict with a list\n value. (:pr:`724`)\n- ``path_info`` defaults to ``'/'`` for\n :meth:`Map.bind() <routing.Map.bind>`. (:issue:`740`, :pr:`768`,\n :pr:`1316`)\n- Change ``RequestRedirect`` code from 301 to 308, preserving the verb\n and request body (form data) during redirect. (:pr:`1342`)\n- ``int`` and ``float`` converters in URL rules will handle negative\n values if passed the ``signed=True`` parameter. For example,\n ``/jump/<int(signed=True):count>``. (:pr:`1355`)\n- ``Location`` autocorrection in :func:`Response.get_wsgi_headers()\n <wrappers.BaseResponse.get_wsgi_headers>` is relative to the current\n path rather than the root path. (:issue:`693`, :pr:`718`,\n :pr:`1315`)\n- 412 responses once again include entity headers and an error message\n in the body. They were originally omitted when implementing\n ``If-Match`` (:pr:`1233`), but the spec doesn't seem to disallow it.\n (:issue:`1231`, :pr:`1255`)\n- The Content-Length header is removed for 1xx and 204 responses. This\n fixes a previous change where no body would be sent, but the header\n would still be present. The new behavior matches RFC 7230.\n (:pr:`1294`)\n- :class:`~exceptions.Unauthorized` takes a ``www_authenticate``\n parameter to set the ``WWW-Authenticate`` header for the response,\n which is technically required for a valid 401 response.\n (:issue:`772`, :pr:`795`)\n- Add support for status code 424 :exc:`~exceptions.FailedDependency`.\n (:pr:`1358`)\n- :func:`http.parse_cookie` ignores empty segments rather than\n producing a cookie with no key or value. (:issue:`1245`, :pr:`1301`)\n- :func:`~http.parse_authorization_header` (and\n :class:`~datastructures.Authorization`,\n :attr:`~wrappers.Request.authorization`) treats the authorization\n header as UTF-8. On Python 2, basic auth username and password are\n ``unicode``. (:pr:`1325`)\n- :func:`~http.parse_options_header` understands :rfc:`2231` parameter\n continuations. (:pr:`1417`)\n- :func:`~urls.uri_to_iri` does not unquote ASCII characters in the\n unreserved class, such as space, and leaves invalid bytes quoted\n when decoding. :func:`~urls.iri_to_uri` does not quote reserved\n characters. See :rfc:`3987` for these character classes.\n (:pr:`1433`)\n- ``get_content_type`` appends a charset for any mimetype that ends\n with ``+xml``, not just those that start with ``application/``.\n Known text types such as ``application/javascript`` are also given\n charsets. (:pr:`1439`)\n- Clean up ``werkzeug.security`` module, remove outdated hashlib\n support. (:pr:`1282`)\n- In :func:`~security.generate_password_hash`, PBKDF2 uses 150000\n iterations by default, increased from 50000. (:pr:`1377`)\n- :class:`~wsgi.ClosingIterator` calls ``close`` on the wrapped\n *iterable*, not the internal iterator. This doesn't affect objects\n where ``__iter__`` returned ``self``. For other objects, the method\n was not called before. (:issue:`1259`, :pr:`1260`)\n- Bytes may be used as keys in :class:`~datastructures.Headers`, they\n will be decoded as Latin-1 like values are. (:pr:`1346`)\n- :class:`~datastructures.Range` validates that list of range tuples\n passed to it would produce a valid ``Range`` header. (:pr:`1412`)\n- :class:`~datastructures.FileStorage` looks up attributes on\n ``stream._file`` if they don't exist on ``stream``, working around\n an issue where :func:`tempfile.SpooledTemporaryFile` didn't\n implement all of :class:`io.IOBase`. See\n https://github.com/python/cpython/pull/3249. (:pr:`1409`)\n- :class:`CombinedMultiDict.copy() <datastructures.CombinedMultiDict>`\n returns a shallow mutable copy as a\n :class:`~datastructures.MultiDict`. The copy no longer reflects\n changes to the combined dicts, but is more generally useful.\n (:pr:`1420`)\n- The version of jQuery used by the debugger is updated to 3.3.1.\n (:pr:`1390`)\n- The debugger correctly renders long ``markupsafe.Markup`` instances.\n (:pr:`1393`)\n- The debugger can serve resources when Werkzeug is installed as a\n zip file. ``DebuggedApplication.get_resource`` uses\n ``pkgutil.get_data``. (:pr:`1401`)\n- The debugger and server log support Python 3's chained exceptions.\n (:pr:`1396`)\n- The interactive debugger highlights frames that come from user code\n to make them easy to pick out in a long stack trace. Note that if an\n env was created with virtualenv instead of venv, the debugger may\n incorrectly classify some frames. (:pr:`1421`)\n- Clicking the error message at the top of the interactive debugger\n will jump down to the bottom of the traceback. (:pr:`1422`)\n- When generating a PIN, the debugger will ignore a ``KeyError``\n raised when the current UID doesn't have an associated username,\n which can happen in Docker. (:issue:`1471`)\n- :class:`~exceptions.BadRequestKeyError` adds the ``KeyError``\n message to the description, making it clearer what caused the 400\n error. Frameworks like Flask can omit this information in production\n by setting ``e.args = ()``. (:pr:`1395`)\n- If a nested ``ImportError`` occurs from :func:`~utils.import_string`\n the traceback mentions the nested import. Removes an untested code\n path for handling \"modules not yet set up by the parent.\"\n (:pr:`735`)\n- Triggering a reload while using a tool such as PDB no longer hides\n input. (:pr:`1318`)\n- The reloader will not prepend the Python executable to the command\n line if the Python file is marked executable. This allows the\n reloader to work on NixOS. (:pr:`1242`)\n- Fix an issue where ``sys.path`` would change between reloads when\n running with ``python -m app``. The reloader can detect that a\n module was run with \"-m\" and reconstructs that instead of the file\n path in ``sys.argv`` when reloading. (:pr:`1416`)\n- The dev server can bind to a Unix socket by passing a hostname like\n ``unix://app.socket``. (:pr:`209`, :pr:`1019`)\n- Server uses ``IPPROTO_TCP`` constant instead of ``SOL_TCP`` for\n Jython compatibility. (:pr:`1375`)\n- When using an adhoc SSL cert with :func:`~serving.run_simple`, the\n cert is shown as self-signed rather than signed by an invalid\n authority. (:pr:`1430`)\n- The development server logs the unquoted IRI rather than the raw\n request line, to make it easier to work with Unicode in request\n paths during development. (:issue:`1115`)\n- The development server recognizes ``ConnectionError`` on Python 3 to\n silence client disconnects, and does not silence other ``OSErrors``\n that may have been raised inside the application. (:pr:`1418`)\n- The environ keys ``REQUEST_URI`` and ``RAW_URI`` contain the raw\n path before it was percent-decoded. This is non-standard, but many\n WSGI servers add them. Middleware could replace ``PATH_INFO`` with\n this to route based on the raw value. (:pr:`1419`)\n- :class:`~test.EnvironBuilder` doesn't set ``CONTENT_TYPE`` or\n ``CONTENT_LENGTH`` in the environ if they aren't set. Previously\n these used default values if they weren't set. Now it's possible to\n distinguish between empty and unset values. (:pr:`1308`)\n- The test client raises a ``ValueError`` if a query string argument\n would overwrite a query string in the path. (:pr:`1338`)\n- :class:`test.EnvironBuilder` and :class:`test.Client` take a\n ``json`` argument instead of manually passing ``data`` and\n ``content_type``. This is serialized using the\n :meth:`test.EnvironBuilder.json_dumps` method. (:pr:`1404`)\n- :class:`test.Client` redirect handling is rewritten. (:pr:`1402`)", " - The redirect environ is copied from the initial request environ.\n - Script root and path are correctly distinguished when\n redirecting to a path under the root.\n - The HEAD method is not changed to GET.\n - 307 and 308 codes preserve the method and body. All others\n ignore the body and related headers.\n - Headers are passed to the new request for all codes, following\n what browsers do.\n - :class:`test.EnvironBuilder` sets the content type and length\n headers in addition to the WSGI keys when detecting them from\n the data.\n - Intermediate response bodies are iterated over even when\n ``buffered=False`` to ensure iterator middleware can run cleanup\n code safely. Only the last response is not buffered. (:pr:`988`)", "- :class:`~test.EnvironBuilder`, :class:`~datastructures.FileStorage`,\n and :func:`wsgi.get_input_stream` no longer share a global\n ``_empty_stream`` instance. This improves test isolation by\n preventing cases where closing the stream in one request would\n affect other usages. (:pr:`1340`)\n- The default :attr:`SecureCookie.serialization_method\n <contrib.securecookie.SecureCookie.serialization_method>` will\n change from :mod:`pickle` to :mod:`json` in 1.0. To upgrade existing\n tokens, override :meth:`~contrib.securecookie.SecureCookie.unquote`\n to try ``pickle`` if ``json`` fails. (:pr:`1413`)\n- ``CGIRootFix`` no longer modifies ``PATH_INFO`` for very old\n versions of Lighttpd. ``LighttpdCGIRootFix`` was renamed to\n ``CGIRootFix`` in 0.9. Both are deprecated and will be removed in\n version 1.0. (:pr:`1141`)\n- :class:`werkzeug.wrappers.json.JSONMixin` has been replaced with\n Flask's implementation. Check the docs for the full API.\n (:pr:`1445`)\n- The :doc:`contrib modules </contrib/index>` are deprecated and will\n either be moved into ``werkzeug`` core or removed completely in\n version 1.0. Some modules that already issued deprecation warnings\n have been removed. Be sure to run or test your code with\n ``python -W default::DeprecationWarning`` to catch any deprecated\n code you're using. (:issue:`4`)", " - ``LintMiddleware`` has moved to :mod:`werkzeug.middleware.lint`.\n - ``ProfilerMiddleware`` has moved to\n :mod:`werkzeug.middleware.profiler`.\n - ``ProxyFix`` has moved to :mod:`werkzeug.middleware.proxy_fix`.\n - ``JSONRequestMixin`` has moved to :mod:`werkzeug.wrappers.json`.\n - ``cache`` has been extracted into a separate project,\n `cachelib <https://github.com/pallets/cachelib>`_. The version\n in Werkzeug is deprecated.\n - ``securecookie`` and ``sessions`` have been extracted into a\n separate project,\n `secure-cookie <https://github.com/pallets/secure-cookie>`_. The\n version in Werkzeug is deprecated.\n - Everything in ``fixers``, except ``ProxyFix``, is deprecated.\n - Everything in ``wrappers``, except ``JSONMixin``, is deprecated.\n - ``atom`` is deprecated. This did not fit in with the rest of\n Werkzeug, and is better served by a dedicated library in the\n community.\n - ``jsrouting`` is removed. Set URLs when rendering templates\n or JSON responses instead.\n - ``limiter`` is removed. Its specific use is handled by Werkzeug\n directly, but stream limiting is better handled by the WSGI\n server in general.\n - ``testtools`` is removed. It did not offer significant benefit\n over the default test client.\n - ``iterio`` is deprecated.", "- :func:`wsgi.get_host` no longer looks at ``X-Forwarded-For``. Use\n :class:`~middleware.proxy_fix.ProxyFix` to handle that.\n (:issue:`609`, :pr:`1303`)\n- :class:`~middleware.proxy_fix.ProxyFix` is refactored to support\n more headers, multiple values, and more secure configuration.", " - Each header supports multiple values. The trusted number of\n proxies is configured separately for each header. The\n ``num_proxies`` argument is deprecated. (:pr:`1314`)\n - Sets ``SERVER_NAME`` and ``SERVER_PORT`` based on\n ``X-Forwarded-Host``. (:pr:`1314`)\n - Sets ``SERVER_PORT`` and modifies ``HTTP_HOST`` based on\n ``X-Forwarded-Port``. (:issue:`1023`, :pr:`1304`)\n - Sets ``SCRIPT_NAME`` based on ``X-Forwarded-Prefix``.\n (:issue:`1237`)\n - The original WSGI environment values are stored in the\n ``werkzeug.proxy_fix.orig`` key, a dict. The individual keys\n ``werkzeug.proxy_fix.orig_remote_addr``,\n ``werkzeug.proxy_fix.orig_wsgi_url_scheme``, and\n ``werkzeug.proxy_fix.orig_http_host`` are deprecated.", "- Middleware from ``werkzeug.wsgi`` has moved to separate modules\n under ``werkzeug.middleware``, along with the middleware moved from\n ``werkzeug.contrib``. The old ``werkzeug.wsgi`` imports are\n deprecated and will be removed in version 1.0. (:pr:`1452`)", " - ``werkzeug.wsgi.DispatcherMiddleware`` has moved to\n :class:`werkzeug.middleware.dispatcher.DispatcherMiddleware`.\n - ``werkzeug.wsgi.ProxyMiddleware`` as moved to\n :class:`werkzeug.middleware.http_proxy.ProxyMiddleware`.\n - ``werkzeug.wsgi.SharedDataMiddleware`` has moved to\n :class:`werkzeug.middleware.shared_data.SharedDataMiddleware`.", "- :class:`~middleware.http_proxy.ProxyMiddleware` proxies the query\n string. (:pr:`1252`)\n- The filenames generated by\n :class:`~middleware.profiler.ProfilerMiddleware` can be customized.\n (:issue:`1283`)\n- The ``werkzeug.wrappers`` module has been converted to a package,\n and its various classes have been organized into separate modules.\n Any previously documented classes, understood to be the existing\n public API, are still importable from ``werkzeug.wrappers``, or may\n be imported from their specific modules. (:pr:`1456`)", "\nVersion 0.14.1\n--------------", "Released on December 31st 2017", "- Resolved a regression with status code handling in the integrated\n development server.", "Version 0.14\n------------", "Released on December 31st 2017", "- HTTP exceptions are now automatically caught by\n ``Request.application``.\n- Added support for edge as browser.\n- Added support for platforms that lack ``SpooledTemporaryFile``.\n- Add support for etag handling through if-match\n- Added support for the SameSite cookie attribute.\n- Added ``werkzeug.wsgi.ProxyMiddleware``\n- Implemented ``has`` for ``NullCache``\n- ``get_multi`` on cache clients now returns lists all the time.\n- Improved the watchdog observer shutdown for the reloader to not crash\n on exit on older Python versions.\n- Added support for ``filename*`` filename attributes according to\n RFC 2231\n- Resolved an issue where machine ID for the reloader PIN was not\n read accurately on windows.\n- Added a workaround for syntax errors in init files in the reloader.\n- Added support for using the reloader with console scripts on windows.\n- The built-in HTTP server will no longer close a connection in cases\n where no HTTP body is expected (204, 204, HEAD requests etc.)\n- The ``EnvironHeaders`` object now skips over empty content type and\n lengths if they are set to falsy values.\n- Werkzeug will no longer send the content-length header on 1xx or\n 204/304 responses.\n- Cookie values are now also permitted to include slashes and equal\n signs without quoting.\n- Relaxed the regex for the routing converter arguments.\n- If cookies are sent without values they are now assumed to have an\n empty value and the parser accepts this. Previously this could have\n corrupted cookies that followed the value.\n- The test ``Client`` and ``EnvironBuilder`` now support mimetypes like\n the request object does.\n- Added support for static weights in URL rules.\n- Better handle some more complex reloader scenarios where sys.path\n contained non directory paths.\n- ``EnvironHeaders`` no longer raises weird errors if non string keys\n are passed to it.", "\nVersion 0.13\n------------", "Released on December 7th 2017", "- **Deprecate support for Python 2.6 and 3.3.** CI tests will not run\n for these versions, and support will be dropped completely in the next\n version. (:issue:`pallets/meta#24`)\n- Raise ``TypeError`` when port is not an integer. (:pr:`1088`)\n- Fully deprecate ``werkzeug.script``. Use `Click`_ instead.\n (:pr:`1090`)\n- ``response.age`` is parsed as a ``timedelta``. Previously, it was\n incorrectly treated as a ``datetime``. The header value is an integer\n number of seconds, not a date string. (:pr:`414`)\n- Fix a bug in ``TypeConversionDict`` where errors are not propagated\n when using the converter. (:issue:`1102`)\n- ``Authorization.qop`` is a string instead of a set, to comply with\n RFC 2617. (:pr:`984`)\n- An exception is raised when an encoded cookie is larger than, by\n default, 4093 bytes. Browsers may silently ignore cookies larger than\n this. ``BaseResponse`` has a new attribute ``max_cookie_size`` and\n ``dump_cookie`` has a new argument ``max_size`` to configure this.\n (:pr:`780`, :pr:`1109`)\n- Fix a TypeError in ``werkzeug.contrib.lint.GuardedIterator.close``.\n (:pr:`1116`)\n- ``BaseResponse.calculate_content_length`` now correctly works for\n Unicode responses on Python 3. It first encodes using\n ``iter_encoded``. (:issue:`705`)\n- Secure cookie contrib works with string secret key on Python 3.\n (:pr:`1205`)\n- Shared data middleware accepts a list instead of a dict of static\n locations to preserve lookup order. (:pr:`1197`)\n- HTTP header values without encoding can contain single quotes.\n (:pr:`1208`)\n- The built-in dev server supports receiving requests with chunked\n transfer encoding. (:pr:`1198`)", ".. _Click: https://palletsprojects.com/p/click/", "\nVersion 0.12.2\n--------------", "Released on May 16 2017", "- Fix regression: Pull request ``#892`` prevented Werkzeug from correctly\n logging the IP of a remote client behind a reverse proxy, even when using\n `ProxyFix`.\n- Fix a bug in `safe_join` on Windows.", "Version 0.12.1\n--------------", "Released on March 15th 2017", "- Fix crash of reloader (used on debug mode) on Windows.\n (`OSError: [WinError 10038]`). See pull request ``#1081``\n- Partially revert change to class hierarchy of `Headers`. See ``#1084``.", "Version 0.12\n------------", "Released on March 10th 2017", "- Spit out big deprecation warnings for werkzeug.script\n- Use `inspect.getfullargspec` internally when available as\n `inspect.getargspec` is gone in 3.6\n- Added support for status code 451 and 423\n- Improved the build error suggestions. In particular only if\n someone stringifies the error will the suggestions be calculated.\n- Added support for uWSGI's caching backend.\n- Fix a bug where iterating over a `FileStorage` would result in an infinite\n loop.\n- Datastructures now inherit from the relevant baseclasses from the\n `collections` module in the stdlib. See #794.\n- Add support for recognizing NetBSD, OpenBSD, FreeBSD, DragonFlyBSD platforms\n in the user agent string.\n- Recognize SeaMonkey browser name and version correctly\n- Recognize Baiduspider, and bingbot user agents\n- If `LocalProxy`'s wrapped object is a function, refer to it with __wrapped__\n attribute.\n- The defaults of ``generate_password_hash`` have been changed to more secure\n ones, see pull request ``#753``.\n- Add support for encoding in options header parsing, see pull request\n ``#933``.\n- ``test.Client`` now properly handles Location headers with relative URLs, see\n pull request ``#879``.\n- When `HTTPException` is raised, it now prints the description, for easier\n debugging.\n- Werkzeug's dict-like datastructures now have ``view``-methods under Python 2,\n see pull request ``#968``.\n- Fix a bug in ``MultiPartParser`` when no ``stream_factory`` was provided\n during initialization, see pull request ``#973``.\n- Disable autocorrect and spellchecker in the debugger middleware's Python\n prompt, see pull request ``#994``.\n- Don't redirect to slash route when method doesn't match, see pull request\n ``#907``.\n- Fix a bug when using ``SharedDataMiddleware`` with frozen packages, see pull\n request ``#959``.\n- `Range` header parsing function fixed for invalid values ``#974``.\n- Add support for byte Range Requests, see pull request ``#978``.\n- Use modern cryptographic defaults in the dev servers ``#1004``.\n- the post() method of the test client now accept file object through the data\n parameter.\n- Color run_simple's terminal output based on HTTP codes ``#1013``.\n- Fix self-XSS in debugger console, see ``#1031``.\n- Fix IPython 5.x shell support, see ``#1033``.\n- Change Accept datastructure to sort by specificity first, allowing for more\n accurate results when using ``best_match`` for mime types (for example in\n ``requests.accept_mimetypes.best_match``)", "Version 0.11.16\n---------------", "- werkzeug.serving: set CONTENT_TYPE / CONTENT_LENGTH if only they're provided by the client\n- werkzeug.serving: Fix crash of reloader when using `python -m werkzeug.serving`.", "Version 0.11.15\n---------------", "Released on December 30th 2016.", "- Bugfix for the bugfix in the previous release.", "Version 0.11.14\n---------------", "Released on December 30th 2016.", "- Check if platform can fork before importing ``ForkingMixIn``, raise exception\n when creating ``ForkingWSGIServer`` on such a platform, see PR ``#999``.", "Version 0.11.13\n---------------", "Released on December 26th 2016.", "- Correct fix for the reloader issuer on certain Windows installations.", "Version 0.11.12\n---------------", "Released on December 26th 2016.", "- Fix more bugs in multidicts regarding empty lists. See ``#1000``.\n- Add some docstrings to some `EnvironBuilder` properties that were previously\n unintentionally missing.\n- Added a workaround for the reloader on windows.", "Version 0.11.11\n---------------", "Released on August 31st 2016.", "- Fix JSONRequestMixin for Python3. See #731\n- Fix broken string handling in test client when passing integers. See #852\n- Fix a bug in ``parse_options_header`` where an invalid content type\n starting with comma or semi-colon would result in an invalid return value,\n see issue ``#995``.\n- Fix a bug in multidicts when passing empty lists as values, see issue\n ``#979``.\n- Fix a security issue that allows XSS on the Werkzeug debugger. See ``#1001``.", "Version 0.11.10\n---------------", "Released on May 24th 2016.", "- Fixed a bug that occurs when running on Python 2.6 and using a broken locale.\n See pull request #912.\n- Fixed a crash when running the debugger on Google App Engine. See issue #925.\n- Fixed an issue with multipart parsing that could cause memory exhaustion.", "Version 0.11.9\n--------------", "Released on April 24th 2016.", "- Corrected an issue that caused the debugger not to use the\n machine GUID on POSIX systems.\n- Corrected a Unicode error on Python 3 for the debugger's\n PIN usage.\n- Corrected the timestamp verification in the pin debug code.\n Without this fix the pin was remembered for too long.", "Version 0.11.8\n--------------", "Released on April 15th 2016.", "- fixed a problem with the machine GUID detection code on OS X\n on Python 3.", "Version 0.11.7\n--------------", "Released on April 14th 2016.", "- fixed a regression on Python 3 for the debugger.", "Version 0.11.6\n--------------", "Released on April 14th 2016.", "- werkzeug.serving: Still show the client address on bad requests.\n- improved the PIN based protection for the debugger to make it harder to\n brute force via trying cookies. Please keep in mind that the debugger\n *is not intended for running on production environments*\n- increased the pin timeout to a week to make it less annoying for people\n which should decrease the chance that users disable the pin check\n entirely.\n- werkzeug.serving: Fix broken HTTP_HOST when path starts with double slash.", "Version 0.11.5\n--------------", "Released on March 22nd 2016.", "- werkzeug.serving: Fix crash when attempting SSL connection to HTTP server.", "Version 0.11.4\n--------------", "Released on February 14th 2016.", "- Fixed werkzeug.serving not working from -m flag.\n- Fixed incorrect weak etag handling.", "Version 0.11.3\n--------------", "Released on December 20th 2015.", "- Fixed an issue with copy operations not working against\n proxies.\n- Changed the logging operations of the development server to\n correctly log where the server is running in all situations\n again.\n- Fixed another regression with SSL wrapping similar to the\n fix in 0.11.2 but for a different code path.", "Version 0.11.2\n--------------", "Released on November 12th 2015.", "- Fix inheritable sockets on Windows on Python 3.\n- Fixed an issue with the forking server not starting any longer.\n- Fixed SSL wrapping on platforms that supported opening sockets\n by file descriptor.\n- No longer log from the watchdog reloader.\n- Unicode errors in hosts are now better caught or converted into\n bad request errors.", "Version 0.11.1\n--------------", "Released on November 10th 2015.", "- Fixed a regression on Python 3 in the debugger.", "Version 0.11\n------------", "Released on November 8th 2015, codename Gleisbaumaschine.", "- Added ``reloader_paths`` option to ``run_simple`` and other functions in\n ``werkzeug.serving``. This allows the user to completely override the Python\n module watching of Werkzeug with custom paths.\n- Many custom cached properties of Werkzeug's classes are now subclasses of\n Python's ``property`` type (issue ``#616``).\n- ``bind_to_environ`` now doesn't differentiate between implicit and explicit\n default port numbers in ``HTTP_HOST`` (pull request ``#204``).\n- ``BuildErrors`` are now more informative. They come with a complete sentence\n as error message, and also provide suggestions (pull request ``#691``).\n- Fix a bug in the user agent parser where Safari's build number instead of\n version would be extracted (pull request ``#703``).\n- Fixed issue where RedisCache set_many was broken for twemproxy, which doesn't\n support the default MULTI command (pull request ``#702``).\n- ``mimetype`` parameters on request and response classes are now always\n converted to lowercase.\n- Changed cache so that cache never expires if timeout is 0. This also fixes\n an issue with redis setex (issue ``#550``)\n- Werkzeug now assumes ``UTF-8`` as filesystem encoding on Unix if Python\n detected it as ASCII.\n- New optional `has` method on caches.\n- Fixed various bugs in `parse_options_header` (pull request ``#643``).\n- If the reloader is enabled the server will now open the socket in the parent\n process if this is possible. This means that when the reloader kicks in\n the connection from client will wait instead of tearing down. This does\n not work on all Python versions.\n- Implemented PIN based authentication for the debugger. This can optionally\n be disabled but is discouraged. This change was necessary as it has been\n discovered that too many people run the debugger in production.\n- Devserver no longer requires SSL module to be installed.", "Version 0.10.5\n--------------", "(bugfix release, release date yet to be decided)", "- Reloader: Correctly detect file changes made by moving temporary files over\n the original, which is e.g. the case with PyCharm (pull request ``#722``).\n- Fix bool behavior of ``werkzeug.datastructures.ETags`` under Python 3 (issue\n ``#744``).", "Version 0.10.4\n--------------", "(bugfix release, released on March 26th 2015)", "- Re-release of 0.10.3 with packaging artifacts manually removed.", "Version 0.10.3\n--------------", "(bugfix release, released on March 26th 2015)", "- Re-release of 0.10.2 without packaging artifacts.", "Version 0.10.2\n--------------", "(bugfix release, released on March 26th 2015)", "- Fixed issue where ``empty`` could break third-party libraries that relied on\n keyword arguments (pull request ``#675``)\n- Improved ``Rule.empty`` by providing a ```get_empty_kwargs`` to allow setting\n custom kwargs without having to override entire ``empty`` method. (pull\n request ``#675``)\n- Fixed ```extra_files``` parameter for reloader to not cause startup\n to crash when included in server params\n- Using `MultiDict` when building URLs is now not supported again. The behavior\n introduced several regressions.\n- Fix performance problems with stat-reloader (pull request ``#715``).", "Version 0.10.1\n--------------", "(bugfix release, released on February 3rd 2015)", "- Fixed regression with multiple query values for URLs (pull request ``#667``).\n- Fix issues with eventlet's monkeypatching and the builtin server (pull\n request ``#663``).", "Version 0.10\n------------", "Released on January 30th 2015, codename Bagger.", "- Changed the error handling of and improved testsuite for the caches in\n ``contrib.cache``.\n- Fixed a bug on Python 3 when creating adhoc ssl contexts, due to `sys.maxint`\n not being defined.\n- Fixed a bug on Python 3, that caused\n :func:`~werkzeug.serving.make_ssl_devcert` to fail with an exception.\n- Added exceptions for 504 and 505.\n- Added support for ChromeOS detection.\n- Added UUID converter to the routing system.\n- Added message that explains how to quit the server.\n- Fixed a bug on Python 2, that caused ``len`` for\n :class:`werkzeug.datastructures.CombinedMultiDict` to crash.\n- Added support for stdlib pbkdf2 hmac if a compatible digest\n is found.\n- Ported testsuite to use ``py.test``.\n- Minor optimizations to various middlewares (pull requests ``#496`` and\n ``#571``).\n- Use stdlib ``ssl`` module instead of ``OpenSSL`` for the builtin server\n (issue ``#434``). This means that OpenSSL contexts are not supported anymore,\n but instead ``ssl.SSLContext`` from the stdlib.\n- Allow protocol-relative URLs when building external URLs.\n- Fixed Atom syndication to print time zone offset for tz-aware datetime\n objects (pull request ``#254``).\n- Improved reloader to track added files and to recover from broken\n sys.modules setups with syntax errors in packages.\n- ``cache.RedisCache`` now supports arbitrary ``**kwargs`` for the redis\n object.\n- ``werkzeug.test.Client`` now uses the original request method when resolving\n 307 redirects (pull request ``#556``).\n- ``werkzeug.datastructures.MIMEAccept`` now properly deals with mimetype\n parameters (pull request ``#205``).\n- ``werkzeug.datastructures.Accept`` now handles a quality of ``0`` as\n intolerable, as per RFC 2616 (pull request ``#536``).\n- ``werkzeug.urls.url_fix`` now properly encodes hostnames with ``idna``\n encoding (issue ``#559``). It also doesn't crash on malformed URLs anymore\n (issue ``#582``).\n- ``werkzeug.routing.MapAdapter.match`` now recognizes the difference between\n the path ``/`` and an empty one (issue ``#360``).\n- The interactive debugger now tries to decode non-ascii filenames (issue\n ``#469``).\n- Increased default key size of generated SSL certificates to 1024 bits (issue\n ``#611``).\n- Added support for specifying a ``Response`` subclass to use when calling\n :func:`~werkzeug.utils.redirect`\\ .\n- ``werkzeug.test.EnvironBuilder`` now doesn't use the request method anymore\n to guess the content type, and purely relies on the ``form``, ``files`` and\n ``input_stream`` properties (issue ``#620``).\n- Added Symbian to the user agent platform list.\n- Fixed make_conditional to respect automatically_set_content_length\n- Unset ``Content-Length`` when writing to response.stream (issue ``#451``)\n- ``wrappers.Request.method`` is now always uppercase, eliminating\n inconsistencies of the WSGI environment (issue ``647``).\n- ``routing.Rule.empty`` now works correctly with subclasses of ``Rule`` (pull\n request ``#645``).\n- Made map updating safe in light of concurrent updates.\n- Allow multiple values for the same field for url building (issue ``#658``).", "Version 0.9.7\n-------------", "(bugfix release, release date to be decided)", "- Fix unicode problems in ``werkzeug.debug.tbtools``.\n- Fix Python 3-compatibility problems in ``werkzeug.posixemulation``.\n- Backport fix of fatal typo for ``ImmutableList`` (issue ``#492``).\n- Make creation of the cache dir for ``FileSystemCache`` atomic (issue\n ``#468``).\n- Use native strings for memcached keys to work with Python 3 client (issue\n ``#539``).\n- Fix charset detection for ``werkzeug.debug.tbtools.Frame`` objects (issues\n ``#547`` and ``#532``).\n- Fix ``AttributeError`` masking in ``werkzeug.utils.import_string`` (issue\n ``#182``).\n- Explicitly shut down server (issue ``#519``).\n- Fix timeouts greater than 2592000 being misinterpreted as UNIX timestamps in\n ``werkzeug.contrib.cache.MemcachedCache`` (issue ``#533``).\n- Fix bug where ``werkzeug.exceptions.abort`` would raise an arbitrary subclass\n of the expected class (issue ``#422``).\n- Fix broken ``jsrouting`` (due to removal of ``werkzeug.templates``)\n- ``werkzeug.urls.url_fix`` now doesn't crash on malformed URLs anymore, but\n returns them unmodified. This is a cheap workaround for ``#582``, the proper\n fix is included in version 0.10.\n- The repr of ``werkzeug.wrappers.Request`` doesn't crash on non-ASCII-values\n anymore (pull request ``#466``).\n- Fix bug in ``cache.RedisCache`` when combined with ``redis.StrictRedis``\n object (pull request ``#583``).\n- The ``qop`` parameter for ``WWW-Authenticate`` headers is now always quoted,\n as required by RFC 2617 (issue ``#633``).\n- Fix bug in ``werkzeug.contrib.cache.SimpleCache`` with Python 3 where add/set\n may throw an exception when pruning old entries from the cache (pull request\n ``#651``).", "Version 0.9.6\n-------------", "(bugfix release, released on June 7th 2014)", "- Added a safe conversion for IRI to URI conversion and use that\n internally to work around issues with spec violations for\n protocols such as ``itms-service``.", "Version 0.9.7\n-------------", "- Fixed uri_to_iri() not re-encoding hashes in query string parameters.", "Version 0.9.5\n-------------", "(bugfix release, released on June 7th 2014)", "- Forward charset argument from request objects to the environ\n builder.\n- Fixed error handling for missing boundaries in multipart data.\n- Fixed session creation on systems without ``os.urandom()``.\n- Fixed pluses in dictionary keys not being properly URL encoded.\n- Fixed a problem with deepcopy not working for multi dicts.\n- Fixed a double quoting issue on redirects.\n- Fixed a problem with unicode keys appearing in headers on 2.x.\n- Fixed a bug with unicode strings in the test builder.\n- Fixed a unicode bug on Python 3 in the WSGI profiler.\n- Fixed an issue with the safe string compare function on\n Python 2.7.7 and Python 3.4.", "Version 0.9.4\n-------------", "(bugfix release, released on August 26th 2013)", "- Fixed an issue with Python 3.3 and an edge case in cookie parsing.\n- Fixed decoding errors not handled properly through the WSGI\n decoding dance.\n- Fixed URI to IRI conversion incorrectly decoding percent signs.", "Version 0.9.3\n-------------", "(bugfix release, released on July 25th 2013)", "- Restored behavior of the ``data`` descriptor of the request class to pre 0.9\n behavior. This now also means that ``.data`` and ``.get_data()`` have\n different behavior. New code should use ``.get_data()`` always.", " In addition to that there is now a flag for the ``.get_data()`` method that\n controls what should happen with form data parsing and the form parser will\n honor cached data. This makes dealing with custom form data more consistent.", "Version 0.9.2\n-------------", "(bugfix release, released on July 18th 2013)", "- Added `unsafe` parameter to :func:`~werkzeug.urls.url_quote`.\n- Fixed an issue with :func:`~werkzeug.urls.url_quote_plus` not quoting\n `'+'` correctly.\n- Ported remaining parts of :class:`~werkzeug.contrib.RedisCache` to\n Python 3.3.\n- Ported remaining parts of :class:`~werkzeug.contrib.MemcachedCache` to\n Python 3.3\n- Fixed a deprecation warning in the contrib atom module.\n- Fixed a regression with setting of content types through the\n headers dictionary instead with the content type parameter.\n- Use correct name for stdlib secure string comparison function.\n- Fixed a wrong reference in the docstring of\n :func:`~werkzeug.local.release_local`.\n- Fixed an `AttributeError` that sometimes occurred when accessing the\n :attr:`werkzeug.wrappers.BaseResponse.is_streamed` attribute.", "Version 0.9.1\n-------------", "(bugfix release, released on June 14th 2013)", "- Fixed an issue with integers no longer being accepted in certain\n parts of the routing system or URL quoting functions.\n- Fixed an issue with `url_quote` not producing the right escape\n codes for single digit codepoints.\n- Fixed an issue with :class:`~werkzeug.wsgi.SharedDataMiddleware` not\n reading the path correctly and breaking on etag generation in some\n cases.\n- Properly handle `Expect: 100-continue` in the development server\n to resolve issues with curl.\n- Automatically exhaust the input stream on request close. This should\n fix issues where not touching request files results in a timeout.\n- Fixed exhausting of streams not doing anything if a non-limited\n stream was passed into the multipart parser.\n- Raised the buffer sizes for the multipart parser.", "Version 0.9\n-----------", "Released on June 13nd 2013, codename Planierraupe.", "- Added support for :meth:`~werkzeug.wsgi.LimitedStream.tell`\n on the limited stream.\n- :class:`~werkzeug.datastructures.ETags` now is nonzero if it\n contains at least one etag of any kind, including weak ones.\n- Added a workaround for a bug in the stdlib for SSL servers.\n- Improved SSL interface of the devserver so that it can generate\n certificates easily and load them from files.\n- Refactored test client to invoke the open method on the class\n for redirects. This makes subclassing more powerful.\n- :func:`werkzeug.wsgi.make_chunk_iter` and\n :func:`werkzeug.wsgi.make_line_iter` now support processing of\n iterators and streams.\n- URL generation by the routing system now no longer quotes\n ``+``.\n- URL fixing now no longer quotes certain reserved characters.\n- The :func:`werkzeug.security.generate_password_hash` and\n check functions now support any of the hashlib algorithms.\n- `wsgi.get_current_url` is now ascii safe for browsers sending\n non-ascii data in query strings.\n- improved parsing behavior for :func:`werkzeug.http.parse_options_header`\n- added more operators to local proxies.\n- added a hook to override the default converter in the routing\n system.\n- The description field of HTTP exceptions is now always escaped.\n Use markup objects to disable that.\n- Added number of proxy argument to the proxy fix to make it more\n secure out of the box on common proxy setups. It will by default\n no longer trust the x-forwarded-for header as much as it did\n before.\n- Added support for fragment handling in URI/IRI functions.\n- Added custom class support for :func:`werkzeug.http.parse_dict_header`.\n- Renamed `LighttpdCGIRootFix` to `CGIRootFix`.\n- Always treat `+` as safe when fixing URLs as people love misusing them.\n- Added support to profiling into directories in the contrib profiler.\n- The escape function now by default escapes quotes.\n- Changed repr of exceptions to be less magical.\n- Simplified exception interface to no longer require environments\n to be passed to receive the response object.\n- Added sentinel argument to IterIO objects.\n- Added pbkdf2 support for the security module.\n- Added a plain request type that disables all form parsing to only\n leave the stream behind.\n- Removed support for deprecated `fix_headers`.\n- Removed support for deprecated `header_list`.\n- Removed support for deprecated parameter for `iter_encoded`.\n- Removed support for deprecated non-silent usage of the limited\n stream object.\n- Removed support for previous dummy `writable` parameter on\n the cached property.\n- Added support for explicitly closing request objects to close\n associated resources.\n- Conditional request handling or access to the data property on responses no\n longer ignores direct passthrough mode.\n- Removed werkzeug.templates and werkzeug.contrib.kickstart.\n- Changed host lookup logic for forwarded hosts to allow lists of\n hosts in which case only the first one is picked up.\n- Added `wsgi.get_query_string`, `wsgi.get_path_info` and\n `wsgi.get_script_name` and made the `wsgi.pop_path_info` and\n `wsgi.peek_path_info` functions perform unicode decoding. This\n was necessary to avoid having to expose the WSGI encoding dance\n on Python 3.\n- Added `content_encoding` and `content_md5` to the request object's\n common request descriptor mixin.\n- added `options` and `trace` to the test client.\n- Overhauled the utilization of the input stream to be easier to use\n and better to extend. The detection of content payload on the input\n side is now more compliant with HTTP by detecting off the content\n type header instead of the request method. This also now means that\n the stream property on the request class is always available instead\n of just when the parsing fails.\n- Added support for using :class:`werkzeug.wrappers.BaseResponse` in a with\n statement.\n- Changed `get_app_iter` to fetch the response early so that it does not\n fail when wrapping a response iterable. This makes filtering easier.\n- Introduced `get_data` and `set_data` methods for responses.\n- Introduced `get_data` for requests.\n- Soft deprecated the `data` descriptors for request and response objects.\n- Added `as_bytes` operations to some of the headers to simplify working\n with things like cookies.\n- Made the debugger paste tracebacks into github's gist service as\n private pastes.", "Version 0.8.4\n-------------", "(bugfix release, release date to be announced)", "- Added a favicon to the debugger which fixes problem with\n state changes being triggered through a request to\n /favicon.ico in Google Chrome. This should fix some\n problems with Flask and other frameworks that use\n context local objects on a stack with context preservation\n on errors.\n- Fixed an issue with scrolling up in the debugger.\n- Fixed an issue with debuggers running on a different URL\n than the URL root.\n- Fixed a problem with proxies not forwarding some rarely\n used special methods properly.\n- Added a workaround to prevent the XSS protection from Chrome\n breaking the debugger.\n- Skip redis tests if redis is not running.\n- Fixed a typo in the multipart parser that caused content-type\n to not be picked up properly.", "Version 0.8.3\n-------------", "(bugfix release, released on February 5th 2012)", "- Fixed another issue with :func:`werkzeug.wsgi.make_line_iter`\n where lines longer than the buffer size were not handled\n properly.\n- Restore stdout after debug console finished executing so\n that the debugger can be used on GAE better.\n- Fixed a bug with the redis cache for int subclasses\n (affects bool caching).\n- Fixed an XSS problem with redirect targets coming from\n untrusted sources.\n- Redis cache backend now supports password authentication.", "Version 0.8.2\n-------------", "(bugfix release, released on December 16th 2011)", "- Fixed a problem with request handling of the builtin server\n not responding to socket errors properly.\n- The routing request redirect exception's code attribute is now\n used properly.\n- Fixed a bug with shutdowns on Windows.\n- Fixed a few unicode issues with non-ascii characters being\n hardcoded in URL rules.\n- Fixed two property docstrings being assigned to fdel instead\n of ``__doc__``.\n- Fixed an issue where CRLF line endings could be split into two\n by the line iter function, causing problems with multipart file\n uploads.", "Version 0.8.1\n-------------", "(bugfix release, released on September 30th 2011)", "- Fixed an issue with the memcache not working properly.\n- Fixed an issue for Python 2.7.1 and higher that broke\n copying of multidicts with :func:`copy.copy`.\n- Changed hashing methodology of immutable ordered multi dicts\n for a potential problem with alternative Python implementations.", "Version 0.8\n-----------", "Released on September 29th 2011, codename Lötkolben", "- Removed data structure specific KeyErrors for a general\n purpose :exc:`~werkzeug.exceptions.BadRequestKeyError`.\n- Documented :meth:`werkzeug.wrappers.BaseRequest._load_form_data`.\n- The routing system now also accepts strings instead of\n dictionaries for the `query_args` parameter since we're only\n passing them through for redirects.\n- Werkzeug now automatically sets the content length immediately when\n the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute is set\n for efficiency and simplicity reasons.\n- The routing system will now normalize server names to lowercase.\n- The routing system will no longer raise ValueErrors in case the\n configuration for the server name was incorrect. This should make\n deployment much easier because you can ignore that factor now.\n- Fixed a bug with parsing HTTP digest headers. It rejected headers\n with missing nc and nonce params.\n- Proxy fix now also updates wsgi.url_scheme based on X-Forwarded-Proto.\n- Added support for key prefixes to the redis cache.\n- Added the ability to suppress some auto corrections in the wrappers\n that are now controlled via `autocorrect_location_header` and\n `automatically_set_content_length` on the response objects.\n- Werkzeug now uses a new method to check that the length of incoming\n data is complete and will raise IO errors by itself if the server\n fails to do so.\n- :func:`~werkzeug.wsgi.make_line_iter` now requires a limit that is\n not higher than the length the stream can provide.\n- Refactored form parsing into a form parser class that makes it possible\n to hook into individual parts of the parsing process for debugging and\n extending.\n- For conditional responses the content length is no longer set when it\n is already there and added if missing.\n- Immutable datastructures are hashable now.\n- Headers datastructure no longer allows newlines in values to avoid\n header injection attacks.\n- Made it possible through subclassing to select a different remote\n addr in the proxy fix.\n- Added stream based URL decoding. This reduces memory usage on large\n transmitted form data that is URL decoded since Werkzeug will no longer\n load all the unparsed data into memory.\n- Memcache client now no longer uses the buggy cmemcache module and\n supports pylibmc. GAE is not tried automatically and the dedicated\n class is no longer necessary.\n- Redis cache now properly serializes data.\n- Removed support for Python 2.4", "Version 0.7.2\n-------------", "(bugfix release, released on September 30th 2011)", "- Fixed a CSRF problem with the debugger.\n- The debugger is now generating private pastes on lodgeit.\n- If URL maps are now bound to environments the query arguments\n are properly decoded from it for redirects.", "Version 0.7.1\n-------------", "(bugfix release, released on July 26th 2011)", "- Fixed a problem with newer versions of IPython.\n- Disabled pyinotify based reloader which does not work reliably.", "Version 0.7\n-----------", "Released on July 24th 2011, codename Schraubschlüssel", "- Add support for python-libmemcached to the Werkzeug cache abstraction\n layer.\n- Improved :func:`url_decode` and :func:`url_encode` performance.\n- Fixed an issue where the SharedDataMiddleware could cause an\n internal server error on weird paths when loading via pkg_resources.\n- Fixed an URL generation bug that caused URLs to be invalid if a\n generated component contains a colon.\n- :func:`werkzeug.import_string` now works with partially set up\n packages properly.\n- Disabled automatic socket switching for IPv6 on the development\n server due to problems it caused.\n- Werkzeug no longer overrides the Date header when creating a\n conditional HTTP response.\n- The routing system provides a method to retrieve the matching\n methods for a given path.\n- The routing system now accepts a parameter to change the encoding\n error behaviour.\n- The local manager can now accept custom ident functions in the\n constructor that are forwarded to the wrapped local objects.\n- url_unquote_plus now accepts unicode strings again.\n- Fixed an issue with the filesystem session support's prune\n function and concurrent usage.\n- Fixed a problem with external URL generation discarding the port.\n- Added support for pylibmc to the Werkzeug cache abstraction layer.\n- Fixed an issue with the new multipart parser that happened when\n a linebreak happened to be on the chunk limit.\n- Cookies are now set properly if ports are in use. A runtime error\n is raised if one tries to set a cookie for a domain without a dot.\n- Fixed an issue with Template.from_file not working for file\n descriptors.\n- Reloader can now use inotify to track reloads. This requires the\n pyinotify library to be installed.\n- Werkzeug debugger can now submit to custom lodgeit installations.\n- redirect function's status code assertion now allows 201 to be used\n as redirection code. While it's not a real redirect, it shares\n enough with redirects for the function to still be useful.\n- Fixed securecookie for pypy.\n- Fixed `ValueErrors` being raised on calls to `best_match` on\n `MIMEAccept` objects when invalid user data was supplied.\n- Deprecated `werkzeug.contrib.kickstart` and `werkzeug.contrib.testtools`\n- URL routing now can be passed the URL arguments to keep them for\n redirects. In the future matching on URL arguments might also be\n possible.\n- Header encoding changed from utf-8 to latin1 to support a port to\n Python 3. Bytestrings passed to the object stay untouched which\n makes it possible to have utf-8 cookies. This is a part where\n the Python 3 version will later change in that it will always\n operate on latin1 values.\n- Fixed a bug in the form parser that caused the last character to\n be dropped off if certain values in multipart data are used.\n- Multipart parser now looks at the part-individual content type\n header to override the global charset.\n- Introduced mimetype and mimetype_params attribute for the file\n storage object.\n- Changed FileStorage filename fallback logic to skip special filenames\n that Python uses for marking special files like stdin.\n- Introduced more HTTP exception classes.\n- `call_on_close` now can be used as a decorator.\n- Support for redis as cache backend.\n- Added `BaseRequest.scheme`.\n- Support for the RFC 5789 PATCH method.\n- New custom routing parser and better ordering.\n- Removed support for `is_behind_proxy`. Use a WSGI middleware\n instead that rewrites the `REMOTE_ADDR` according to your setup.\n Also see the :class:`werkzeug.contrib.fixers.ProxyFix` for\n a drop-in replacement.\n- Added cookie forging support to the test client.\n- Added support for host based matching in the routing system.\n- Switched from the default 'ignore' to the better 'replace'\n unicode error handling mode.\n- The builtin server now adds a function named 'werkzeug.server.shutdown'\n into the WSGI env to initiate a shutdown. This currently only works\n in Python 2.6 and later.\n- Headers are now assumed to be latin1 for better compatibility with\n Python 3 once we have support.\n- Added :func:`werkzeug.security.safe_join`.\n- Added `accept_json` property analogous to `accept_html` on the\n :class:`werkzeug.datastructures.MIMEAccept`.\n- :func:`werkzeug.utils.import_string` now fails with much better\n error messages that pinpoint to the problem.\n- Added support for parsing of the `If-Range` header\n (:func:`werkzeug.http.parse_if_range_header` and\n :class:`werkzeug.datastructures.IfRange`).\n- Added support for parsing of the `Range` header\n (:func:`werkzeug.http.parse_range_header` and\n :class:`werkzeug.datastructures.Range`).\n- Added support for parsing of the `Content-Range` header of responses\n and provided an accessor object for it\n (:func:`werkzeug.http.parse_content_range_header` and\n :class:`werkzeug.datastructures.ContentRange`).", "Version 0.6.2\n-------------", "(bugfix release, released on April 23th 2010)", "- renamed the attribute `implicit_seqence_conversion` attribute of the\n request object to `implicit_sequence_conversion`.", "Version 0.6.1\n-------------", "(bugfix release, released on April 13th 2010)", "- heavily improved local objects. Should pick up standalone greenlet\n builds now and support proxies to free callables as well. There is\n also a stacked local now that makes it possible to invoke the same\n application from within itself by pushing current request/response\n on top of the stack.\n- routing build method will also build non-default method rules properly\n if no method is provided.\n- added proper IPv6 support for the builtin server.\n- windows specific filesystem session store fixes.\n (should now be more stable under high concurrency)\n- fixed a `NameError` in the session system.\n- fixed a bug with empty arguments in the werkzeug.script system.\n- fixed a bug where log lines will be duplicated if an application uses\n :meth:`logging.basicConfig` (#499)\n- added secure password hashing and checking functions.\n- `HEAD` is now implicitly added as method in the routing system if\n `GET` is present. Not doing that was considered a bug because often\n code assumed that this is the case and in web servers that do not\n normalize `HEAD` to `GET` this could break `HEAD` requests.\n- the script support can start SSL servers now.", "Version 0.6\n-----------", "Released on Feb 19th 2010, codename Hammer.", "- removed pending deprecations\n- sys.path is now printed from the testapp.\n- fixed an RFC 2068 incompatibility with cookie value quoting.\n- the :class:`FileStorage` now gives access to the multipart headers.\n- `cached_property.writeable` has been deprecated.\n- :meth:`MapAdapter.match` now accepts a `return_rule` keyword argument\n that returns the matched `Rule` instead of just the `endpoint`\n- :meth:`routing.Map.bind_to_environ` raises a more correct error message\n now if the map was bound to an invalid WSGI environment.\n- added support for SSL to the builtin development server.\n- Response objects are no longer modified in place when they are evaluated\n as WSGI applications. For backwards compatibility the `fix_headers`\n function is still called in case it was overridden.\n You should however change your application to use `get_wsgi_headers` if\n you need header modifications before responses are sent as the backwards\n compatibility support will go away in future versions.\n- :func:`append_slash_redirect` no longer requires the QUERY_STRING to be\n in the WSGI environment.\n- added :class:`~werkzeug.contrib.wrappers.DynamicCharsetResponseMixin`\n- added :class:`~werkzeug.contrib.wrappers.DynamicCharsetRequestMixin`\n- added :attr:`BaseRequest.url_charset`\n- request and response objects have a default `__repr__` now.\n- builtin data structures can be pickled now.\n- the form data parser will now look at the filename instead the\n content type to figure out if it should treat the upload as regular\n form data or file upload. This fixes a bug with Google Chrome.\n- improved performance of `make_line_iter` and the multipart parser\n for binary uploads.\n- fixed :attr:`~werkzeug.BaseResponse.is_streamed`\n- fixed a path quoting bug in `EnvironBuilder` that caused PATH_INFO and\n SCRIPT_NAME to end up in the environ unquoted.\n- :meth:`werkzeug.BaseResponse.freeze` now sets the content length.\n- for unknown HTTP methods the request stream is now always limited\n instead of being empty. This makes it easier to implement DAV\n and other protocols on top of Werkzeug.\n- added :meth:`werkzeug.MIMEAccept.best_match`\n- multi-value test-client posts from a standard dictionary are now\n supported. Previously you had to use a multi dict.\n- rule templates properly work with submounts, subdomains and\n other rule factories now.\n- deprecated non-silent usage of the :class:`werkzeug.LimitedStream`.\n- added support for IRI handling to many parts of Werkzeug.\n- development server properly logs to the werkzeug logger now.\n- added :func:`werkzeug.extract_path_info`\n- fixed a querystring quoting bug in :func:`url_fix`\n- added `fallback_mimetype` to :class:`werkzeug.SharedDataMiddleware`.\n- deprecated :meth:`BaseResponse.iter_encoded`'s charset parameter.\n- added :meth:`BaseResponse.make_sequence`,\n :attr:`BaseResponse.is_sequence` and\n :meth:`BaseResponse._ensure_sequence`.\n- added better __repr__ of :class:`werkzeug.Map`\n- `import_string` accepts unicode strings as well now.\n- development server doesn't break on double slashes after the host name.\n- better `__repr__` and `__str__` of\n :exc:`werkzeug.exceptions.HTTPException`\n- test client works correctly with multiple cookies now.\n- the :class:`werkzeug.routing.Map` now has a class attribute with\n the default converter mapping. This helps subclasses to override\n the converters without passing them to the constructor.\n- implemented :class:`OrderedMultiDict`\n- improved the session support for more efficient session storing\n on the filesystem. Also added support for listing of sessions\n currently stored in the filesystem session store.\n- werkzeug no longer utilizes the Python time module for parsing\n which means that dates in a broader range can be parsed.\n- the wrappers have no class attributes that make it possible to\n swap out the dict and list types it uses.\n- werkzeug debugger should work on the appengine dev server now.\n- the URL builder supports dropping of unexpected arguments now.\n Previously they were always appended to the URL as query string.\n- profiler now writes to the correct stream.", "Version 0.5.1\n-------------\n(bugfix release for 0.5, released on July 9th 2009)", "- fixed boolean check of :class:`FileStorage`\n- url routing system properly supports unicode URL rules now.\n- file upload streams no longer have to provide a truncate()\n method.\n- implemented :meth:`BaseRequest._form_parsing_failed`.\n- fixed #394\n- :meth:`ImmutableDict.copy`, :meth:`ImmutableMultiDict.copy` and\n :meth:`ImmutableTypeConversionDict.copy` return mutable shallow\n copies.\n- fixed a bug with the `make_runserver` script action.\n- :meth:`MultiDict.items` and :meth:`MutiDict.iteritems` now accept an\n argument to return a pair for each value of each key.\n- the multipart parser works better with hand-crafted multipart\n requests now that have extra newlines added. This fixes a bug\n with setuptools uploads not handled properly (#390)\n- fixed some minor bugs in the atom feed generator.\n- fixed a bug with client cookie header parsing being case sensitive.\n- fixed a not-working deprecation warning.\n- fixed package loading for :class:`SharedDataMiddleware`.\n- fixed a bug in the secure cookie that made server-side expiration\n on servers with a local time that was not set to UTC impossible.\n- fixed console of the interactive debugger.", "\nVersion 0.5\n-----------", "Released on April 24th, codename Schlagbohrer.", "- requires Python 2.4 now\n- fixed a bug in :class:`~contrib.IterIO`\n- added :class:`MIMEAccept` and :class:`CharsetAccept` that work like the\n regular :class:`Accept` but have extra special normalization for mimetypes\n and charsets and extra convenience methods.\n- switched the serving system from wsgiref to something homebrew.\n- the :class:`Client` now supports cookies.\n- added the :mod:`~werkzeug.contrib.fixers` module with various\n fixes for webserver bugs and hosting setup side-effects.\n- added :mod:`werkzeug.contrib.wrappers`\n- added :func:`is_hop_by_hop_header`\n- added :func:`is_entity_header`\n- added :func:`remove_hop_by_hop_headers`\n- added :func:`pop_path_info`\n- added :func:`peek_path_info`\n- added :func:`wrap_file` and :class:`FileWrapper`\n- moved `LimitedStream` from the contrib package into the regular\n werkzeug one and changed the default behavior to raise exceptions\n rather than stopping without warning. The old class will stick in\n the module until 0.6.\n- implemented experimental multipart parser that replaces the old CGI hack.\n- added :func:`dump_options_header` and :func:`parse_options_header`\n- added :func:`quote_header_value` and :func:`unquote_header_value`\n- :func:`url_encode` and :func:`url_decode` now accept a separator\n argument to switch between `&` and `;` as pair separator. The magic\n switch is no longer in place.\n- all form data parsing functions as well as the :class:`BaseRequest`\n object have parameters (or attributes) to limit the number of\n incoming bytes (either totally or per field).\n- added :class:`LanguageAccept`\n- request objects are now enforced to be read only for all collections.\n- added many new collection classes, refactored collections in general.\n- test support was refactored, semi-undocumented `werkzeug.test.File`\n was replaced by :class:`werkzeug.FileStorage`.\n- :class:`EnvironBuilder` was added and unifies the previous distinct\n :func:`create_environ`, :class:`Client` and\n :meth:`BaseRequest.from_values`. They all work the same now which\n is less confusing.\n- officially documented imports from the internal modules as undefined\n behavior. These modules were never exposed as public interfaces.\n- removed `FileStorage.__len__` which previously made the object\n falsy for browsers not sending the content length which all browsers\n do.\n- :class:`SharedDataMiddleware` uses `wrap_file` now and has a\n configurable cache timeout.\n- added :class:`CommonRequestDescriptorsMixin`\n- added :attr:`CommonResponseDescriptorsMixin.mimetype_params`\n- added :mod:`werkzeug.contrib.lint`\n- added `passthrough_errors` to `run_simple`.\n- added `secure_filename`\n- added :func:`make_line_iter`\n- :class:`MultiDict` copies now instead of revealing internal\n lists to the caller for `getlist` and iteration functions that\n return lists.\n- added :attr:`follow_redirect` to the :func:`open` of :class:`Client`.\n- added support for `extra_files` in\n :func:`~werkzeug.script.make_runserver`", "Version 0.4.1\n-------------", "(Bugfix release, released on January 11th 2009)", "- `werkzeug.contrib.cache.Memcached` accepts now objects that\n implement the memcache.Client interface as alternative to a list of\n strings with server addresses.\n There is also now a `GAEMemcachedCache` that connects to the Google\n appengine cache.\n- explicitly convert secret keys to bytestrings now because Python\n 2.6 no longer does that.\n- `url_encode` and all interfaces that call it, support ordering of\n options now which however is disabled by default.\n- the development server no longer resolves the addresses of clients.\n- Fixed a typo in `werkzeug.test` that broke `File`.\n- `Map.bind_to_environ` uses the `Host` header now if available.\n- Fixed `BaseCache.get_dict` (#345)\n- `werkzeug.test.Client` can now run the application buffered in which\n case the application is properly closed automatically.\n- Fixed `Headers.set` (#354). Caused header duplication before.\n- Fixed `Headers.pop` (#349). default parameter was not properly\n handled.\n- Fixed UnboundLocalError in `create_environ` (#351)\n- `Headers` is more compatible with wsgiref now.\n- `Template.render` accepts multidicts now.\n- dropped support for Python 2.3", "Version 0.4\n-----------", "Released on November 23rd 2008, codename Schraubenzieher.", "- `Client` supports an empty `data` argument now.\n- fixed a bug in `Response.application` that made it impossible to use it\n as method decorator.\n- the session system should work on appengine now\n- the secure cookie works properly in load balanced environments with\n different cpu architectures now.\n- `CacheControl.no_cache` and `CacheControl.private` behavior changed to\n reflect the possibilities of the HTTP RFC. Setting these attributes to\n `None` or `True` now sets the value to \"the empty value\".\n More details in the documentation.\n- fixed `werkzeug.contrib.atom.AtomFeed.__call__`. (#338)\n- `BaseResponse.make_conditional` now always returns `self`. Previously\n it didn't for post requests and such.\n- fixed a bug in boolean attribute handling of `html` and `xhtml`.\n- added graceful error handling to the debugger pastebin feature.\n- added a more list like interface to `Headers` (slicing and indexing\n works now)\n- fixed a bug with the `__setitem__` method of `Headers` that didn't\n properly remove all keys on replacing.\n- added `remove_entity_headers` which removes all entity headers from\n a list of headers (or a `Headers` object)\n- the responses now automatically call `remove_entity_headers` if the\n status code is 304.\n- fixed a bug with `Href` query parameter handling. Previously the last\n item of a call to `Href` was not handled properly if it was a dict.\n- headers now support a `pop` operation to better work with environ\n properties.", "\nVersion 0.3.1\n-------------", "(bugfix release, released on June 24th 2008)", "- fixed a security problem with `werkzeug.contrib.SecureCookie`.", "\nVersion 0.3\n-----------", "Released on June 14th 2008, codename EUR325CAT6.", "- added support for redirecting in url routing.\n- added `Authorization` and `AuthorizationMixin`\n- added `WWWAuthenticate` and `WWWAuthenticateMixin`\n- added `parse_list_header`\n- added `parse_dict_header`\n- added `parse_authorization_header`\n- added `parse_www_authenticate_header`\n- added `_get_current_object` method to `LocalProxy` objects\n- added `parse_form_data`\n- `MultiDict`, `CombinedMultiDict`, `Headers`, and `EnvironHeaders` raise\n special key errors now that are subclasses of `BadRequest` so if you\n don't catch them they give meaningful HTTP responses.\n- added support for alternative encoding error handling and the new\n `HTTPUnicodeError` which (if not caught) behaves like a `BadRequest`.\n- added `BadRequest.wrap`.\n- added ETag support to the SharedDataMiddleware and added an option\n to disable caching.\n- fixed `is_xhr` on the request objects.\n- fixed error handling of the url adapter's `dispatch` method. (#318)\n- fixed bug with `SharedDataMiddleware`.\n- fixed `Accept.values`.\n- `EnvironHeaders` contain content-type and content-length now\n- `url_encode` treats lists and tuples in dicts passed to it as multiple\n values for the same key so that one doesn't have to pass a `MultiDict`\n to the function.\n- added `validate_arguments`\n- added `BaseRequest.application`\n- improved Python 2.3 support\n- `run_simple` accepts `use_debugger` and `use_evalex` parameters now,\n like the `make_runserver` factory function from the script module.\n- the `environ_property` is now read-only by default\n- it's now possible to initialize requests as \"shallow\" requests which\n causes runtime errors if the request object tries to consume the\n input stream.", "\nVersion 0.2\n-----------", "Released Feb 14th 2008, codename Faustkeil.", "- Added `AnyConverter` to the routing system.\n- Added `werkzeug.contrib.securecookie`\n- Exceptions have a ``get_response()`` method that return a response object\n- fixed the path ordering bug (#293), thanks Thomas Johansson\n- `BaseReporterStream` is now part of the werkzeug contrib module. From\n Werkzeug 0.3 onwards you will have to import it from there.\n- added `DispatcherMiddleware`.\n- `RequestRedirect` is now a subclass of `HTTPException` and uses a\n 301 status code instead of 302.\n- `url_encode` and `url_decode` can optionally treat keys as unicode strings\n now, too.\n- `werkzeug.script` has a different caller format for boolean arguments now.\n- renamed `lazy_property` to `cached_property`.\n- added `import_string`.\n- added is_* properties to request objects.\n- added `empty()` method to routing rules.\n- added `werkzeug.contrib.profiler`.\n- added `extends` to `Headers`.\n- added `dump_cookie` and `parse_cookie`.\n- added `as_tuple` to the `Client`.\n- added `werkzeug.contrib.testtools`.\n- added `werkzeug.unescape`\n- added `BaseResponse.freeze`\n- added `werkzeug.contrib.atom`\n- the HTTPExceptions accept an argument `description` now which overrides the\n default description.\n- the `MapAdapter` has a default for path info now. If you use\n `bind_to_environ` you don't have to pass the path later.\n- the wsgiref subclass werkzeug uses for the dev server does not use direct\n sys.stderr logging any more but a logger called \"werkzeug\".\n- implemented `Href`.\n- implemented `find_modules`\n- refactored request and response objects into base objects, mixins and\n full featured subclasses that implement all mixins.\n- added simple user agent parser\n- werkzeug's routing raises `MethodNotAllowed` now if it matches a\n rule but for a different method.\n- many fixes and small improvements", "\nVersion 0.1\n-----------", "Released on Dec 9th 2007, codename Wictorinoxger.", "- Initial release" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 69], "buggy_code_start_loc": [22, 69], "filenames": ["CHANGES.rst", "src/werkzeug/debug/__init__.py"], "fixing_code_end_loc": [25, 83], "fixing_code_start_loc": [23, 70], "message": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:palletsprojects:werkzeug:*:*:*:*:*:*:*:*", "matchCriteriaId": "2BEABB52-D59B-4CBF-AD1B-47B7F8909E70", "versionEndExcluding": "0.15.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id."}, {"lang": "es", "value": "Pallets Werkzeug en versiones anteriores a 0.15.3, cuando es usado con Docker, presenta una aleatoriedad insuficiente del PIN del depurador porque los contenedores Docker comparten la mismo id de m\u00e1quina."}], "evaluatorComment": null, "id": "CVE-2019-14806", "lastModified": "2023-03-03T19:34:49.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-08-09T15:15:12.917", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00047.html"}, {"source": "cve@mitre.org", "tags": ["Product"], "url": "https://github.com/pallets/werkzeug/blob/7fef41b120327d3912fbe12fb64f1951496fcf3e/src/werkzeug/debug/__init__.py#L168"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://palletsprojects.com/blog/werkzeug-0-15-3-released/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-331"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, "type": "CWE-331"}
108
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n\"\"\"\n werkzeug.debug\n ~~~~~~~~~~~~~~", " WSGI application traceback debugger.", " :copyright: 2007 Pallets\n :license: BSD-3-Clause\n\"\"\"\nimport getpass\nimport hashlib\nimport json\nimport mimetypes\nimport os\nimport pkgutil\nimport re\nimport sys\nimport time\nimport uuid\nfrom itertools import chain\nfrom os.path import basename\nfrom os.path import join", "from .._compat import text_type\nfrom .._internal import _log\nfrom ..http import parse_cookie\nfrom ..security import gen_salt\nfrom ..wrappers import BaseRequest as Request\nfrom ..wrappers import BaseResponse as Response\nfrom .console import Console\nfrom .repr import debug_repr as _debug_repr\nfrom .tbtools import get_current_traceback\nfrom .tbtools import render_console_html", "\ndef debug_repr(*args, **kwargs):\n import warnings", " warnings.warn(\n \"'debug_repr' has moved to 'werkzeug.debug.repr.debug_repr'\"\n \" as of version 0.7. This old import will be removed in version\"\n \" 1.0.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return _debug_repr(*args, **kwargs)", "\n# A week\nPIN_TIME = 60 * 60 * 24 * 7", "\ndef hash_pin(pin):\n if isinstance(pin, text_type):\n pin = pin.encode(\"utf-8\", \"replace\")\n return hashlib.md5(pin + b\"shittysalt\").hexdigest()[:12]", "\n_machine_id = None", "\ndef get_machine_id():\n global _machine_id\n rv = _machine_id\n if rv is not None:\n return rv", " def _generate():", "", " # Potential sources of secret information on linux. The machine-id\n # is stable across boots, the boot id is not\n for filename in \"/etc/machine-id\", \"/proc/sys/kernel/random/boot_id\":\n try:\n with open(filename, \"rb\") as f:\n return f.readline().strip()\n except IOError:\n continue", " # On OS X we can use the computer's serial number assuming that\n # ioreg exists and can spit out that information.\n try:\n # Also catch import errors: subprocess may not be available, e.g.\n # Google App Engine\n # See https://github.com/pallets/werkzeug/issues/925\n from subprocess import Popen, PIPE", " dump = Popen(\n [\"ioreg\", \"-c\", \"IOPlatformExpertDevice\", \"-d\", \"2\"], stdout=PIPE\n ).communicate()[0]\n match = re.search(b'\"serial-number\" = <([^>]+)', dump)\n if match is not None:\n return match.group(1)\n except (OSError, ImportError):\n pass", " # On Windows we can use winreg to get the machine guid\n wr = None\n try:\n import winreg as wr\n except ImportError:\n try:\n import _winreg as wr\n except ImportError:\n pass\n if wr is not None:\n try:\n with wr.OpenKey(\n wr.HKEY_LOCAL_MACHINE,\n \"SOFTWARE\\\\Microsoft\\\\Cryptography\",\n 0,\n wr.KEY_READ | wr.KEY_WOW64_64KEY,\n ) as rk:\n machineGuid, wrType = wr.QueryValueEx(rk, \"MachineGuid\")\n if wrType == wr.REG_SZ:\n return machineGuid.encode(\"utf-8\")\n else:\n return machineGuid\n except WindowsError:\n pass", " _machine_id = rv = _generate()\n return rv", "\nclass _ConsoleFrame(object):\n \"\"\"Helper class so that we can reuse the frame console code for the\n standalone console.\n \"\"\"", " def __init__(self, namespace):\n self.console = Console(namespace)\n self.id = 0", "\ndef get_pin_and_cookie_name(app):\n \"\"\"Given an application object this returns a semi-stable 9 digit pin\n code and a random key. The hope is that this is stable between\n restarts to not make debugging particularly frustrating. If the pin\n was forcefully disabled this returns `None`.", " Second item in the resulting tuple is the cookie name for remembering.\n \"\"\"\n pin = os.environ.get(\"WERKZEUG_DEBUG_PIN\")\n rv = None\n num = None", " # Pin was explicitly disabled\n if pin == \"off\":\n return None, None", " # Pin was provided explicitly\n if pin is not None and pin.replace(\"-\", \"\").isdigit():\n # If there are separators in the pin, return it directly\n if \"-\" in pin:\n rv = pin\n else:\n num = pin", " modname = getattr(app, \"__module__\", app.__class__.__module__)", " try:\n # getuser imports the pwd module, which does not exist in Google\n # App Engine. It may also raise a KeyError if the UID does not\n # have a username, such as in Docker.\n username = getpass.getuser()\n except (ImportError, KeyError):\n username = None", " mod = sys.modules.get(modname)", " # This information only exists to make the cookie unique on the\n # computer, not as a security feature.\n probably_public_bits = [\n username,\n modname,\n getattr(app, \"__name__\", app.__class__.__name__),\n getattr(mod, \"__file__\", None),\n ]", " # This information is here to make it harder for an attacker to\n # guess the cookie name. They are unlikely to be contained anywhere\n # within the unauthenticated debug page.\n private_bits = [str(uuid.getnode()), get_machine_id()]", " h = hashlib.md5()\n for bit in chain(probably_public_bits, private_bits):\n if not bit:\n continue\n if isinstance(bit, text_type):\n bit = bit.encode(\"utf-8\")\n h.update(bit)\n h.update(b\"cookiesalt\")", " cookie_name = \"__wzd\" + h.hexdigest()[:20]", " # If we need to generate a pin we salt it a bit more so that we don't\n # end up with the same value and generate out 9 digits\n if num is None:\n h.update(b\"pinsalt\")\n num = (\"%09d\" % int(h.hexdigest(), 16))[:9]", " # Format the pincode in groups of digits for easier remembering if\n # we don't have a result yet.\n if rv is None:\n for group_size in 5, 4, 3:\n if len(num) % group_size == 0:\n rv = \"-\".join(\n num[x : x + group_size].rjust(group_size, \"0\")\n for x in range(0, len(num), group_size)\n )\n break\n else:\n rv = num", " return rv, cookie_name", "\nclass DebuggedApplication(object):\n \"\"\"Enables debugging support for a given application::", " from werkzeug.debug import DebuggedApplication\n from myapp import app\n app = DebuggedApplication(app, evalex=True)", " The `evalex` keyword argument allows evaluating expressions in a\n traceback's frame context.", " .. versionadded:: 0.9\n The `lodgeit_url` parameter was deprecated.", " :param app: the WSGI application to run debugged.\n :param evalex: enable exception evaluation feature (interactive\n debugging). This requires a non-forking server.\n :param request_key: The key that points to the request object in ths\n environment. This parameter is ignored in current\n versions.\n :param console_path: the URL for a general purpose console.\n :param console_init_func: the function that is executed before starting\n the general purpose console. The return value\n is used as initial namespace.\n :param show_hidden_frames: by default hidden traceback frames are skipped.\n You can show them by setting this parameter\n to `True`.\n :param pin_security: can be used to disable the pin based security system.\n :param pin_logging: enables the logging of the pin system.\n \"\"\"", " def __init__(\n self,\n app,\n evalex=False,\n request_key=\"werkzeug.request\",\n console_path=\"/console\",\n console_init_func=None,\n show_hidden_frames=False,\n lodgeit_url=None,\n pin_security=True,\n pin_logging=True,\n ):\n if lodgeit_url is not None:\n from warnings import warn", " warn(\n \"'lodgeit_url' is no longer used as of version 0.9 and\"\n \" will be removed in version 1.0. Werkzeug uses\"\n \" https://gist.github.com/ instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n if not console_init_func:\n console_init_func = None\n self.app = app\n self.evalex = evalex\n self.frames = {}\n self.tracebacks = {}\n self.request_key = request_key\n self.console_path = console_path\n self.console_init_func = console_init_func\n self.show_hidden_frames = show_hidden_frames\n self.secret = gen_salt(20)\n self._failed_pin_auth = 0", " self.pin_logging = pin_logging\n if pin_security:\n # Print out the pin for the debugger on standard out.\n if os.environ.get(\"WERKZEUG_RUN_MAIN\") == \"true\" and pin_logging:\n _log(\"warning\", \" * Debugger is active!\")\n if self.pin is None:\n _log(\"warning\", \" * Debugger PIN disabled. DEBUGGER UNSECURED!\")\n else:\n _log(\"info\", \" * Debugger PIN: %s\" % self.pin)\n else:\n self.pin = None", " def _get_pin(self):\n if not hasattr(self, \"_pin\"):\n self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)\n return self._pin", " def _set_pin(self, value):\n self._pin = value", " pin = property(_get_pin, _set_pin)\n del _get_pin, _set_pin", " @property\n def pin_cookie_name(self):\n \"\"\"The name of the pin cookie.\"\"\"\n if not hasattr(self, \"_pin_cookie\"):\n self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)\n return self._pin_cookie", " def debug_application(self, environ, start_response):\n \"\"\"Run the application and conserve the traceback frames.\"\"\"\n app_iter = None\n try:\n app_iter = self.app(environ, start_response)\n for item in app_iter:\n yield item\n if hasattr(app_iter, \"close\"):\n app_iter.close()\n except Exception:\n if hasattr(app_iter, \"close\"):\n app_iter.close()\n traceback = get_current_traceback(\n skip=1,\n show_hidden_frames=self.show_hidden_frames,\n ignore_system_exceptions=True,\n )\n for frame in traceback.frames:\n self.frames[frame.id] = frame\n self.tracebacks[traceback.id] = traceback", " try:\n start_response(\n \"500 INTERNAL SERVER ERROR\",\n [\n (\"Content-Type\", \"text/html; charset=utf-8\"),\n # Disable Chrome's XSS protection, the debug\n # output can cause false-positives.\n (\"X-XSS-Protection\", \"0\"),\n ],\n )\n except Exception:\n # if we end up here there has been output but an error\n # occurred. in that situation we can do nothing fancy any\n # more, better log something into the error log and fall\n # back gracefully.\n environ[\"wsgi.errors\"].write(\n \"Debugging middleware caught exception in streamed \"\n \"response at a point where response headers were already \"\n \"sent.\\n\"\n )\n else:\n is_trusted = bool(self.check_pin_trust(environ))\n yield traceback.render_full(\n evalex=self.evalex, evalex_trusted=is_trusted, secret=self.secret\n ).encode(\"utf-8\", \"replace\")", " traceback.log(environ[\"wsgi.errors\"])", " def execute_command(self, request, command, frame):\n \"\"\"Execute a command in a console.\"\"\"\n return Response(frame.console.eval(command), mimetype=\"text/html\")", " def display_console(self, request):\n \"\"\"Display a standalone shell.\"\"\"\n if 0 not in self.frames:\n if self.console_init_func is None:\n ns = {}\n else:\n ns = dict(self.console_init_func())\n ns.setdefault(\"app\", self.app)\n self.frames[0] = _ConsoleFrame(ns)\n is_trusted = bool(self.check_pin_trust(request.environ))\n return Response(\n render_console_html(secret=self.secret, evalex_trusted=is_trusted),\n mimetype=\"text/html\",\n )", " def paste_traceback(self, request, traceback):\n \"\"\"Paste the traceback and return a JSON response.\"\"\"\n rv = traceback.paste()\n return Response(json.dumps(rv), mimetype=\"application/json\")", " def get_resource(self, request, filename):\n \"\"\"Return a static resource from the shared folder.\"\"\"\n filename = join(\"shared\", basename(filename))\n try:\n data = pkgutil.get_data(__package__, filename)\n except OSError:\n data = None\n if data is not None:\n mimetype = mimetypes.guess_type(filename)[0] or \"application/octet-stream\"\n return Response(data, mimetype=mimetype)\n return Response(\"Not Found\", status=404)", " def check_pin_trust(self, environ):\n \"\"\"Checks if the request passed the pin test. This returns `True` if the\n request is trusted on a pin/cookie basis and returns `False` if not.\n Additionally if the cookie's stored pin hash is wrong it will return\n `None` so that appropriate action can be taken.\n \"\"\"\n if self.pin is None:\n return True\n val = parse_cookie(environ).get(self.pin_cookie_name)\n if not val or \"|\" not in val:\n return False\n ts, pin_hash = val.split(\"|\", 1)\n if not ts.isdigit():\n return False\n if pin_hash != hash_pin(self.pin):\n return None\n return (time.time() - PIN_TIME) < int(ts)", " def _fail_pin_auth(self):\n time.sleep(5.0 if self._failed_pin_auth > 5 else 0.5)\n self._failed_pin_auth += 1", " def pin_auth(self, request):\n \"\"\"Authenticates with the pin.\"\"\"\n exhausted = False\n auth = False\n trust = self.check_pin_trust(request.environ)", " # If the trust return value is `None` it means that the cookie is\n # set but the stored pin hash value is bad. This means that the\n # pin was changed. In this case we count a bad auth and unset the\n # cookie. This way it becomes harder to guess the cookie name\n # instead of the pin as we still count up failures.\n bad_cookie = False\n if trust is None:\n self._fail_pin_auth()\n bad_cookie = True", " # If we're trusted, we're authenticated.\n elif trust:\n auth = True", " # If we failed too many times, then we're locked out.\n elif self._failed_pin_auth > 10:\n exhausted = True", " # Otherwise go through pin based authentication\n else:\n entered_pin = request.args.get(\"pin\")\n if entered_pin.strip().replace(\"-\", \"\") == self.pin.replace(\"-\", \"\"):\n self._failed_pin_auth = 0\n auth = True\n else:\n self._fail_pin_auth()", " rv = Response(\n json.dumps({\"auth\": auth, \"exhausted\": exhausted}),\n mimetype=\"application/json\",\n )\n if auth:\n rv.set_cookie(\n self.pin_cookie_name,\n \"%s|%s\" % (int(time.time()), hash_pin(self.pin)),\n httponly=True,\n )\n elif bad_cookie:\n rv.delete_cookie(self.pin_cookie_name)\n return rv", " def log_pin_request(self):\n \"\"\"Log the pin if needed.\"\"\"\n if self.pin_logging and self.pin is not None:\n _log(\n \"info\", \" * To enable the debugger you need to enter the security pin:\"\n )\n _log(\"info\", \" * Debugger pin code: %s\" % self.pin)\n return Response(\"\")", " def __call__(self, environ, start_response):\n \"\"\"Dispatch the requests.\"\"\"\n # important: don't ever access a function here that reads the incoming\n # form data! Otherwise the application won't have access to that data\n # any more!\n request = Request(environ)\n response = self.debug_application\n if request.args.get(\"__debugger__\") == \"yes\":\n cmd = request.args.get(\"cmd\")\n arg = request.args.get(\"f\")\n secret = request.args.get(\"s\")\n traceback = self.tracebacks.get(request.args.get(\"tb\", type=int))\n frame = self.frames.get(request.args.get(\"frm\", type=int))\n if cmd == \"resource\" and arg:\n response = self.get_resource(request, arg)\n elif cmd == \"paste\" and traceback is not None and secret == self.secret:\n response = self.paste_traceback(request, traceback)\n elif cmd == \"pinauth\" and secret == self.secret:\n response = self.pin_auth(request)\n elif cmd == \"printpin\" and secret == self.secret:\n response = self.log_pin_request()\n elif (\n self.evalex\n and cmd is not None\n and frame is not None\n and self.secret == secret\n and self.check_pin_trust(environ)\n ):\n response = self.execute_command(request, cmd, frame)\n elif (\n self.evalex\n and self.console_path is not None\n and request.path == self.console_path\n ):\n response = self.display_console(request)\n return response(environ, start_response)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 69], "buggy_code_start_loc": [22, 69], "filenames": ["CHANGES.rst", "src/werkzeug/debug/__init__.py"], "fixing_code_end_loc": [25, 83], "fixing_code_start_loc": [23, 70], "message": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:palletsprojects:werkzeug:*:*:*:*:*:*:*:*", "matchCriteriaId": "2BEABB52-D59B-4CBF-AD1B-47B7F8909E70", "versionEndExcluding": "0.15.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id."}, {"lang": "es", "value": "Pallets Werkzeug en versiones anteriores a 0.15.3, cuando es usado con Docker, presenta una aleatoriedad insuficiente del PIN del depurador porque los contenedores Docker comparten la mismo id de m\u00e1quina."}], "evaluatorComment": null, "id": "CVE-2019-14806", "lastModified": "2023-03-03T19:34:49.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-08-09T15:15:12.917", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00047.html"}, {"source": "cve@mitre.org", "tags": ["Product"], "url": "https://github.com/pallets/werkzeug/blob/7fef41b120327d3912fbe12fb64f1951496fcf3e/src/werkzeug/debug/__init__.py#L168"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://palletsprojects.com/blog/werkzeug-0-15-3-released/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-331"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, "type": "CWE-331"}
108
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n\"\"\"\n werkzeug.debug\n ~~~~~~~~~~~~~~", " WSGI application traceback debugger.", " :copyright: 2007 Pallets\n :license: BSD-3-Clause\n\"\"\"\nimport getpass\nimport hashlib\nimport json\nimport mimetypes\nimport os\nimport pkgutil\nimport re\nimport sys\nimport time\nimport uuid\nfrom itertools import chain\nfrom os.path import basename\nfrom os.path import join", "from .._compat import text_type\nfrom .._internal import _log\nfrom ..http import parse_cookie\nfrom ..security import gen_salt\nfrom ..wrappers import BaseRequest as Request\nfrom ..wrappers import BaseResponse as Response\nfrom .console import Console\nfrom .repr import debug_repr as _debug_repr\nfrom .tbtools import get_current_traceback\nfrom .tbtools import render_console_html", "\ndef debug_repr(*args, **kwargs):\n import warnings", " warnings.warn(\n \"'debug_repr' has moved to 'werkzeug.debug.repr.debug_repr'\"\n \" as of version 0.7. This old import will be removed in version\"\n \" 1.0.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return _debug_repr(*args, **kwargs)", "\n# A week\nPIN_TIME = 60 * 60 * 24 * 7", "\ndef hash_pin(pin):\n if isinstance(pin, text_type):\n pin = pin.encode(\"utf-8\", \"replace\")\n return hashlib.md5(pin + b\"shittysalt\").hexdigest()[:12]", "\n_machine_id = None", "\ndef get_machine_id():\n global _machine_id\n rv = _machine_id\n if rv is not None:\n return rv", " def _generate():", " # docker containers share the same machine id, get the\n # container id instead\n try:\n with open(\"/proc/self/cgroup\") as f:\n value = f.readline()\n except IOError:\n pass\n else:\n value = value.strip().partition(\"/docker/\")[2]", " if value:\n return value\n", " # Potential sources of secret information on linux. The machine-id\n # is stable across boots, the boot id is not\n for filename in \"/etc/machine-id\", \"/proc/sys/kernel/random/boot_id\":\n try:\n with open(filename, \"rb\") as f:\n return f.readline().strip()\n except IOError:\n continue", " # On OS X we can use the computer's serial number assuming that\n # ioreg exists and can spit out that information.\n try:\n # Also catch import errors: subprocess may not be available, e.g.\n # Google App Engine\n # See https://github.com/pallets/werkzeug/issues/925\n from subprocess import Popen, PIPE", " dump = Popen(\n [\"ioreg\", \"-c\", \"IOPlatformExpertDevice\", \"-d\", \"2\"], stdout=PIPE\n ).communicate()[0]\n match = re.search(b'\"serial-number\" = <([^>]+)', dump)\n if match is not None:\n return match.group(1)\n except (OSError, ImportError):\n pass", " # On Windows we can use winreg to get the machine guid\n wr = None\n try:\n import winreg as wr\n except ImportError:\n try:\n import _winreg as wr\n except ImportError:\n pass\n if wr is not None:\n try:\n with wr.OpenKey(\n wr.HKEY_LOCAL_MACHINE,\n \"SOFTWARE\\\\Microsoft\\\\Cryptography\",\n 0,\n wr.KEY_READ | wr.KEY_WOW64_64KEY,\n ) as rk:\n machineGuid, wrType = wr.QueryValueEx(rk, \"MachineGuid\")\n if wrType == wr.REG_SZ:\n return machineGuid.encode(\"utf-8\")\n else:\n return machineGuid\n except WindowsError:\n pass", " _machine_id = rv = _generate()\n return rv", "\nclass _ConsoleFrame(object):\n \"\"\"Helper class so that we can reuse the frame console code for the\n standalone console.\n \"\"\"", " def __init__(self, namespace):\n self.console = Console(namespace)\n self.id = 0", "\ndef get_pin_and_cookie_name(app):\n \"\"\"Given an application object this returns a semi-stable 9 digit pin\n code and a random key. The hope is that this is stable between\n restarts to not make debugging particularly frustrating. If the pin\n was forcefully disabled this returns `None`.", " Second item in the resulting tuple is the cookie name for remembering.\n \"\"\"\n pin = os.environ.get(\"WERKZEUG_DEBUG_PIN\")\n rv = None\n num = None", " # Pin was explicitly disabled\n if pin == \"off\":\n return None, None", " # Pin was provided explicitly\n if pin is not None and pin.replace(\"-\", \"\").isdigit():\n # If there are separators in the pin, return it directly\n if \"-\" in pin:\n rv = pin\n else:\n num = pin", " modname = getattr(app, \"__module__\", app.__class__.__module__)", " try:\n # getuser imports the pwd module, which does not exist in Google\n # App Engine. It may also raise a KeyError if the UID does not\n # have a username, such as in Docker.\n username = getpass.getuser()\n except (ImportError, KeyError):\n username = None", " mod = sys.modules.get(modname)", " # This information only exists to make the cookie unique on the\n # computer, not as a security feature.\n probably_public_bits = [\n username,\n modname,\n getattr(app, \"__name__\", app.__class__.__name__),\n getattr(mod, \"__file__\", None),\n ]", " # This information is here to make it harder for an attacker to\n # guess the cookie name. They are unlikely to be contained anywhere\n # within the unauthenticated debug page.\n private_bits = [str(uuid.getnode()), get_machine_id()]", " h = hashlib.md5()\n for bit in chain(probably_public_bits, private_bits):\n if not bit:\n continue\n if isinstance(bit, text_type):\n bit = bit.encode(\"utf-8\")\n h.update(bit)\n h.update(b\"cookiesalt\")", " cookie_name = \"__wzd\" + h.hexdigest()[:20]", " # If we need to generate a pin we salt it a bit more so that we don't\n # end up with the same value and generate out 9 digits\n if num is None:\n h.update(b\"pinsalt\")\n num = (\"%09d\" % int(h.hexdigest(), 16))[:9]", " # Format the pincode in groups of digits for easier remembering if\n # we don't have a result yet.\n if rv is None:\n for group_size in 5, 4, 3:\n if len(num) % group_size == 0:\n rv = \"-\".join(\n num[x : x + group_size].rjust(group_size, \"0\")\n for x in range(0, len(num), group_size)\n )\n break\n else:\n rv = num", " return rv, cookie_name", "\nclass DebuggedApplication(object):\n \"\"\"Enables debugging support for a given application::", " from werkzeug.debug import DebuggedApplication\n from myapp import app\n app = DebuggedApplication(app, evalex=True)", " The `evalex` keyword argument allows evaluating expressions in a\n traceback's frame context.", " .. versionadded:: 0.9\n The `lodgeit_url` parameter was deprecated.", " :param app: the WSGI application to run debugged.\n :param evalex: enable exception evaluation feature (interactive\n debugging). This requires a non-forking server.\n :param request_key: The key that points to the request object in ths\n environment. This parameter is ignored in current\n versions.\n :param console_path: the URL for a general purpose console.\n :param console_init_func: the function that is executed before starting\n the general purpose console. The return value\n is used as initial namespace.\n :param show_hidden_frames: by default hidden traceback frames are skipped.\n You can show them by setting this parameter\n to `True`.\n :param pin_security: can be used to disable the pin based security system.\n :param pin_logging: enables the logging of the pin system.\n \"\"\"", " def __init__(\n self,\n app,\n evalex=False,\n request_key=\"werkzeug.request\",\n console_path=\"/console\",\n console_init_func=None,\n show_hidden_frames=False,\n lodgeit_url=None,\n pin_security=True,\n pin_logging=True,\n ):\n if lodgeit_url is not None:\n from warnings import warn", " warn(\n \"'lodgeit_url' is no longer used as of version 0.9 and\"\n \" will be removed in version 1.0. Werkzeug uses\"\n \" https://gist.github.com/ instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n if not console_init_func:\n console_init_func = None\n self.app = app\n self.evalex = evalex\n self.frames = {}\n self.tracebacks = {}\n self.request_key = request_key\n self.console_path = console_path\n self.console_init_func = console_init_func\n self.show_hidden_frames = show_hidden_frames\n self.secret = gen_salt(20)\n self._failed_pin_auth = 0", " self.pin_logging = pin_logging\n if pin_security:\n # Print out the pin for the debugger on standard out.\n if os.environ.get(\"WERKZEUG_RUN_MAIN\") == \"true\" and pin_logging:\n _log(\"warning\", \" * Debugger is active!\")\n if self.pin is None:\n _log(\"warning\", \" * Debugger PIN disabled. DEBUGGER UNSECURED!\")\n else:\n _log(\"info\", \" * Debugger PIN: %s\" % self.pin)\n else:\n self.pin = None", " def _get_pin(self):\n if not hasattr(self, \"_pin\"):\n self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)\n return self._pin", " def _set_pin(self, value):\n self._pin = value", " pin = property(_get_pin, _set_pin)\n del _get_pin, _set_pin", " @property\n def pin_cookie_name(self):\n \"\"\"The name of the pin cookie.\"\"\"\n if not hasattr(self, \"_pin_cookie\"):\n self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)\n return self._pin_cookie", " def debug_application(self, environ, start_response):\n \"\"\"Run the application and conserve the traceback frames.\"\"\"\n app_iter = None\n try:\n app_iter = self.app(environ, start_response)\n for item in app_iter:\n yield item\n if hasattr(app_iter, \"close\"):\n app_iter.close()\n except Exception:\n if hasattr(app_iter, \"close\"):\n app_iter.close()\n traceback = get_current_traceback(\n skip=1,\n show_hidden_frames=self.show_hidden_frames,\n ignore_system_exceptions=True,\n )\n for frame in traceback.frames:\n self.frames[frame.id] = frame\n self.tracebacks[traceback.id] = traceback", " try:\n start_response(\n \"500 INTERNAL SERVER ERROR\",\n [\n (\"Content-Type\", \"text/html; charset=utf-8\"),\n # Disable Chrome's XSS protection, the debug\n # output can cause false-positives.\n (\"X-XSS-Protection\", \"0\"),\n ],\n )\n except Exception:\n # if we end up here there has been output but an error\n # occurred. in that situation we can do nothing fancy any\n # more, better log something into the error log and fall\n # back gracefully.\n environ[\"wsgi.errors\"].write(\n \"Debugging middleware caught exception in streamed \"\n \"response at a point where response headers were already \"\n \"sent.\\n\"\n )\n else:\n is_trusted = bool(self.check_pin_trust(environ))\n yield traceback.render_full(\n evalex=self.evalex, evalex_trusted=is_trusted, secret=self.secret\n ).encode(\"utf-8\", \"replace\")", " traceback.log(environ[\"wsgi.errors\"])", " def execute_command(self, request, command, frame):\n \"\"\"Execute a command in a console.\"\"\"\n return Response(frame.console.eval(command), mimetype=\"text/html\")", " def display_console(self, request):\n \"\"\"Display a standalone shell.\"\"\"\n if 0 not in self.frames:\n if self.console_init_func is None:\n ns = {}\n else:\n ns = dict(self.console_init_func())\n ns.setdefault(\"app\", self.app)\n self.frames[0] = _ConsoleFrame(ns)\n is_trusted = bool(self.check_pin_trust(request.environ))\n return Response(\n render_console_html(secret=self.secret, evalex_trusted=is_trusted),\n mimetype=\"text/html\",\n )", " def paste_traceback(self, request, traceback):\n \"\"\"Paste the traceback and return a JSON response.\"\"\"\n rv = traceback.paste()\n return Response(json.dumps(rv), mimetype=\"application/json\")", " def get_resource(self, request, filename):\n \"\"\"Return a static resource from the shared folder.\"\"\"\n filename = join(\"shared\", basename(filename))\n try:\n data = pkgutil.get_data(__package__, filename)\n except OSError:\n data = None\n if data is not None:\n mimetype = mimetypes.guess_type(filename)[0] or \"application/octet-stream\"\n return Response(data, mimetype=mimetype)\n return Response(\"Not Found\", status=404)", " def check_pin_trust(self, environ):\n \"\"\"Checks if the request passed the pin test. This returns `True` if the\n request is trusted on a pin/cookie basis and returns `False` if not.\n Additionally if the cookie's stored pin hash is wrong it will return\n `None` so that appropriate action can be taken.\n \"\"\"\n if self.pin is None:\n return True\n val = parse_cookie(environ).get(self.pin_cookie_name)\n if not val or \"|\" not in val:\n return False\n ts, pin_hash = val.split(\"|\", 1)\n if not ts.isdigit():\n return False\n if pin_hash != hash_pin(self.pin):\n return None\n return (time.time() - PIN_TIME) < int(ts)", " def _fail_pin_auth(self):\n time.sleep(5.0 if self._failed_pin_auth > 5 else 0.5)\n self._failed_pin_auth += 1", " def pin_auth(self, request):\n \"\"\"Authenticates with the pin.\"\"\"\n exhausted = False\n auth = False\n trust = self.check_pin_trust(request.environ)", " # If the trust return value is `None` it means that the cookie is\n # set but the stored pin hash value is bad. This means that the\n # pin was changed. In this case we count a bad auth and unset the\n # cookie. This way it becomes harder to guess the cookie name\n # instead of the pin as we still count up failures.\n bad_cookie = False\n if trust is None:\n self._fail_pin_auth()\n bad_cookie = True", " # If we're trusted, we're authenticated.\n elif trust:\n auth = True", " # If we failed too many times, then we're locked out.\n elif self._failed_pin_auth > 10:\n exhausted = True", " # Otherwise go through pin based authentication\n else:\n entered_pin = request.args.get(\"pin\")\n if entered_pin.strip().replace(\"-\", \"\") == self.pin.replace(\"-\", \"\"):\n self._failed_pin_auth = 0\n auth = True\n else:\n self._fail_pin_auth()", " rv = Response(\n json.dumps({\"auth\": auth, \"exhausted\": exhausted}),\n mimetype=\"application/json\",\n )\n if auth:\n rv.set_cookie(\n self.pin_cookie_name,\n \"%s|%s\" % (int(time.time()), hash_pin(self.pin)),\n httponly=True,\n )\n elif bad_cookie:\n rv.delete_cookie(self.pin_cookie_name)\n return rv", " def log_pin_request(self):\n \"\"\"Log the pin if needed.\"\"\"\n if self.pin_logging and self.pin is not None:\n _log(\n \"info\", \" * To enable the debugger you need to enter the security pin:\"\n )\n _log(\"info\", \" * Debugger pin code: %s\" % self.pin)\n return Response(\"\")", " def __call__(self, environ, start_response):\n \"\"\"Dispatch the requests.\"\"\"\n # important: don't ever access a function here that reads the incoming\n # form data! Otherwise the application won't have access to that data\n # any more!\n request = Request(environ)\n response = self.debug_application\n if request.args.get(\"__debugger__\") == \"yes\":\n cmd = request.args.get(\"cmd\")\n arg = request.args.get(\"f\")\n secret = request.args.get(\"s\")\n traceback = self.tracebacks.get(request.args.get(\"tb\", type=int))\n frame = self.frames.get(request.args.get(\"frm\", type=int))\n if cmd == \"resource\" and arg:\n response = self.get_resource(request, arg)\n elif cmd == \"paste\" and traceback is not None and secret == self.secret:\n response = self.paste_traceback(request, traceback)\n elif cmd == \"pinauth\" and secret == self.secret:\n response = self.pin_auth(request)\n elif cmd == \"printpin\" and secret == self.secret:\n response = self.log_pin_request()\n elif (\n self.evalex\n and cmd is not None\n and frame is not None\n and self.secret == secret\n and self.check_pin_trust(environ)\n ):\n response = self.execute_command(request, cmd, frame)\n elif (\n self.evalex\n and self.console_path is not None\n and request.path == self.console_path\n ):\n response = self.display_console(request)\n return response(environ, start_response)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [22, 69], "buggy_code_start_loc": [22, 69], "filenames": ["CHANGES.rst", "src/werkzeug/debug/__init__.py"], "fixing_code_end_loc": [25, 83], "fixing_code_start_loc": [23, 70], "message": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:palletsprojects:werkzeug:*:*:*:*:*:*:*:*", "matchCriteriaId": "2BEABB52-D59B-4CBF-AD1B-47B7F8909E70", "versionEndExcluding": "0.15.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pallets Werkzeug before 0.15.3, when used with Docker, has insufficient debugger PIN randomness because Docker containers share the same machine id."}, {"lang": "es", "value": "Pallets Werkzeug en versiones anteriores a 0.15.3, cuando es usado con Docker, presenta una aleatoriedad insuficiente del PIN del depurador porque los contenedores Docker comparten la mismo id de m\u00e1quina."}], "evaluatorComment": null, "id": "CVE-2019-14806", "lastModified": "2023-03-03T19:34:49.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-08-09T15:15:12.917", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-09/msg00047.html"}, {"source": "cve@mitre.org", "tags": ["Product"], "url": "https://github.com/pallets/werkzeug/blob/7fef41b120327d3912fbe12fb64f1951496fcf3e/src/werkzeug/debug/__init__.py#L168"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://palletsprojects.com/blog/werkzeug-0-15-3-released/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-331"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pallets/werkzeug/commit/00bc43b1672e662e5e3b8cecd79e67fc968fa246"}, "type": "CWE-331"}
108
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/nn_ops.cc.", "#define EIGEN_USE_THREADS", "#include \"tensorflow/core/kernels/avgpooling_op.h\"", "#include <vector>", "#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/kernel_shape_util.h\"\n#include \"tensorflow/core/framework/numeric_op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/tensor_slice.h\"\n#include \"tensorflow/core/kernels/eigen_pooling.h\"\n#include \"tensorflow/core/kernels/ops_util.h\"\n#include \"tensorflow/core/kernels/pooling_ops_common.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/gtl/array_slice.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/util/padding.h\"\n#include \"tensorflow/core/util/tensor_format.h\"", "#if GOOGLE_CUDA\n#include \"third_party/gpus/cudnn/cudnn.h\"\n#endif // GOOGLE_CUDA", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n#include \"tensorflow/core/kernels/maxpooling_op_gpu.h\"\n#include \"tensorflow/core/kernels/pooling_ops_common_gpu.h\"\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "namespace tensorflow {", "typedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;", "template <typename Device, typename T>\nclass AvgPoolingOp : public UnaryOp<T> {\n public:\n explicit AvgPoolingOp(OpKernelConstruction* context) : UnaryOp<T>(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES(\n context, data_format_ == FORMAT_NHWC,\n errors::InvalidArgument(\"Default AvgPoolingOp only supports NHWC \",\n \"on device type \",\n DeviceTypeString(context->device_type())));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window stride field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));", " for (int i = 0; i < ksize_.size(); ++i) {\n OP_REQUIRES(context, ksize_[i] != 0,\n errors::InvalidArgument(\"ksize cannot be zero\"));\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n PoolParameters params{context,\n ksize_,\n stride_,\n padding_,\n /*explicit_paddings=*/{},\n data_format_,\n tensor_in.shape()};\n if (!context->status().ok()) {\n return;\n }\n OP_REQUIRES(context, params.depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " // For avgpooling, tensor_in should have 4 dimensions.\n OP_REQUIRES(context, tensor_in.dims() == 4,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));", " Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, params.forward_output_shape(), &output));", " SpatialAvgPool<Device, T>(context, output, tensor_in, params, padding_);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"),\n AvgPoolingOp<CPUDevice, double>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"),\n AvgPoolingOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<Eigen::half>(\"T\"),\n AvgPoolingOp<CPUDevice, Eigen::half>);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\ntemplate <typename T>\nclass AvgPoolingOp<GPUDevice, T> : public UnaryOp<T> {\n public:\n typedef GPUDevice Device;\n explicit AvgPoolingOp(OpKernelConstruction* context) : UnaryOp<T>(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window stride field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));", " for (int i = 0; i < ksize_.size(); ++i) {\n OP_REQUIRES(context, ksize_[i] != 0,\n errors::InvalidArgument(\"ksize cannot be zero\"));\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n PoolParameters params{context,\n ksize_,\n stride_,\n padding_,\n /*explicit_paddings=*/{},\n data_format_,\n tensor_in.shape()};\n if (!context->status().ok()) {\n return;\n }\n OP_REQUIRES(context, params.depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " // For avgpooling, tensor_in should have 4 dimensions.\n OP_REQUIRES(context, tensor_in.dims() == 4,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));", " TensorShape output_shape = params.forward_output_shape();\n if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", "#if CUDNN_VERSION >= 7300\n DnnPoolingOp<T>::Compute(context, se::dnn::PoolingMode::kAverage, ksize_,\n stride_, padding_, /*explicit_paddings=*/{},\n data_format_, tensor_in, output_shape,\n /*propagate_nans=*/false);\n#else\n if (data_format_ == FORMAT_NCHW) {\n DnnPoolingOp<T>::Compute(context, se::dnn::PoolingMode::kAverage, ksize_,\n stride_, padding_, /*explicit_paddings=*/{},\n data_format_, tensor_in, output_shape,\n /*propagate_nans=*/false);\n } else {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n Eigen::PaddingType pt = BrainPadding2EigenPadding(padding_);\n functor::SpatialAvgPooling<Device, T>()(\n context->eigen_device<Device>(), output->tensor<T, 4>(),\n tensor_in.tensor<T, 4>(), params.window_rows, params.window_cols,\n params.row_stride, params.col_stride, pt);\n }\n#endif // CUDNN_VERSION >= 7300\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "// Forward declarations of the functor specializations for GPU.\nnamespace functor {\n#define DECLARE_GPU_SPEC(T) \\\n template <> \\\n void SpatialAvgPooling<GPUDevice, T>::operator()( \\\n const GPUDevice& d, typename TTypes<T, 4>::Tensor output, \\\n typename TTypes<T, 4>::ConstTensor input, int window_rows, \\\n int window_cols, int row_stride, int col_stride, \\\n const Eigen::PaddingType& padding); \\\n extern template struct SpatialAvgPooling<GPUDevice, T>;", "DECLARE_GPU_SPEC(Eigen::half);\nDECLARE_GPU_SPEC(float);\nDECLARE_GPU_SPEC(double);\n#undef DECLARE_GPU_SPEC\n} // namespace functor", "REGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<Eigen::half>(\"T\"),\n AvgPoolingOp<GPUDevice, Eigen::half>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"),\n AvgPoolingOp<GPUDevice, float>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<double>(\"T\"),\n AvgPoolingOp<GPUDevice, double>);\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// The operation to compute AvgPool gradients.\n// It takes two inputs:\n// - The original input tensor shape\n// - Backprop tensor for output\n// It produces one output: backprop tensor for input.\ntemplate <typename Device, class T>\nclass AvgPoolingGradOp : public OpKernel {\n public:\n explicit AvgPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES(\n context, data_format_ == FORMAT_NHWC,\n errors::InvalidArgument(\"Default AvgPoolingGradOp only supports NHWC \",\n \"on device type \",\n DeviceTypeString(context->device_type())));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));\n const int64_t out_backprop_batch = out_backprop.dim_size(0);\n const int64_t out_backprop_rows = out_backprop.dim_size(1);\n const int64_t out_backprop_cols = out_backprop.dim_size(2);\n const int64_t out_backprop_depth = out_backprop.dim_size(3);", " TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " output_shape.AddDim(shape_vec(i));", " }\n const int64_t in_rows = output_shape.dim_size(1);\n const int64_t in_cols = output_shape.dim_size(2);", " Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));\n output->flat<T>().setZero();", " if (output_shape.num_elements() == 0) {\n return;\n }\n const int window_rows = ksize_[1];\n const int window_cols = ksize_[2];\n const int depth_window = ksize_[3];", " const int row_stride = stride_[1];\n const int col_stride = stride_[2];", " // We (will) use different code for spatial pooling and\n // non-spatial pooling.\n //\n // Spatial pooling is when depth_window = 1\n OP_REQUIRES(context, depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " int64_t out_height, out_width, pad_rows, pad_cols;\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_rows, window_rows, row_stride,\n padding_, &out_height, &pad_rows));\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_cols, window_cols, col_stride,\n padding_, &out_width, &pad_cols));", " const T* out_backprop_ptr = out_backprop.flat<T>().data();\n T* input_backprop_ptr = output->flat<T>().data();", " auto shard = [context, out_backprop_ptr, input_backprop_ptr,\n out_backprop_rows, out_backprop_cols, out_backprop_depth,\n in_rows, in_cols, window_rows, window_cols, row_stride,\n col_stride, pad_rows,\n pad_cols](int64_t start, int64_t limit) {\n for (int64_t b = start; b < limit; ++b) {\n for (int64_t r = 0; r < out_backprop_rows; ++r) {\n // Calculates row broadcast size. For SAME padding, current\n // index could be in the padding area, and r*row_stride +\n // window_rows could be beyond the input tensor's boundary. In\n // such cases, change the starting index and reduce the\n // broadcast size.\n int rindex, rsize;\n OP_REQUIRES_OK(context,\n GetBroadcastSize(r, in_rows, window_rows, row_stride,\n pad_rows, &rindex, &rsize));\n for (int64_t c = 0; c < out_backprop_cols; ++c) {\n // Calculates col broadcast size. For SAME padding, current\n // index could be in the padding area, and c*col_stride +\n // window_cols could be beyond the input tensor's boundary. In\n // such cases, change the starting index and reduce the\n // broadcast size.\n int cindex, csize;\n OP_REQUIRES_OK(context,\n GetBroadcastSize(c, in_cols, window_cols, col_stride,\n pad_cols, &cindex, &csize));", " T divide_coeff(1.0 / (rsize * csize));\n int64_t output_index =\n (b * out_backprop_rows + r) * out_backprop_cols + c;\n for (int64_t r_dst = rindex; r_dst < rindex + rsize; ++r_dst) {\n for (int64_t c_dst = cindex; c_dst < cindex + csize; ++c_dst) {\n int64_t input_index = (b * in_rows + r_dst) * in_cols + c_dst;\n const T* output_offset =\n out_backprop_ptr + output_index * out_backprop_depth;\n T* input_offset =\n input_backprop_ptr + input_index * out_backprop_depth;\n for (int64_t d = 0; d < out_backprop_depth; ++d) {\n *input_offset += *output_offset * divide_coeff;\n ++output_offset;\n ++input_offset;\n }\n }\n }\n }\n }\n }\n };", " const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n const int64_t shard_cost =\n window_rows * window_cols * depth_window * in_rows * in_rows * in_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n out_backprop_batch, shard_cost, shard);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "#define REGISTER_CPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\") \\\n .HostMemory(\"orig_input_shape\"), \\\n AvgPoolingGradOp<CPUDevice, T>);", "TF_CALL_float(REGISTER_CPU_KERNEL);\nTF_CALL_double(REGISTER_CPU_KERNEL);\nTF_CALL_half(REGISTER_CPU_KERNEL);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// A CUDNN based AvgPoolingGrad implementation. It includes the padding as the\n// candidates for the pooling operation.\ntemplate <class T>\nclass AvgPoolingGradOp<GPUDevice, T> : public OpKernel {\n public:\n typedef GPUDevice Device;", " explicit AvgPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));", " TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " output_shape.AddDim(shape_vec(i));", " }", " if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", " DnnPoolingGradOp<T>::Compute(\n context, se::dnn::PoolingMode::kAverage, ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_, nullptr, nullptr, out_backprop,\n output_shape, /*propagate_nans=*/false);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<double>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, double>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<float>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<Eigen::half>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, Eigen::half>);", "// A custom GPU kernel based AvgPoolingGrad implementation. It includes the\n// padding as the candidates for the pooling operation.\ntemplate <class T>\nclass AvgPoolingGradOpCustomGPUKernel : public OpKernel {\n public:\n typedef GPUDevice Device;", " explicit AvgPoolingGradOpCustomGPUKernel(OpKernelConstruction* context)\n : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));\n TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " output_shape.AddDim(shape_vec(i));", " }\n if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", "#if CUDNN_VERSION >= 7300\n DnnPoolingGradOp<T>::Compute(context, se::dnn::PoolingMode::kAverage,\n ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_,\n nullptr, nullptr, out_backprop, output_shape,\n /*propagate_nans=*/false);\n#else\n if (data_format_ == FORMAT_NHWC) {\n const int64 out_backprop_batch = out_backprop.dim_size(0);\n const int64 out_backprop_rows = out_backprop.dim_size(1);\n const int64 out_backprop_cols = out_backprop.dim_size(2);\n const int64 out_backprop_depth = out_backprop.dim_size(3);", " const int64 in_rows = output_shape.dim_size(1);\n const int64 in_cols = output_shape.dim_size(2);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));", " const int window_rows = ksize_[1];\n const int window_cols = ksize_[2];\n const int depth_window = ksize_[3];", " const int row_stride = stride_[1];\n const int col_stride = stride_[2];", " // We (will) use different code for spatial pooling and\n // non-spatial pooling.\n //\n // Spatial pooling is when depth_window = 1\n OP_REQUIRES(context, depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " int64 out_height, out_width, pad_rows, pad_cols;\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_rows, window_rows, row_stride,\n padding_, &out_height, &pad_rows));\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_cols, window_cols, col_stride,\n padding_, &out_width, &pad_cols));", " RunAvePoolBackwardNHWC<T>(out_backprop.flat<T>().data(), // top_diff\n out_backprop_batch, // num\n in_rows, // height\n in_cols, // width\n out_backprop_depth, // channels\n out_backprop_rows, // pooled_height\n out_backprop_cols, // pooled_width\n window_rows, // kernel_h\n window_cols, // kernel_w\n row_stride, // stride_h\n col_stride, // stride_w\n pad_rows, // pad_t\n pad_cols, // pad_l\n output->flat<T>().data(), // bottom_diff\n context->eigen_gpu_device()); // d\n } else {\n DnnPoolingGradOp<T>::Compute(context, se::dnn::PoolingMode::kAverage,\n ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_,\n nullptr, nullptr, out_backprop, output_shape,\n /*propagate_nans=*/false);\n }\n#endif // CUDNN_VERSION >= 7300\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<float>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<float>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<double>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<double>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<Eigen::half>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<Eigen::half>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [547, 2472], "buggy_code_start_loc": [301, 2472], "filenames": ["tensorflow/core/kernels/avgpooling_op.cc", "tensorflow/python/kernel_tests/nn_ops/pooling_ops_test.py"], "fixing_code_end_loc": [547, 2489], "fixing_code_start_loc": [301, 2473], "message": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C4DFBF2D-5283-42F6-8800-D653BFA5CE82", "versionEndExcluding": "2.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F9D273D-02DC-441E-AA91-EAC8DEAA4B44", "versionEndExcluding": "2.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FE4F8A81-6CC2-4F7F-9602-C170FDD926E7", "versionEndExcluding": "2.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc0:*:*:*:*:*:*", "matchCriteriaId": "1DBFBCE2-0A01-4575-BE45-6775ABFB8B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc1:*:*:*:*:*:*", "matchCriteriaId": "89806CF9-E423-4CA6-A01A-8175C260CB24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc2:*:*:*:*:*:*", "matchCriteriaId": "F2B80690-A257-4E16-BD27-9AE045BC56ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc3:*:*:*:*:*:*", "matchCriteriaId": "F335F9A4-5AB8-4E53-BC18-E01F7C653E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto para el aprendizaje autom\u00e1tico. La funci\u00f3n \"AvgPoolOp\" toma un argumento \"ksize\" que debe ser positivo pero no se comprueba. Un \"ksize\" negativo puede desencadenar un fallo de \"CHECK\" y bloquear el programa. Hemos parcheado el problema en el commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.10.0. Tambi\u00e9n seleccionaremos este compromiso en TensorFlow versi\u00f3n 2.9.1, TensorFlow versi\u00f3n 2.8.1, y TensorFlow versi\u00f3n 2.7.2, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango admitido. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-35941", "lastModified": "2022-09-20T18:07:25.377", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-16T20:15:10.377", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/avgpooling_op.cc#L56-L98"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mgmh-g2v6-mqw5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-617"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, "type": "CWE-617"}
109
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "// See docs in ../ops/nn_ops.cc.", "#define EIGEN_USE_THREADS", "#include \"tensorflow/core/kernels/avgpooling_op.h\"", "#include <vector>", "#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/kernel_shape_util.h\"\n#include \"tensorflow/core/framework/numeric_op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/tensor.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/tensor_slice.h\"\n#include \"tensorflow/core/kernels/eigen_pooling.h\"\n#include \"tensorflow/core/kernels/ops_util.h\"\n#include \"tensorflow/core/kernels/pooling_ops_common.h\"\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/gtl/array_slice.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/util/padding.h\"\n#include \"tensorflow/core/util/tensor_format.h\"", "#if GOOGLE_CUDA\n#include \"third_party/gpus/cudnn/cudnn.h\"\n#endif // GOOGLE_CUDA", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n#include \"tensorflow/core/kernels/maxpooling_op_gpu.h\"\n#include \"tensorflow/core/kernels/pooling_ops_common_gpu.h\"\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "namespace tensorflow {", "typedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;", "template <typename Device, typename T>\nclass AvgPoolingOp : public UnaryOp<T> {\n public:\n explicit AvgPoolingOp(OpKernelConstruction* context) : UnaryOp<T>(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES(\n context, data_format_ == FORMAT_NHWC,\n errors::InvalidArgument(\"Default AvgPoolingOp only supports NHWC \",\n \"on device type \",\n DeviceTypeString(context->device_type())));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window stride field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));", " for (int i = 0; i < ksize_.size(); ++i) {\n OP_REQUIRES(context, ksize_[i] != 0,\n errors::InvalidArgument(\"ksize cannot be zero\"));\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n PoolParameters params{context,\n ksize_,\n stride_,\n padding_,\n /*explicit_paddings=*/{},\n data_format_,\n tensor_in.shape()};\n if (!context->status().ok()) {\n return;\n }\n OP_REQUIRES(context, params.depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " // For avgpooling, tensor_in should have 4 dimensions.\n OP_REQUIRES(context, tensor_in.dims() == 4,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));", " Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, params.forward_output_shape(), &output));", " SpatialAvgPool<Device, T>(context, output, tensor_in, params, padding_);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"),\n AvgPoolingOp<CPUDevice, double>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"),\n AvgPoolingOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_CPU).TypeConstraint<Eigen::half>(\"T\"),\n AvgPoolingOp<CPUDevice, Eigen::half>);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM\ntemplate <typename T>\nclass AvgPoolingOp<GPUDevice, T> : public UnaryOp<T> {\n public:\n typedef GPUDevice Device;\n explicit AvgPoolingOp(OpKernelConstruction* context) : UnaryOp<T>(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window stride field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));", " for (int i = 0; i < ksize_.size(); ++i) {\n OP_REQUIRES(context, ksize_[i] != 0,\n errors::InvalidArgument(\"ksize cannot be zero\"));\n }\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in = context->input(0);\n PoolParameters params{context,\n ksize_,\n stride_,\n padding_,\n /*explicit_paddings=*/{},\n data_format_,\n tensor_in.shape()};\n if (!context->status().ok()) {\n return;\n }\n OP_REQUIRES(context, params.depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " // For avgpooling, tensor_in should have 4 dimensions.\n OP_REQUIRES(context, tensor_in.dims() == 4,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));", " TensorShape output_shape = params.forward_output_shape();\n if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", "#if CUDNN_VERSION >= 7300\n DnnPoolingOp<T>::Compute(context, se::dnn::PoolingMode::kAverage, ksize_,\n stride_, padding_, /*explicit_paddings=*/{},\n data_format_, tensor_in, output_shape,\n /*propagate_nans=*/false);\n#else\n if (data_format_ == FORMAT_NCHW) {\n DnnPoolingOp<T>::Compute(context, se::dnn::PoolingMode::kAverage, ksize_,\n stride_, padding_, /*explicit_paddings=*/{},\n data_format_, tensor_in, output_shape,\n /*propagate_nans=*/false);\n } else {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n Eigen::PaddingType pt = BrainPadding2EigenPadding(padding_);\n functor::SpatialAvgPooling<Device, T>()(\n context->eigen_device<Device>(), output->tensor<T, 4>(),\n tensor_in.tensor<T, 4>(), params.window_rows, params.window_cols,\n params.row_stride, params.col_stride, pt);\n }\n#endif // CUDNN_VERSION >= 7300\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "// Forward declarations of the functor specializations for GPU.\nnamespace functor {\n#define DECLARE_GPU_SPEC(T) \\\n template <> \\\n void SpatialAvgPooling<GPUDevice, T>::operator()( \\\n const GPUDevice& d, typename TTypes<T, 4>::Tensor output, \\\n typename TTypes<T, 4>::ConstTensor input, int window_rows, \\\n int window_cols, int row_stride, int col_stride, \\\n const Eigen::PaddingType& padding); \\\n extern template struct SpatialAvgPooling<GPUDevice, T>;", "DECLARE_GPU_SPEC(Eigen::half);\nDECLARE_GPU_SPEC(float);\nDECLARE_GPU_SPEC(double);\n#undef DECLARE_GPU_SPEC\n} // namespace functor", "REGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<Eigen::half>(\"T\"),\n AvgPoolingOp<GPUDevice, Eigen::half>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"),\n AvgPoolingOp<GPUDevice, float>);\nREGISTER_KERNEL_BUILDER(\n Name(\"AvgPool\").Device(DEVICE_GPU).TypeConstraint<double>(\"T\"),\n AvgPoolingOp<GPUDevice, double>);\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// The operation to compute AvgPool gradients.\n// It takes two inputs:\n// - The original input tensor shape\n// - Backprop tensor for output\n// It produces one output: backprop tensor for input.\ntemplate <typename Device, class T>\nclass AvgPoolingGradOp : public OpKernel {\n public:\n explicit AvgPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES(\n context, data_format_ == FORMAT_NHWC,\n errors::InvalidArgument(\"Default AvgPoolingGradOp only supports NHWC \",\n \"on device type \",\n DeviceTypeString(context->device_type())));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));\n const int64_t out_backprop_batch = out_backprop.dim_size(0);\n const int64_t out_backprop_rows = out_backprop.dim_size(1);\n const int64_t out_backprop_cols = out_backprop.dim_size(2);\n const int64_t out_backprop_depth = out_backprop.dim_size(3);", " TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(shape_vec(i)));", " }\n const int64_t in_rows = output_shape.dim_size(1);\n const int64_t in_cols = output_shape.dim_size(2);", " Tensor* output = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));\n output->flat<T>().setZero();", " if (output_shape.num_elements() == 0) {\n return;\n }\n const int window_rows = ksize_[1];\n const int window_cols = ksize_[2];\n const int depth_window = ksize_[3];", " const int row_stride = stride_[1];\n const int col_stride = stride_[2];", " // We (will) use different code for spatial pooling and\n // non-spatial pooling.\n //\n // Spatial pooling is when depth_window = 1\n OP_REQUIRES(context, depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " int64_t out_height, out_width, pad_rows, pad_cols;\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_rows, window_rows, row_stride,\n padding_, &out_height, &pad_rows));\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_cols, window_cols, col_stride,\n padding_, &out_width, &pad_cols));", " const T* out_backprop_ptr = out_backprop.flat<T>().data();\n T* input_backprop_ptr = output->flat<T>().data();", " auto shard = [context, out_backprop_ptr, input_backprop_ptr,\n out_backprop_rows, out_backprop_cols, out_backprop_depth,\n in_rows, in_cols, window_rows, window_cols, row_stride,\n col_stride, pad_rows,\n pad_cols](int64_t start, int64_t limit) {\n for (int64_t b = start; b < limit; ++b) {\n for (int64_t r = 0; r < out_backprop_rows; ++r) {\n // Calculates row broadcast size. For SAME padding, current\n // index could be in the padding area, and r*row_stride +\n // window_rows could be beyond the input tensor's boundary. In\n // such cases, change the starting index and reduce the\n // broadcast size.\n int rindex, rsize;\n OP_REQUIRES_OK(context,\n GetBroadcastSize(r, in_rows, window_rows, row_stride,\n pad_rows, &rindex, &rsize));\n for (int64_t c = 0; c < out_backprop_cols; ++c) {\n // Calculates col broadcast size. For SAME padding, current\n // index could be in the padding area, and c*col_stride +\n // window_cols could be beyond the input tensor's boundary. In\n // such cases, change the starting index and reduce the\n // broadcast size.\n int cindex, csize;\n OP_REQUIRES_OK(context,\n GetBroadcastSize(c, in_cols, window_cols, col_stride,\n pad_cols, &cindex, &csize));", " T divide_coeff(1.0 / (rsize * csize));\n int64_t output_index =\n (b * out_backprop_rows + r) * out_backprop_cols + c;\n for (int64_t r_dst = rindex; r_dst < rindex + rsize; ++r_dst) {\n for (int64_t c_dst = cindex; c_dst < cindex + csize; ++c_dst) {\n int64_t input_index = (b * in_rows + r_dst) * in_cols + c_dst;\n const T* output_offset =\n out_backprop_ptr + output_index * out_backprop_depth;\n T* input_offset =\n input_backprop_ptr + input_index * out_backprop_depth;\n for (int64_t d = 0; d < out_backprop_depth; ++d) {\n *input_offset += *output_offset * divide_coeff;\n ++output_offset;\n ++input_offset;\n }\n }\n }\n }\n }\n }\n };", " const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n const int64_t shard_cost =\n window_rows * window_cols * depth_window * in_rows * in_rows * in_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n out_backprop_batch, shard_cost, shard);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "#define REGISTER_CPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\") \\\n .HostMemory(\"orig_input_shape\"), \\\n AvgPoolingGradOp<CPUDevice, T>);", "TF_CALL_float(REGISTER_CPU_KERNEL);\nTF_CALL_double(REGISTER_CPU_KERNEL);\nTF_CALL_half(REGISTER_CPU_KERNEL);", "#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "// A CUDNN based AvgPoolingGrad implementation. It includes the padding as the\n// candidates for the pooling operation.\ntemplate <class T>\nclass AvgPoolingGradOp<GPUDevice, T> : public OpKernel {\n public:\n typedef GPUDevice Device;", " explicit AvgPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));", " TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(shape_vec(i)));", " }", " if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", " DnnPoolingGradOp<T>::Compute(\n context, se::dnn::PoolingMode::kAverage, ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_, nullptr, nullptr, out_backprop,\n output_shape, /*propagate_nans=*/false);\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<double>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, double>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<float>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<Eigen::half>(\"T\")\n .HostMemory(\"orig_input_shape\")\n .Label(\"cudnn\"),\n AvgPoolingGradOp<GPUDevice, Eigen::half>);", "// A custom GPU kernel based AvgPoolingGrad implementation. It includes the\n// padding as the candidates for the pooling operation.\ntemplate <class T>\nclass AvgPoolingGradOpCustomGPUKernel : public OpKernel {\n public:\n typedef GPUDevice Device;", " explicit AvgPoolingGradOpCustomGPUKernel(OpKernelConstruction* context)\n : OpKernel(context) {\n string data_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"data_format\", &data_format));\n OP_REQUIRES(context, FormatFromString(data_format, &data_format_),\n errors::InvalidArgument(\"Invalid data format\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"ksize\", &ksize_));\n OP_REQUIRES(context, ksize_.size() == 4,\n errors::InvalidArgument(\"Sliding window ksize field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &stride_));\n OP_REQUIRES(context, stride_.size() == 4,\n errors::InvalidArgument(\"Sliding window strides field must \"\n \"specify 4 dimensions\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n const int32_t ksize_n = GetTensorDim(ksize_, data_format_, 'N');\n const int32_t stride_n = GetTensorDim(stride_, data_format_, 'N');\n OP_REQUIRES(context, ksize_n == 1 && stride_n == 1,\n errors::Unimplemented(\n \"Pooling is not yet supported on the batch dimension.\"));\n }", " void Compute(OpKernelContext* context) override {\n const Tensor& tensor_in_shape = context->input(0);\n const Tensor& out_backprop = context->input(1);\n // For avgpooling, tensor_in_shape should have 1 dimension, and 4 elements.\n OP_REQUIRES(\n context,\n tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 4,\n errors::InvalidArgument(\"out_backprop must be 1-dimensional and 4 \"\n \"elements\"));\n // For avgpooling, out_backprop should have 4 dimensions.\n OP_REQUIRES(context, out_backprop.dims() == 4,\n errors::InvalidArgument(\"out_backprop must be 4-dimensional\"));\n TensorShape output_shape;\n auto shape_vec = tensor_in_shape.vec<int32>();\n for (int64_t i = 0; i < tensor_in_shape.NumElements(); ++i) {", " OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(shape_vec(i)));", " }\n if (output_shape.num_elements() == 0) {\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));\n return;\n }", "#if CUDNN_VERSION >= 7300\n DnnPoolingGradOp<T>::Compute(context, se::dnn::PoolingMode::kAverage,\n ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_,\n nullptr, nullptr, out_backprop, output_shape,\n /*propagate_nans=*/false);\n#else\n if (data_format_ == FORMAT_NHWC) {\n const int64 out_backprop_batch = out_backprop.dim_size(0);\n const int64 out_backprop_rows = out_backprop.dim_size(1);\n const int64 out_backprop_cols = out_backprop.dim_size(2);\n const int64 out_backprop_depth = out_backprop.dim_size(3);", " const int64 in_rows = output_shape.dim_size(1);\n const int64 in_cols = output_shape.dim_size(2);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, output_shape, &output));", " const int window_rows = ksize_[1];\n const int window_cols = ksize_[2];\n const int depth_window = ksize_[3];", " const int row_stride = stride_[1];\n const int col_stride = stride_[2];", " // We (will) use different code for spatial pooling and\n // non-spatial pooling.\n //\n // Spatial pooling is when depth_window = 1\n OP_REQUIRES(context, depth_window == 1,\n errors::Unimplemented(\"Non-spatial pooling is not \"\n \"yet supported. Volunteers? :)\"));", " int64 out_height, out_width, pad_rows, pad_cols;\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_rows, window_rows, row_stride,\n padding_, &out_height, &pad_rows));\n OP_REQUIRES_OK(context,\n GetWindowedOutputSize(in_cols, window_cols, col_stride,\n padding_, &out_width, &pad_cols));", " RunAvePoolBackwardNHWC<T>(out_backprop.flat<T>().data(), // top_diff\n out_backprop_batch, // num\n in_rows, // height\n in_cols, // width\n out_backprop_depth, // channels\n out_backprop_rows, // pooled_height\n out_backprop_cols, // pooled_width\n window_rows, // kernel_h\n window_cols, // kernel_w\n row_stride, // stride_h\n col_stride, // stride_w\n pad_rows, // pad_t\n pad_cols, // pad_l\n output->flat<T>().data(), // bottom_diff\n context->eigen_gpu_device()); // d\n } else {\n DnnPoolingGradOp<T>::Compute(context, se::dnn::PoolingMode::kAverage,\n ksize_, stride_, padding_,\n /*explicit_paddings=*/{}, data_format_,\n nullptr, nullptr, out_backprop, output_shape,\n /*propagate_nans=*/false);\n }\n#endif // CUDNN_VERSION >= 7300\n }", " private:\n std::vector<int32> ksize_;\n std::vector<int32> stride_;\n Padding padding_;\n TensorFormat data_format_;\n};", "REGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<float>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<float>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<double>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<double>);\nREGISTER_KERNEL_BUILDER(Name(\"AvgPoolGrad\")\n .Device(DEVICE_GPU)\n .TypeConstraint<Eigen::half>(\"T\")\n .HostMemory(\"orig_input_shape\"),\n AvgPoolingGradOpCustomGPUKernel<Eigen::half>);", "#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [547, 2472], "buggy_code_start_loc": [301, 2472], "filenames": ["tensorflow/core/kernels/avgpooling_op.cc", "tensorflow/python/kernel_tests/nn_ops/pooling_ops_test.py"], "fixing_code_end_loc": [547, 2489], "fixing_code_start_loc": [301, 2473], "message": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C4DFBF2D-5283-42F6-8800-D653BFA5CE82", "versionEndExcluding": "2.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F9D273D-02DC-441E-AA91-EAC8DEAA4B44", "versionEndExcluding": "2.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FE4F8A81-6CC2-4F7F-9602-C170FDD926E7", "versionEndExcluding": "2.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc0:*:*:*:*:*:*", "matchCriteriaId": "1DBFBCE2-0A01-4575-BE45-6775ABFB8B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc1:*:*:*:*:*:*", "matchCriteriaId": "89806CF9-E423-4CA6-A01A-8175C260CB24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc2:*:*:*:*:*:*", "matchCriteriaId": "F2B80690-A257-4E16-BD27-9AE045BC56ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc3:*:*:*:*:*:*", "matchCriteriaId": "F335F9A4-5AB8-4E53-BC18-E01F7C653E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto para el aprendizaje autom\u00e1tico. La funci\u00f3n \"AvgPoolOp\" toma un argumento \"ksize\" que debe ser positivo pero no se comprueba. Un \"ksize\" negativo puede desencadenar un fallo de \"CHECK\" y bloquear el programa. Hemos parcheado el problema en el commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.10.0. Tambi\u00e9n seleccionaremos este compromiso en TensorFlow versi\u00f3n 2.9.1, TensorFlow versi\u00f3n 2.8.1, y TensorFlow versi\u00f3n 2.7.2, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango admitido. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-35941", "lastModified": "2022-09-20T18:07:25.377", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-16T20:15:10.377", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/avgpooling_op.cc#L56-L98"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mgmh-g2v6-mqw5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-617"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, "type": "CWE-617"}
109
Determine whether the {function_name} code is vulnerable or not.
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Functional tests for pooling operations.\"\"\"", "import collections\nimport os", "from absl.testing import parameterized\nimport numpy as np", "from tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nimport tensorflow.python.framework.config as config_exec\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import variables\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging", "\ndef GetDeviceScope(self, use_gpu=False):\n if context.executing_eagerly():\n if use_gpu and test.is_gpu_available():\n return ops.device(\"GPU:0\")\n return ops.device(\"CPU:0\")\n else:\n return self.session(use_gpu=use_gpu)", "\n# TODO(jlebar): Convert the rest of this file to parameters.parameterized().\n# Then remove GetTestConfigs() and rename GetTestConfigsDicts().\ndef GetTestConfigsDicts(v1_fn,\n v2_fn=None,\n one_dimensional=False,\n allow_gpu=True):\n # (data_format, use_gpu) tuple\n if one_dimensional:\n configs0 = [\n (\"NWC\", False),\n (\"NWC\", True),\n (\"NCW\", True),\n ]\n else:\n configs0 = [\n (\"NHWC\", False),\n (\"NHWC\", True),\n (\"NCHW\", True),\n ]\n # NCHW_VECT_C only supported for max_pool.\n if (v1_fn == nn_ops.max_pool or v1_fn == nn_ops.max_pool1d or\n v2_fn == nn_ops.max_pool_v2 or v2_fn == gen_nn_ops.max_pool_v2):\n configs0.append((\"NCHW_VECT_C\", True))", " # (data_format, use_gpu, data_type) tuple\n configs1 = []\n for data_format, use_gpu in configs0:\n configs1.append((data_format, use_gpu, dtypes.float32))", " # In our test, VECT_C always uses float32. (It gets converted to int8 in\n # the test runner.)\n if data_format == \"NCHW_VECT_C\":\n continue", " configs1 += [(data_format, use_gpu, dtypes.float16),\n (data_format, use_gpu, dtypes.float64)]", " # Convert from tuple to dict and add v1/v2 versions.\n ret = []\n for data_format, use_gpu, data_type in configs1:\n ret.append({\n \"pool_func\": v1_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": False\n })\n if v2_fn:\n ret.append({\n \"pool_func\": v2_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": False\n })\n ret.append({\n \"pool_func\": v2_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": True\n })", " # Filter out GPU configs if necessary.\n if not allow_gpu:\n ret = [c for c in ret if not c[\"use_gpu\"]]", " return ret", "\ndef GetTestConfigs(include_nchw_vect_c=False, one_dimensional=False):\n \"\"\"Get all the valid tests configs to run.", " Args:\n include_nchw_vect_c: Whether to include NCHW_VECT_C in the test configs.\n one_dimensional: If it's a 1D test", " Returns:\n all the valid test configs as tuples of data_format and use_gpu.\n \"\"\"\n if one_dimensional:\n test_configs = [(\"NWC\", False), (\"NWC\", True)]\n if test.is_gpu_available(cuda_only=True):\n test_configs += [(\"NCW\", True)]\n return test_configs\n test_configs = [(\"NHWC\", False), (\"NHWC\", True)]\n if not test.is_gpu_available(cuda_only=True):\n tf_logging.info(\"NCHW and NCHW_VECT_C tests skipped because not run with \"\n \"--config=cuda or no GPUs available.\")\n return test_configs\n # \"NCHW\" format is currently supported exclusively on CUDA GPUs.\n test_configs += [(\"NCHW\", True)]\n if include_nchw_vect_c:\n if test.is_gpu_available(\n cuda_only=True, min_cuda_compute_capability=(6, 1)):\n test_configs += [(\"NCHW_VECT_C\", True)]\n else:\n tf_logging.info(\"NCHW_VECT_C test skipped because no GPUs with \"\n \"compute capability >= 6.1 are available.\")", " return test_configs", "\ndef GetShrunkInceptionMaxPoolShapes(shrink=30):\n \"\"\"Iterator for some of the max pool ops in the Inception 2015 model.", " Args:\n shrink: Factor to shrink depth relative to Inception.", " Yields:\n Tuple (name, input_size, filter_size, out_size, strides, padding)\n \"\"\"\n names = [\"maxpool2\", \"maxpool3\", \"maxpool4\", \"maxpool5\"]\n input_sizes = [[32, 71, 71, 192], [32, 35, 35, 288], [32, 17, 17, 1248],\n [32, 8, 8, 2048]]\n filter_sizes = [[1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1]]\n output_sizes = [[32, 35, 35, 192], [32, 17, 17, 288], [32, 8, 8, 1248],\n [32, 8, 8, 2048]]\n strides = [[1, 2, 2, 1], [1, 2, 2, 1], [1, 2, 2, 1], [1, 1, 1, 1]]\n # Shrink each depth value\n for i in input_sizes:\n i[3] //= shrink\n for o in output_sizes:\n o[3] //= shrink\n paddings = [\"VALID\", \"VALID\", \"VALID\", \"SAME\"]\n for n, i, f, o, s, p in zip(names, input_sizes, filter_sizes, output_sizes,\n strides, paddings):\n yield n, i, f, o, s, p", "\n@test_util.with_eager_op_as_function\nclass PoolingTest(test.TestCase, parameterized.TestCase):", " def _isMaxPool(self, func):\n return func in (nn_ops.max_pool, nn_ops.max_pool_v2)", " def _VerifyOneType(self, pool_func, input_sizes, ksize, strides, padding,\n data_format, data_type, expected, use_gpu, v2,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n data_format: The data format we use to run the pooling operation.\n data_type: The data type to use to run the pooling operation.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n use_negative_input: If the input values should be negative.\n \"\"\"\n # Check that this test is compatible with the hardware we have. (Really\n # this should be done in GetTestConfigsDicts(), but when that runs, we\n # haven't initialized enough of TF to know what our hardware is!)\n if use_gpu and not test.is_gpu_available():\n self.skipTest(\"No GPU is available.\")\n if use_gpu and data_type == dtypes.float64 and test.is_built_with_rocm():\n self.skipTest(\"ROCm pooling ops don't support float64.\")\n if use_gpu and data_format == \"NCHW_VECT_C\" and not test.is_gpu_available(\n cuda_only=True, min_cuda_compute_capability=(6, 1)):\n self.skipTest(\"NCHW_VECT_C requires sm61+.\")", " if v2 and data_format != \"NHWC\":\n self.skipTest(\"v2 not supported for %s\" % data_format)\n if v2 and not isinstance(padding, str):\n self.skipTest(\"non-constant ksize/strides requires nonexplicit padding\")\n if data_format == \"NCHW_VECT_C\":\n if data_type != dtypes.float32:\n self.skipTest(\"quantization to qint8 not implemented for %r\" %\n data_type)\n if input_sizes[-1] % 4 != 0:\n self.skipTest(\"Skipping test for depth %d\" % input_sizes[-1])", " total_size = 1\n for s in input_sizes:\n total_size *= s\n tf_logging.info(\"Running %s test. %r %r %d %r %r %r %s\", data_format, v2,\n input_sizes, total_size, pool_func, ksize, strides,\n data_type)\n # Initializes the input tensor with array containing incrementing\n # numbers from 1, wrapping round to -127 after 127 to support int8.\n y = -1 if use_negative_input else 1\n x = [(((f + 128) % 255) - 127)*y for f in range(total_size)]\n with self.cached_session(use_gpu=use_gpu):\n t = constant_op.constant(x, shape=input_sizes, dtype=data_type)\n if data_format in (\"NCHW\", \"NCHW_VECT_C\", \"NCW\"):\n if data_format == \"NCHW_VECT_C\":\n t = test_util.NHWCToNCHW_VECT_C(t)\n t, _, _ = gen_array_ops.quantize_v2(t, -128.0, 127.0, dtypes.qint8)\n else:\n t = test_util.NHWCToNCHW(t)\n ksize = test_util.NHWCToNCHW(ksize)\n strides = test_util.NHWCToNCHW(strides)\n if isinstance(padding, list):\n padding = test_util.NHWCToNCHW(padding)\n ksize_placeholder = array_ops.placeholder(dtypes.int32, shape=[4])\n strides_placeholder = array_ops.placeholder(dtypes.int32, shape=[4])\n if v2:\n t = pool_func(\n t,\n ksize=ksize_placeholder,\n strides=strides_placeholder,\n padding=padding,\n data_format=data_format)\n else:\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format)\n if data_format == \"NCHW_VECT_C\":\n t = gen_array_ops.dequantize(t, -128, 127)\n t = test_util.NCHW_VECT_CToNHWC(t)\n elif data_format == \"NCHW\":\n t = test_util.NCHWToNHWC(t)\n if v2:\n actual = t.eval(feed_dict={\n ksize_placeholder: ksize,\n strides_placeholder: strides\n })\n else:\n actual = self.evaluate(t)\n self.assertShapeEqual(actual, t)\n self.assertAllCloseAccordingToType(expected, actual.flatten())", " def _VerifyOneTest(self, pool_func, input_sizes, ksize, strides, padding,\n data_format, expected, use_gpu, v2,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n data_format: The data format we use to run the pooling operation.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n use_negative_input: If the input values should be negative.\"\n \"\"\"\n if data_format == \"NCHW_VECT_C\":\n avg_pool_func = nn_ops.avg_pool\n tf_logging.info(\"pool_func=%s\", pool_func)\n if pool_func == avg_pool_func:\n tf_logging.info(\"NCHW_VECT_C not yet implemented for avg_pool\")\n return\n if (self._isMaxPool(pool_func) and isinstance(padding, list)):\n tf_logging.info(\"NCHW_VECT_C not yet implemented for max pool\" +\n \" with explicit padding\")\n return", " self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float32, expected, use_gpu, v2,\n use_negative_input)\n if not test.is_built_with_rocm():\n # double datatype is not supported for pooling ops on the ROCm platform\n self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float64, expected, use_gpu, v2,\n use_negative_input)", " if not use_gpu or test_util.GpuSupportsHalfMatMulAndConv():\n self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float16, expected, use_gpu, v2,\n use_negative_input)", " def _VerifyValues(self,\n pool_func,\n input_sizes,\n ksize,\n strides,\n padding,\n expected,\n use_gpu,\n v2=False,\n one_dim=False,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n one_dim: If one dimensional pools should be done instead of two\n dimensional pools.\n use_negative_input: If the input values should be negative.\n \"\"\"\n for (data_format, use_gpu_2) in GetTestConfigs(\n include_nchw_vect_c=True, one_dimensional=one_dim):\n if use_gpu_2 == use_gpu:\n self._VerifyOneTest(pool_func, input_sizes, ksize, strides, padding,\n data_format, expected, use_gpu, v2,\n use_negative_input)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolEmpty(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 0],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 2, 4, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[8.5, 9.5, 10.5, 14.5, 15.5, 16.5],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindow(self, **kwargs):\n # input is:\n # [1.0, 2.0\n # 3.0 4.0]\n #\n # Window of [x, x] should do:\n # [avg(1.0, 2.0), avg(2.0, padded0),\n # avg(3.0, 4.0), avg(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[1.5, 2.0, 3.5, 4.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindow_2(self, **kwargs):\n # Window of [x,\n # x] should do:\n # [avg(1.0, 3.0), avg(2.0, 4.0)\n # avg(3.0, padded0), avg(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 2, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[2.0, 3.0, 3.0, 4.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindowMultiBatch(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[2, 2, 2, 2],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[\n 2.0, 3.0, 3.0, 4.0, 6.0, 7.0, 7.0, 8.0, 10.0, 11.0, 11.0, 12.0,\n 14.0, 15.0, 15.0, 16.0\n ],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindowMultiBatch_2(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[2, 2, 2, 2],\n ksize=[1, 2, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[\n 3.0, 4.0, 5.0, 6.0, 5.0, 6.0, 7.0, 8.0, 11.0, 12.0, 13.0, 14.0,\n 13.0, 14.0, 15.0, 16.0\n ],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPaddingUnevenStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 2, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0, 16.0, 17.0, 18.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPaddingUnevenStride_2(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 1, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0, 10.0, 11.0, 12.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePadding_2(self, **kwargs):\n expected_output = [\n 11.0, 12.0, 13.0, 14.0, 19.0, 20.0, 21.0, 22.0, 43.0, 44.0, 45.0, 46.0,\n 51.0, 52.0, 53.0, 54.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingPacket_4(self, **kwargs):\n expected_output = [\n 21.0, 22.0, 23.0, 24.0, 27.0, 28.0, 29.0, 30.0, 45.0, 46.0, 47.0, 48.0,\n 51.0, 52.0, 53.0, 54.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingPacket_8(self, **kwargs):\n expected_output = [\n -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, 4.0, 5.0, 6.0, 7.0,\n 8.0, 9.0, 10.0, 11.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0,\n 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, -3.5, -54.0, -53.0, -52.0,\n -51.0, -50.0, -49.0, -48.0, -47.0, -38.0, -37.0, -36.0, -35.0, -34.0,\n -33.0, -32.0, -31.0, -22.0, -21.0, -20.0, -19.0, -18.0, -17.0, -16.0,\n -15.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -11.0, -10.0,\n -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,\n 12.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 33.0, 34.0, 35.0,\n 36.0, 37.0, 38.0, -3.5, -2.5, -85.0, -84.0, -83.0, -82.0, -81.0, -80.0,\n -79.0, -78.0, -69.0, -68.0, -67.0, -66.0, -65.0, -64.0, -63.0, -62.0,\n -53.0, -52.0, -51.0, -50.0, -49.0, -48.0, -47.0, -46.0, -41.0, -40.0,\n -39.0, -38.0, -37.0, -36.0, -35.0, -34.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolEmptyInput(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[0, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[13.0, 14.0, 15.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 2, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[13.0, 14.0, 15.0, 16.0, 17.0, 18.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolZeroExplicitPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 0], [0, 0], [0, 0]],\n expected=[9.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolNegativeInputExpPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [2, 1], [2, 1], [0, 0]],\n expected=[-1, -1, -1, -1],\n use_negative_input=True,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding(self, **kwargs):\n expected_output = [9.0, 9.0]\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 2], [0, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPaddingAdvanced(self, **kwargs):\n expected_output = [7, 9, 11, 12, 19, 21, 23, 24, 31, 33, 35, 36, 31, 33,\n 35, 36]\n self._VerifyOneType(\n input_sizes=[1, 6, 6, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [1, 2], [2, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolNegativeInputExpPaddingAdv(self, **kwargs):\n expected_output = [-1, -1, -3, -5, -7, -7, -9, -11, -19, -19, -21, -23, -31,\n -31, -33, -35]", " self._VerifyOneType(\n input_sizes=[1, 6, 6, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [1, 2], [2, 1], [0, 0]],\n expected=expected_output,\n use_negative_input=True,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding2_(self, **kwargs):\n expected_output = [9.0, 9.0]\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 2], [0, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool1d, nn_ops.max_pool_v2, one_dimensional=True))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding_1D(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 1],\n ksize=[1, 2, 1],\n strides=[1, 2, 1],\n padding=[[0, 0], [0, 1], [0, 0]],\n expected=[2.0, 3.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingNonSquareWindow(self, **kwargs):\n # input is:\n # [1.0, 2.0\n # 3.0 4.0]\n #\n # Window of [x, x] should do:\n #\n # [max(1.0, 2.0), max(2.0, padded0),\n # max(3.0, 4.0), max(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[2.0, 2.0, 4.0, 4.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPaddingUnevenStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 2, 1],\n padding=\"VALID\",\n expected=[6.0, 8.0, 10.0, 12.0, 14.0, 16.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPaddingUnevenStride2_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 1, 1],\n padding=\"VALID\",\n expected=[6.0, 7.0, 8.0, 14.0, 15.0, 16.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingPacket4_(self, **kwargs):\n expected_output = [\n 21.0, 22.0, 23.0, 24.0, 29.0, 30.0, 31.0, 32.0, 53.0, 54.0, 55.0, 56.0,\n 61.0, 62.0, 63.0, 64.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingPacket8_(self, **kwargs):\n expected_output = [\n 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 97.0, 98.0, 99.0, 100.0,\n 101.0, 102.0, 103.0, 104.0, 113.0, 114.0, 115.0, 116.0, 117.0, 118.0,\n 119.0, 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0, 120.0,\n 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 34.0, 35.0, 36.0, 37.0,\n 38.0, 39.0, 40.0, 41.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0,\n 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 82.0, 83.0, 84.0, 85.0,\n 86.0, 87.0, 88.0, 89.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, 104.0,\n 105.0, 114.0, 115.0, 116.0, 117.0, 118.0, 119.0, 120.0, 121.0, 122.0,\n 123.0, 124.0, 125.0, 126.0, 127.0, 120.0, 121.0, -45.0, -44.0, -43.0,\n -42.0, -41.0, -40.0, -39.0, -38.0, -29.0, -28.0, -27.0, -26.0, -25.0,\n -24.0, -23.0, -22.0, -13.0, -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0,\n -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolEmptyInput(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[0, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[],\n **kwargs)", " # Tests for DepthwiseMaxPooling on CPU only.\n @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testDepthwiseMaxPool1x1DepthWindow(self, **kwargs):\n # input is:\n # [1.0, ..., 10.0] along depth,\n #\n # We maxpool by depth in patches of 2.\n self._VerifyOneType(\n input_sizes=[1, 1, 1, 10],\n ksize=[1, 1, 1, 2],\n strides=[1, 1, 1, 2],\n padding=\"SAME\",\n expected=[2.0, 4.0, 6.0, 8.0, 10.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testDepthwiseMaxPool2x2DepthWindow(self, **kwargs):\n # input is:\n #\n # a 2x2x6 cube, and we depthwise max across 3 to produce a 2x2x2\n # output. Each node has contiguous values, so the depthwise max\n # should be multiples of 3.0.\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 6],\n ksize=[1, 1, 1, 3],\n strides=[1, 1, 1, 3],\n padding=\"SAME\",\n expected=[3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testMaxPoolKernelSmallerThanStrideValid(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 7, 7, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 3, 3, 1],\n padding=\"VALID\",\n expected=[9, 12, 30, 33],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolKernelSmallerThanStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 7, 7, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 3, 3, 1],\n padding=\"VALID\",\n expected=[5, 8, 26, 29],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2) +\n GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testKernelSmallerThanStrideSame1_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 1, 1, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[1, 3, 7, 9],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2) +\n GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testKernelSmallerThanStrideSame2_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 1, 1, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[1, 3, 9, 11],\n **kwargs)", " def _testDepthwiseMaxPoolInvalidConfig(self,\n in_size,\n ksize,\n strides,\n error_msg,\n use_gpu=False):\n with self.cached_session(use_gpu=use_gpu):\n t = constant_op.constant(1.0, shape=in_size)\n with self.assertRaisesRegex(errors_impl.UnimplementedError, error_msg):\n t = nn_ops.max_pool(\n t, ksize=ksize, strides=strides, padding=\"SAME\").eval()", " @test_util.disable_xla(\"b/123338077\") # Passes with XLA\n def testDepthwiseMaxPoolInvalidConfigs(self):\n self._testDepthwiseMaxPoolInvalidConfig(\n [1, 2, 2, 4], [1, 2, 2, 2], [1, 1, 1, 2],\n \"exactly one of pooling across depth\")\n self._testDepthwiseMaxPoolInvalidConfig(\n [1, 2, 2, 4], [1, 1, 1, 2], [1, 1, 1, 1],\n \"depth window to equal the depth stride\")\n self._testDepthwiseMaxPoolInvalidConfig([1, 2, 2, 4], [1, 1, 1, 3],\n [1, 1, 1, 3], \"evenly divide\")\n if test.is_gpu_available():\n with self.session():\n t = variables.Variable(np.ones([1, 2, 2, 4]))\n self.evaluate(variables.global_variables_initializer())\n with self.assertRaisesOpError(\"for CPU devices\"):\n nn_ops.max_pool(\n t, ksize=[1, 1, 1, 2], strides=[1, 1, 1, 2],\n padding=\"SAME\").eval()", " # The following are tests that verify that the CPU and GPU implementations\n # produce the same results.\n def _CompareMaxPoolingFwd(self, input_shape, ksize, strides, padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n tensor_input = np.random.rand(*input_shape).astype(dtype)\n with self.cached_session():\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op, _ = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n gpu_val = self.evaluate(out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n cpu_val = self.evaluate(out_op)\n self.assertAllCloseAccordingToType(cpu_val, gpu_val)", " def _CompareMaxPoolingBk(self, input_shape, output_shape, ksize, strides,\n padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n # Generate numbers in a narrow range, so that there are many duplicates\n # in the input.\n tensor_input = np.random.random_integers(0, 3, input_shape).astype(dtype)\n tensor_output = np.random.rand(*output_shape).astype(dtype)\n with self.cached_session():\n t = constant_op.constant(tensor_input, shape=input_shape)\n _, argmax_op = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n argmax = self.evaluate(argmax_op)\n grad_in = constant_op.constant(tensor_output, shape=output_shape)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(t, grad_in, argmax, ksize,\n strides, padding)\n gpu_val = self.evaluate(out_op)\n self.assertShapeEqual(gpu_val, out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n orig_out = self.evaluate(out_op)\n grad_in = constant_op.constant(tensor_output, shape=output_shape)\n out_op = gen_nn_ops.max_pool_grad(t, orig_out, grad_in, ksize, strides,\n padding)\n cpu_val = self.evaluate(out_op)\n self.assertShapeEqual(cpu_val, out_op)\n # The CPU version accumulates its gradient on fp16, so it's less\n # accurate than the GPU version that does the accumulation on fp32\n self.assertAllCloseAccordingToType(\n cpu_val, gpu_val, half_rtol=0.01, half_atol=0.01)", " def _CompareMaxPoolingGradBk(self, input_shape, output_shape, ksize, strides,\n padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n # Generate numbers in a narrow range, so that there are many duplicates\n # in the input.\n tensor_input = np.random.random_integers(0, 3, input_shape).astype(dtype)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n _, argmax_op = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n argmax = self.evaluate(argmax_op)\n grad_in = constant_op.constant(tensor_input, shape=input_shape)\n out_op = gen_nn_ops.max_pool_grad_grad_with_argmax(\n t, grad_in, argmax, ksize, strides, padding)\n gpu_val = self.evaluate(out_op)\n self.assertShapeEqual(gpu_val, out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n orig_out = self.evaluate(out_op)\n grad_in = constant_op.constant(tensor_input, shape=input_shape)\n out_op = gen_nn_ops.max_pool_grad_grad(t, orig_out, grad_in, ksize,\n strides, padding)\n cpu_val = self.evaluate(out_op)\n self.assertShapeEqual(cpu_val, out_op)\n # The CPU version accumulates its gradient on fp16, so it's less\n # accurate than the GPU version that does the accumulation on fp32\n self.assertAllCloseAccordingToType(\n cpu_val, gpu_val, half_rtol=0.01, half_atol=0.01)", " def testMaxPoolingWithArgmax(self):\n tensor_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\", \"Targmax\"])\n configs = [\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int64),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int64),\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int32),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int32),\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int64),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int64),\n ]", " for config in configs:\n with GetDeviceScope(self, use_gpu=config.use_gpu):\n t = constant_op.constant(tensor_input, shape=[2, 3, 3, 1])\n out_op, argmax_op = nn_ops.max_pool_with_argmax(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n Targmax=config.Targmax,\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out, argmax = self.evaluate([out_op, argmax_op])\n self.assertShapeEqual(out, out_op)\n self.assertShapeEqual(argmax, argmax_op)\n self.assertAllClose(out.ravel(),\n [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])\n self.assertAllEqual(argmax.ravel(), config.argmax)", " def testMaxPoolingGradWithArgmax(self):\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\"])\n configs = [\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17]),\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17])\n ]", " for config in configs:\n with GetDeviceScope(self, config.use_gpu):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n config.argmax, shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out = self.evaluate(out_op).flatten()\n self.assertAllClose(out, [\n 11.0, 12.0, 0.0, 13.0, 0.0, 14.0, 0.0, 0.0, 0.0, 21.0, 0.0, 22.0,\n 0.0, 0.0, 0.0, 23.0, 0.0, 24.0\n ])", " def testMaxPoolingGradThrowDeterminismError(self):\n if test.is_gpu_available(cuda_only=True):\n try:\n config_exec.enable_op_determinism()\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " with GetDeviceScope(self, True):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n [0, 1, 3, 5, 0, 2, 6, 8], shape=[2, 2, 2, 1], dtype=dtypes.int64)\n with self.assertRaisesRegexp(\n errors_impl.UnimplementedError, \"Determinism is not yet supported \"\n \"for MaxPoolGradWithArgmax.\"):\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=False)\n self.evaluate(out_op)\n finally:\n config_exec.disable_op_determinism()\n else:\n try:\n config_exec.enable_op_determinism()\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " with GetDeviceScope(self, False):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n [0, 1, 3, 5, 0, 2, 6, 8], shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=False)\n self.evaluate(out_op)\n finally:\n config_exec.disable_op_determinism()", " def testMaxPoolingGradGradWithArgmax(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [\n 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 21.0, 22.0, 23.0,\n 24.0, 25.0, 26.0, 27.0, 28.0, 29.0\n ]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\"])\n configs = [\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17])\n ]", " for config in configs:\n with GetDeviceScope(self, config.use_gpu):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 3, 3, 1])\n argmax_t = constant_op.constant(\n config.argmax, shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out = self.evaluate(out_op).flatten()\n self.assertAllClose(out,\n [11.0, 12.0, 14.0, 16.0, 21.0, 23.0, 27.0, 29.0])", " def _ConstructAndTestGradient(self,\n pool_func,\n input_sizes,\n output_sizes,\n window_rows,\n window_cols,\n row_stride,\n col_stride,\n padding,\n data_format,\n use_gpu,\n x_init_value=None):\n \"\"\"Verifies the gradients of the max or avg pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n output_sizes: Output tensor dimensions.\n window_rows: kernel size in row dim\n window_cols: kernel size in col dim\n row_stride: Row Stride.\n col_stride: Col Stride.\n padding: Padding type.\n data_format: Data format.\n use_gpu: whether we are running on GPU\n x_init_value: Values to be passed to the gradient checker.\n \"\"\"\n assert input_sizes[0] == output_sizes[0]\n assert input_sizes[3] == output_sizes[3]\n total_size = 1\n for s in input_sizes:\n total_size *= s\n # Initializes the input tensor with array containing incrementing\n # numbers from 1.\n x = [f * 1.0 for f in range(1, total_size + 1)]\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = constant_op.constant(x, shape=input_sizes, name=\"input\")\n if pool_func == nn_ops.avg_pool:\n func_name = \"avg_pool\"\n err_tolerance = 1e-4\n else:\n if x_init_value is None:\n x_init_value = np.asfarray(\n np.arange(1, total_size + 1),\n dtype=np.float32).reshape(input_sizes)\n func_name = \"max_pool\"\n err_tolerance = 1e-3\n if data_format == \"NCHW\":\n ksize = [1, 1, window_rows, window_cols]\n strides = [1, 1, row_stride, col_stride]\n if isinstance(padding, list):\n padding = test_util.NHWCToNCHW(padding)\n t = test_util.NHWCToNCHW(input_tensor)\n else:\n ksize = [1, window_rows, window_cols, 1]\n strides = [1, row_stride, col_stride, 1]\n t = input_tensor\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=func_name)\n if data_format == \"NCHW\":\n t = test_util.NCHWToNHWC(t)", " err = gradient_checker.compute_gradient_error(\n input_tensor,\n input_sizes,\n t,\n output_sizes,\n x_init_value=x_init_value,\n delta=1e-2)\n tf_logging.info(\"%s gradient error = %.4f\" % (func_name, err))\n self.assertLess(err, err_tolerance)", " def _ConstructAndTestSecondGradient(self,\n pool_func,\n input_sizes,\n output_sizes,\n window_rows,\n window_cols,\n row_stride,\n col_stride,\n padding,\n data_format,\n use_gpu,\n x_init_value=None):\n \"\"\"Verifies the second-order gradients of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n output_sizes: Output tensor dimensions.\n window_rows: kernel size in row dim\n window_cols: kernel size in col dim\n row_stride: Row Stride.\n col_stride: Col Stride.\n padding: Padding type.\n data_format: Data format.\n use_gpu: whether we are running on GPU\n x_init_value: Values to be passed to the gradient checker.\n \"\"\"\n assert input_sizes[0] == output_sizes[0]\n assert input_sizes[3] == output_sizes[3]\n total_size = 1\n for s in input_sizes:\n total_size *= s\n # Initializes the input tensor with array containing incrementing\n # numbers from 1.\n x = [f * 1.0 for f in range(1, total_size + 1)]\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = constant_op.constant(x, shape=input_sizes, name=\"input\")\n if pool_func == nn_ops.avg_pool:\n func_name = \"avg_pool\"\n err_tolerance = 1e-3\n else:\n if x_init_value is None:\n x_init_value = np.asfarray(\n np.arange(1, total_size + 1),\n dtype=np.float32).reshape(input_sizes)\n func_name = \"max_pool\"\n err_tolerance = 1e-2\n if data_format == \"NCHW\":\n ksize = [1, 1, window_rows, window_rows]\n strides = [1, 1, row_stride, col_stride]\n t = test_util.NHWCToNCHW(input_tensor)\n else:\n ksize = [1, window_rows, window_rows, 1]\n strides = [1, row_stride, col_stride, 1]\n t = input_tensor\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=func_name)\n if data_format == \"NCHW\":\n t = test_util.NHWCToNCHW(t)", " t_g = gradients_impl.gradients(t**2, input_tensor)[0]\n err = gradient_checker.compute_gradient_error(\n input_tensor,\n input_sizes,\n t_g,\n input_sizes,\n x_init_value=x_init_value,\n delta=1e-2)\n tf_logging.info(\"%s second-order gradient error = %.4f\" % (func_name, err))\n self.assertLess(err, err_tolerance)", " def _testMaxPoolGradValidPadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_1_6(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 6, 6, 3],\n output_sizes=[2, 5, 5, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_1_7(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 7, 7, 3],\n output_sizes=[2, 6, 6, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding1_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 2, 2, 1],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding1_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding2_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding3_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPadding_1(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [1, 1], [1, 1], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPadding_2(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 6, 8, 1],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [2, 3], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingLeftGreater(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 6, 8, 1],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [3, 2], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingBatchChannel(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[4, 7, 7, 3],\n output_sizes=[4, 6, 8, 3],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [3, 2], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingStrides(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 4, 3, 1],\n window_rows=3,\n window_cols=3,\n row_stride=2,\n col_stride=3,\n padding=[[0, 0], [1, 1], [1, 1], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testMaxPoolGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testMaxPoolGradValidPadding1_1(data_format, use_gpu)\n self._testMaxPoolGradValidPadding1_2(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_1_6(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_1_7(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding1_1(data_format, use_gpu)\n self._testMaxPoolGradSamePadding1_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding2_1(data_format, use_gpu)\n self._testMaxPoolGradSamePadding2_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding3_1(data_format, use_gpu)\n self._testMaxPoolExplicitPadding_1(data_format, use_gpu)\n self._testMaxPoolExplicitPadding_2(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingStrides(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingLeftGreater(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingBatchChannel(data_format, use_gpu)", " def _MaxPoolGrad(self, orig_input, orig_output, grad, window_rows,\n window_cols, row_stride, col_stride, padding, v2):\n \"\"\"Max Pooling Gradient.", " Args:\n orig_input: A float Tensor. The original input tensor.\n orig_output: A float Tensor. The original output tensor.\n grad: A float Tensor.\n The 4D (batch x rows x cols x depth) output backprop.\n window_rows: integer. Kernel size along rows dimension.\n window_cols: integer. Kernel size along cols dimension.\n row_stride: integer. Stride along rows dimension\n col_stride: integer. Stride along cols dimension\n padding: PoolingOpDef.Padding. Padding type.", " Returns:\n A Tensor.\n \"\"\"\n pool_func = gen_nn_ops.max_pool_grad_v2 if v2 else gen_nn_ops.max_pool_grad\n if v2:\n return pool_func(orig_input, orig_output, grad,\n [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)\n else:\n padding, explicit_paddings = nn_ops.convert_padding(padding)\n return pool_func(orig_input, orig_output, grad,\n [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding,\n explicit_paddings)", " def _testMaxPoolGradDirect(self, input_data, output_backprop,\n expected_input_backprop, input_sizes, output_sizes,\n window_rows, window_cols, row_stride, col_stride,\n padding, use_gpu, v2):\n pool_func = gen_nn_ops.max_pool_v2 if v2 else nn_ops.max_pool\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = variables.Variable(\n np.array(input_data, dtype=np.float32).reshape(input_sizes))\n self.evaluate(variables.global_variables_initializer())\n output_tensor = pool_func(input_tensor, [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)\n output_backprop_tensor = constant_op.constant(\n output_backprop, shape=output_sizes)", " input_backprop_tensor = self._MaxPoolGrad(\n input_tensor, output_tensor, output_backprop_tensor, window_rows,\n window_cols, row_stride, col_stride, padding, v2)", " actual_input_backprop = self.evaluate(input_backprop_tensor)\n self.assertShapeEqual(actual_input_backprop, input_backprop_tensor)\n actual_input_backprop = actual_input_backprop.flatten()\n actual_input_backprop = self._GetNdArray(actual_input_backprop)", " actual_output = self.evaluate(output_tensor).flatten()\n actual_output = self._GetNdArray(actual_output)", " self.assertAllClose(\n expected_input_backprop, actual_input_backprop, rtol=1e-6, atol=1e-6)", " def _testMaxPoolGradDirect1_1(self):\n input_data = [\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 12.0, 13.0, 0.0, 15.0, 16.0, 17.0, 0.0, 19.0, 20.0, 21.0, 0.0,\n 0.0, 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradDirect1_2(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 17.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradDirect1_3(self):\n input_data = [\n 1.0,\n 0.0,\n 1.0,\n 0.0,\n 0.0,\n 1.0,\n 0.0,\n 1.0,\n 1.0,\n 0.0,\n 1.0,\n 0.0,\n 0.0,\n 1.0,\n 0.0,\n 1.0,\n ]\n output_backprop = [\n 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0,\n 23.0, 24.0, 25.0, 26.0\n ]\n expected_input_backprop = [\n 54,\n 0.0,\n 62,\n 0.0,\n 0.0,\n 60,\n 0.0,\n 22.0,\n 47,\n 0.0,\n 51,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 4, 4, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradZeroExplicitPadding(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 17.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 0], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_1(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,\n 20.0, 21.0, 22.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 49.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 22.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 4, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_2(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 54.0, 0.0, 30.0, 0.0, 0.0, 0.0, 0.0, 0.0, 39.0, 0.0, 21.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=3,\n window_cols=3,\n row_stride=2,\n col_stride=2,\n padding=[[0, 0], [2, 1], [2, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_3(self):\n input_data = [\n -1.0, -5.0, -1.0, -5.0, -5.0, -1.0, -5.0, -1.0, -1.0, -5.0, -1.0, -5.0,\n -5.0, -1.0, -5.0, -1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,\n 20.0, 21.0, 22.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 49.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 22.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 4, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " @test_util.no_xla_auto_jit(\"b/123923733\") # NaNs handled differently\n def _testMaxPoolGradDirectWithNans2_1(self):\n input_data = [float(\"nan\")] * 16\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n # Test the CPU implementation, which propagates diffs in case of NaN\n expected_input_backprop_tf_cpu = [\n 11.0, 12.0, 13.0, 0.0, 15.0, 16.0, 17.0, 0.0, 19.0, 20.0, 21.0, 0.0,\n 0.0, 0.0, 0.0, 0.0\n ]\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_tf_cpu,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=False,\n v2=v2)", " if not test.is_gpu_available():\n return", " # The functionality associated with TF_ENABLE_NANPROP is currently\n # not supported on the ROCm platform, so skip this part of the test\n # NANs in input lead to non-deterministic results, and hence skipping\n # the remaining tests altogether on the ROCm platform\n if test.is_built_with_rocm():\n return", " # Test the GPU implementation that uses cudnn for now.\n saved_nanprop = os.environ.get(\"TF_ENABLE_MAXPOOL_NANPROP\")\n # Do not propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"0\"\n expected_input_backprop_cudnn = [\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0\n ]", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " # Propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"1\"\n expected_input_backprop_cudnn = expected_input_backprop_tf_cpu", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " if saved_nanprop:\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = saved_nanprop\n else:\n del os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"]", " @test_util.no_xla_auto_jit(\"b/123923733\") # NaNs handled differently\n def _testMaxPoolGradDirectWithNans2_2(self):\n input_data = [float(\"nan\")] * 16\n output_backprop = [\n float(\"nan\"), 12.0, 13.0, 15.0,\n float(\"nan\"), 17.0, 19.0, 20.0,\n float(\"nan\")\n ]\n # Test the CPU implementation, which propagates diffs in case of NaN\n expected_input_backprop_tf_cpu = [\n float(\"nan\"), 12.0, 13.0, 0.0, 15.0,\n float(\"nan\"), 17.0, 0.0, 19.0, 20.0,\n float(\"nan\"), 0.0, 0.0, 0.0, 0.0, 0.0\n ]\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_tf_cpu,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=False,\n v2=v2)", " if not test.is_gpu_available():\n return", " # The functionality associated with TF_ENABLE_NANPROP is currently\n # not supported on the ROCm platform, so skip this part of the test\n # NANs in input lead to non-deterministic results, and hence skipping\n # the remaining tests altogether on the ROCm platform\n if test.is_built_with_rocm():\n return", " # Test the GPU implementation that uses cudnn for now.\n saved_nanprop = os.environ.get(\"TF_ENABLE_MAXPOOL_NANPROP\")\n # Do not propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"0\"\n expected_input_backprop_cudnn = [\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0\n ]", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " # Propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"1\"\n expected_input_backprop_cudnn = expected_input_backprop_tf_cpu", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " if saved_nanprop:\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = saved_nanprop\n else:\n del os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"]", " @test_util.run_deprecated_v1\n def testMaxPoolGradDirect(self):\n self._testMaxPoolGradDirect1_1()\n self._testMaxPoolGradDirect1_2()\n self._testMaxPoolGradDirect1_3()\n self._testMaxPoolGradDirectWithNans2_1()\n self._testMaxPoolGradDirectWithNans2_2()\n self._testMaxPoolGradZeroExplicitPadding()\n self._testMaxPoolGradExplicitPadding_1()\n self._testMaxPoolGradExplicitPadding_2()\n self._testMaxPoolGradExplicitPadding_3()", " def _testMaxPoolGradGradValidPadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_1_6(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 6, 6, 3],\n output_sizes=[2, 5, 5, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_1_7(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 7, 7, 3],\n output_sizes=[2, 6, 6, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding2_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding3_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testMaxPoolGradGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testMaxPoolGradGradValidPadding1_1(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_1_6(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_1_7(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_2(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding1_1(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding2_1(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding2_2(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding3_1(data_format, use_gpu)", " def _MaxPoolGradGrad(self, orig_input, orig_output, grad, window_rows,\n window_cols, row_stride, col_stride, padding):\n \"\"\"Max Pooling Second-Order Gradient.", " Args:\n orig_input: A float Tensor. The original input tensor.\n orig_output: A float Tensor. The original output tensor.\n grad: A float Tensor.\n The 4D (batch x out_rows x out_cols x depth) output backprop.\n window_rows: integer. Kernel size along rows dimension.\n window_cols: integer. Kernel size along cols dimension.\n row_stride: integer. Stride along rows dimension\n col_stride: integer. Stride along cols dimension\n padding: PoolingOpDef.Padding. Padding type.", " Returns:\n A Tensor.\n \"\"\"\n return gen_nn_ops.max_pool_grad_grad(\n orig_input, orig_output, grad, [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)", " @test_util.run_deprecated_v1\n def testAvgPoolGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testAvgPoolGradValidPadding1_1(data_format, use_gpu)\n self._testAvgPoolGradValidPadding1_2(data_format, use_gpu)\n self._testAvgPoolGradValidPadding2_1(data_format, use_gpu)\n self._testAvgPoolGradValidPadding2_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding1_1(data_format, use_gpu)\n self._testAvgPoolGradSamePadding1_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding2_1(data_format, use_gpu)\n self._testAvgPoolGradSamePadding2_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding3_1(data_format, use_gpu)", " def _testAvgPoolGradValidPadding1_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 3, 3, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding1_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 2, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding2_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 2, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding2_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding1_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding1_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding2_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding2_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding3_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testShapeFunctionEdgeCases(self):\n # All shapes unknown.\n for pool_func in [nn_ops.max_pool, nn_ops.avg_pool]:\n p = pool_func(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")\n self.assertEqual([None, None, None, None], p.get_shape().as_list())\n p, am = nn_ops.max_pool_with_argmax(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")\n self.assertEqual([None, None, None, None], p.get_shape().as_list())\n self.assertEqual([None, None, None, None], am.get_shape().as_list())", " # Incorrect input shape.\n for pool_func in [\n nn_ops.max_pool, nn_ops.avg_pool, nn_ops.max_pool_with_argmax\n ]:\n with self.assertRaises(ValueError):\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[1, 3]),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")", " @test_util.run_deprecated_v1\n @test_util.disable_xla(\"b/123337890\") # Error messages differ\n def testOpEdgeCases(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n pool_funcs = [nn_ops.max_pool, nn_ops.avg_pool]\n if test.is_gpu_available():\n pool_funcs.append(nn_ops.max_pool_with_argmax)\n for pool_func in pool_funcs:\n if pool_func != nn_ops.max_pool:\n # Illegal strides.\n with self.assertRaisesRegex(\n errors_impl.UnimplementedError,\n \"Pooling is not yet supported on the batch\"):\n sess.run(\n pool_func(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[2, 1, 1, 1],\n padding=\"SAME\"))", " # Filter too large.\n with self.assertRaisesRegex(ValueError, \"Negative dimension size\"):\n sess.run(\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[32, 20, 20, 3]),\n ksize=[1, 20, 21, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\"))\n with self.assertRaisesRegex(ValueError, \"Negative dimension size\"):\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[32, 20, 20, 3]),\n ksize=[1, 21, 20, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\")", " @test_util.run_deprecated_v1\n def testEdgeCasesRaiseErrors(self):\n with self.assertRaisesRegexp(\n ValueError, \"NCHW_VECT_C.*is not supported with \"\n \"explicit padding|XLA does not support pooling ops with explicit \"\n \"padding\"):\n nn_ops.max_pool(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1]),\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 1], [0, 1], [0, 0]],\n data_format=\"NCHW_VECT_C\")\n with self.assertRaisesRegexp(\n ValueError, \"Explicit padding is not supported with an input \"\n \"tensor of rank 5\"):\n nn_ops.max_pool_v2(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1, 1]),\n ksize=[1, 2, 2, 1, 1],\n strides=[1, 2, 2, 1, 1],\n padding=[[0, 0], [0, 1], [0, 1], [0, 0]],\n data_format=\"NCHW\")\n with self.assertRaisesRegexp(\n ValueError, \"Attr 'padding' of 'MaxPoolV2' Op passed \"\n \"string 'EXPLICIT'\"):\n gen_nn_ops.max_pool_v2(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1, 1]),\n ksize=[1, 2, 2, 1, 1],\n strides=[1, 2, 2, 1, 1],\n padding=\"EXPLICIT\",\n data_format=\"NHWC\")", " @test_util.run_deprecated_v1\n def testEdgeCasesExcessPadding(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n (errors_impl.UnimplementedError, errors_impl.InvalidArgumentError),\n \"Right padding 2 needs to be smaller than the window size 2|\"\n \"XLA does not support pooling ops with explicit padding\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[0, 0, 0, 1, 0, 2, 0, 0],\n data_format=\"NHWC\"))", " @test_util.run_deprecated_v1\n def testNegativePadding(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n ValueError, \"All elements of explicit_paddings must be \"\n \"nonnegative for\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[0, 0, -1, -1, -1, -1, 0, 0],\n data_format=\"NHWC\"))", " @test_util.run_deprecated_v1\n def testExplicitPaddingBatch(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n ValueError, \"Nonzero explicit padding in the batch or depth \"\n \"dimensions is not supported\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[1, 1, 1, 1, 1, 1, 0, 0],\n data_format=\"NHWC\"))", " @test_util.disable_xla(\n \"b/205634417\") # XLA is not throwing shape errors for multiple *Grad ops.\n def testMaxPoolGradEagerShapeErrors(self):\n with context.eager_mode():\n orig_in = array_ops.ones((1, 1, 1, 1))", " # Test invalid orig_out shape\n orig_out = array_ops.ones((1, 1, 1, 2))\n grad = array_ops.ones((1, 1, 1, 1))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " # Test invalid grad shape\n orig_out = array_ops.ones((1, 1, 1, 1))\n grad = array_ops.ones((1, 1, 1, 2))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " def testMaxPoolGradWithArgmaxEagerShapeErrors(self):\n with context.eager_mode():\n inp = array_ops.ones((1, 1, 1, 1))", " # Test invalid grad shape\n grad = array_ops.ones((1, 1, 1, 2))\n argmax = array_ops.zeros((1, 1, 1, 1), dtype=dtypes.int64)\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n # max_pool_grad_grad_with_argmax is only implemented for GPUs\n if test.is_gpu_available():\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " # Test invalid argmax shape\n grad = array_ops.ones((1, 1, 1, 1))\n argmax = array_ops.ones((1, 1, 1, 2), dtype=dtypes.int64)\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected argmax shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n # max_pool_grad_grad_with_argmax is only implemented for GPUs\n if test.is_gpu_available():\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected argmax shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n", "", "\ndef GetMaxPoolFwdTest(input_size, filter_size, strides, padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingFwd(input_size, filter_size, strides, padding)", " return Test", "\ndef GetMaxPoolGradTest(input_size, filter_size, output_size, strides, padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingBk(input_size, output_size, filter_size, strides,\n padding)", " return Test", "\ndef GetMaxPoolGradGradTest(input_size, filter_size, output_size, strides,\n padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingGradBk(input_size, output_size, filter_size, strides,\n padding)", " return Test", "\nif __name__ == \"__main__\":\n for (name_, input_size_, filter_size_, output_size_, stride_,\n padding_) in GetShrunkInceptionMaxPoolShapes():\n setattr(PoolingTest, \"testMaxPoolFwd_\" + name_,\n GetMaxPoolFwdTest(input_size_, filter_size_, stride_, padding_))\n setattr(PoolingTest, \"testMaxPoolGrad_\" + name_,\n GetMaxPoolGradTest(input_size_, filter_size_, output_size_, stride_,\n padding_))\n setattr(PoolingTest, \"testMaxPoolGradGrad_\" + name_,\n GetMaxPoolGradGradTest(input_size_, filter_size_, output_size_,\n stride_, padding_))\n test.main()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [547, 2472], "buggy_code_start_loc": [301, 2472], "filenames": ["tensorflow/core/kernels/avgpooling_op.cc", "tensorflow/python/kernel_tests/nn_ops/pooling_ops_test.py"], "fixing_code_end_loc": [547, 2489], "fixing_code_start_loc": [301, 2473], "message": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C4DFBF2D-5283-42F6-8800-D653BFA5CE82", "versionEndExcluding": "2.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F9D273D-02DC-441E-AA91-EAC8DEAA4B44", "versionEndExcluding": "2.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FE4F8A81-6CC2-4F7F-9602-C170FDD926E7", "versionEndExcluding": "2.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc0:*:*:*:*:*:*", "matchCriteriaId": "1DBFBCE2-0A01-4575-BE45-6775ABFB8B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc1:*:*:*:*:*:*", "matchCriteriaId": "89806CF9-E423-4CA6-A01A-8175C260CB24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc2:*:*:*:*:*:*", "matchCriteriaId": "F2B80690-A257-4E16-BD27-9AE045BC56ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc3:*:*:*:*:*:*", "matchCriteriaId": "F335F9A4-5AB8-4E53-BC18-E01F7C653E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto para el aprendizaje autom\u00e1tico. La funci\u00f3n \"AvgPoolOp\" toma un argumento \"ksize\" que debe ser positivo pero no se comprueba. Un \"ksize\" negativo puede desencadenar un fallo de \"CHECK\" y bloquear el programa. Hemos parcheado el problema en el commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.10.0. Tambi\u00e9n seleccionaremos este compromiso en TensorFlow versi\u00f3n 2.9.1, TensorFlow versi\u00f3n 2.8.1, y TensorFlow versi\u00f3n 2.7.2, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango admitido. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-35941", "lastModified": "2022-09-20T18:07:25.377", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-16T20:15:10.377", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/avgpooling_op.cc#L56-L98"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mgmh-g2v6-mqw5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-617"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, "type": "CWE-617"}
109
Determine whether the {function_name} code is vulnerable or not.
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Functional tests for pooling operations.\"\"\"", "import collections\nimport os", "from absl.testing import parameterized\nimport numpy as np", "from tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nimport tensorflow.python.framework.config as config_exec\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import variables\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging", "\ndef GetDeviceScope(self, use_gpu=False):\n if context.executing_eagerly():\n if use_gpu and test.is_gpu_available():\n return ops.device(\"GPU:0\")\n return ops.device(\"CPU:0\")\n else:\n return self.session(use_gpu=use_gpu)", "\n# TODO(jlebar): Convert the rest of this file to parameters.parameterized().\n# Then remove GetTestConfigs() and rename GetTestConfigsDicts().\ndef GetTestConfigsDicts(v1_fn,\n v2_fn=None,\n one_dimensional=False,\n allow_gpu=True):\n # (data_format, use_gpu) tuple\n if one_dimensional:\n configs0 = [\n (\"NWC\", False),\n (\"NWC\", True),\n (\"NCW\", True),\n ]\n else:\n configs0 = [\n (\"NHWC\", False),\n (\"NHWC\", True),\n (\"NCHW\", True),\n ]\n # NCHW_VECT_C only supported for max_pool.\n if (v1_fn == nn_ops.max_pool or v1_fn == nn_ops.max_pool1d or\n v2_fn == nn_ops.max_pool_v2 or v2_fn == gen_nn_ops.max_pool_v2):\n configs0.append((\"NCHW_VECT_C\", True))", " # (data_format, use_gpu, data_type) tuple\n configs1 = []\n for data_format, use_gpu in configs0:\n configs1.append((data_format, use_gpu, dtypes.float32))", " # In our test, VECT_C always uses float32. (It gets converted to int8 in\n # the test runner.)\n if data_format == \"NCHW_VECT_C\":\n continue", " configs1 += [(data_format, use_gpu, dtypes.float16),\n (data_format, use_gpu, dtypes.float64)]", " # Convert from tuple to dict and add v1/v2 versions.\n ret = []\n for data_format, use_gpu, data_type in configs1:\n ret.append({\n \"pool_func\": v1_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": False\n })\n if v2_fn:\n ret.append({\n \"pool_func\": v2_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": False\n })\n ret.append({\n \"pool_func\": v2_fn,\n \"data_format\": data_format,\n \"data_type\": data_type,\n \"use_gpu\": use_gpu,\n \"v2\": True\n })", " # Filter out GPU configs if necessary.\n if not allow_gpu:\n ret = [c for c in ret if not c[\"use_gpu\"]]", " return ret", "\ndef GetTestConfigs(include_nchw_vect_c=False, one_dimensional=False):\n \"\"\"Get all the valid tests configs to run.", " Args:\n include_nchw_vect_c: Whether to include NCHW_VECT_C in the test configs.\n one_dimensional: If it's a 1D test", " Returns:\n all the valid test configs as tuples of data_format and use_gpu.\n \"\"\"\n if one_dimensional:\n test_configs = [(\"NWC\", False), (\"NWC\", True)]\n if test.is_gpu_available(cuda_only=True):\n test_configs += [(\"NCW\", True)]\n return test_configs\n test_configs = [(\"NHWC\", False), (\"NHWC\", True)]\n if not test.is_gpu_available(cuda_only=True):\n tf_logging.info(\"NCHW and NCHW_VECT_C tests skipped because not run with \"\n \"--config=cuda or no GPUs available.\")\n return test_configs\n # \"NCHW\" format is currently supported exclusively on CUDA GPUs.\n test_configs += [(\"NCHW\", True)]\n if include_nchw_vect_c:\n if test.is_gpu_available(\n cuda_only=True, min_cuda_compute_capability=(6, 1)):\n test_configs += [(\"NCHW_VECT_C\", True)]\n else:\n tf_logging.info(\"NCHW_VECT_C test skipped because no GPUs with \"\n \"compute capability >= 6.1 are available.\")", " return test_configs", "\ndef GetShrunkInceptionMaxPoolShapes(shrink=30):\n \"\"\"Iterator for some of the max pool ops in the Inception 2015 model.", " Args:\n shrink: Factor to shrink depth relative to Inception.", " Yields:\n Tuple (name, input_size, filter_size, out_size, strides, padding)\n \"\"\"\n names = [\"maxpool2\", \"maxpool3\", \"maxpool4\", \"maxpool5\"]\n input_sizes = [[32, 71, 71, 192], [32, 35, 35, 288], [32, 17, 17, 1248],\n [32, 8, 8, 2048]]\n filter_sizes = [[1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1], [1, 3, 3, 1]]\n output_sizes = [[32, 35, 35, 192], [32, 17, 17, 288], [32, 8, 8, 1248],\n [32, 8, 8, 2048]]\n strides = [[1, 2, 2, 1], [1, 2, 2, 1], [1, 2, 2, 1], [1, 1, 1, 1]]\n # Shrink each depth value\n for i in input_sizes:\n i[3] //= shrink\n for o in output_sizes:\n o[3] //= shrink\n paddings = [\"VALID\", \"VALID\", \"VALID\", \"SAME\"]\n for n, i, f, o, s, p in zip(names, input_sizes, filter_sizes, output_sizes,\n strides, paddings):\n yield n, i, f, o, s, p", "\n@test_util.with_eager_op_as_function\nclass PoolingTest(test.TestCase, parameterized.TestCase):", " def _isMaxPool(self, func):\n return func in (nn_ops.max_pool, nn_ops.max_pool_v2)", " def _VerifyOneType(self, pool_func, input_sizes, ksize, strides, padding,\n data_format, data_type, expected, use_gpu, v2,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n data_format: The data format we use to run the pooling operation.\n data_type: The data type to use to run the pooling operation.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n use_negative_input: If the input values should be negative.\n \"\"\"\n # Check that this test is compatible with the hardware we have. (Really\n # this should be done in GetTestConfigsDicts(), but when that runs, we\n # haven't initialized enough of TF to know what our hardware is!)\n if use_gpu and not test.is_gpu_available():\n self.skipTest(\"No GPU is available.\")\n if use_gpu and data_type == dtypes.float64 and test.is_built_with_rocm():\n self.skipTest(\"ROCm pooling ops don't support float64.\")\n if use_gpu and data_format == \"NCHW_VECT_C\" and not test.is_gpu_available(\n cuda_only=True, min_cuda_compute_capability=(6, 1)):\n self.skipTest(\"NCHW_VECT_C requires sm61+.\")", " if v2 and data_format != \"NHWC\":\n self.skipTest(\"v2 not supported for %s\" % data_format)\n if v2 and not isinstance(padding, str):\n self.skipTest(\"non-constant ksize/strides requires nonexplicit padding\")\n if data_format == \"NCHW_VECT_C\":\n if data_type != dtypes.float32:\n self.skipTest(\"quantization to qint8 not implemented for %r\" %\n data_type)\n if input_sizes[-1] % 4 != 0:\n self.skipTest(\"Skipping test for depth %d\" % input_sizes[-1])", " total_size = 1\n for s in input_sizes:\n total_size *= s\n tf_logging.info(\"Running %s test. %r %r %d %r %r %r %s\", data_format, v2,\n input_sizes, total_size, pool_func, ksize, strides,\n data_type)\n # Initializes the input tensor with array containing incrementing\n # numbers from 1, wrapping round to -127 after 127 to support int8.\n y = -1 if use_negative_input else 1\n x = [(((f + 128) % 255) - 127)*y for f in range(total_size)]\n with self.cached_session(use_gpu=use_gpu):\n t = constant_op.constant(x, shape=input_sizes, dtype=data_type)\n if data_format in (\"NCHW\", \"NCHW_VECT_C\", \"NCW\"):\n if data_format == \"NCHW_VECT_C\":\n t = test_util.NHWCToNCHW_VECT_C(t)\n t, _, _ = gen_array_ops.quantize_v2(t, -128.0, 127.0, dtypes.qint8)\n else:\n t = test_util.NHWCToNCHW(t)\n ksize = test_util.NHWCToNCHW(ksize)\n strides = test_util.NHWCToNCHW(strides)\n if isinstance(padding, list):\n padding = test_util.NHWCToNCHW(padding)\n ksize_placeholder = array_ops.placeholder(dtypes.int32, shape=[4])\n strides_placeholder = array_ops.placeholder(dtypes.int32, shape=[4])\n if v2:\n t = pool_func(\n t,\n ksize=ksize_placeholder,\n strides=strides_placeholder,\n padding=padding,\n data_format=data_format)\n else:\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format)\n if data_format == \"NCHW_VECT_C\":\n t = gen_array_ops.dequantize(t, -128, 127)\n t = test_util.NCHW_VECT_CToNHWC(t)\n elif data_format == \"NCHW\":\n t = test_util.NCHWToNHWC(t)\n if v2:\n actual = t.eval(feed_dict={\n ksize_placeholder: ksize,\n strides_placeholder: strides\n })\n else:\n actual = self.evaluate(t)\n self.assertShapeEqual(actual, t)\n self.assertAllCloseAccordingToType(expected, actual.flatten())", " def _VerifyOneTest(self, pool_func, input_sizes, ksize, strides, padding,\n data_format, expected, use_gpu, v2,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n data_format: The data format we use to run the pooling operation.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n use_negative_input: If the input values should be negative.\"\n \"\"\"\n if data_format == \"NCHW_VECT_C\":\n avg_pool_func = nn_ops.avg_pool\n tf_logging.info(\"pool_func=%s\", pool_func)\n if pool_func == avg_pool_func:\n tf_logging.info(\"NCHW_VECT_C not yet implemented for avg_pool\")\n return\n if (self._isMaxPool(pool_func) and isinstance(padding, list)):\n tf_logging.info(\"NCHW_VECT_C not yet implemented for max pool\" +\n \" with explicit padding\")\n return", " self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float32, expected, use_gpu, v2,\n use_negative_input)\n if not test.is_built_with_rocm():\n # double datatype is not supported for pooling ops on the ROCm platform\n self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float64, expected, use_gpu, v2,\n use_negative_input)", " if not use_gpu or test_util.GpuSupportsHalfMatMulAndConv():\n self._VerifyOneType(pool_func, input_sizes, ksize, strides, padding,\n data_format, dtypes.float16, expected, use_gpu, v2,\n use_negative_input)", " def _VerifyValues(self,\n pool_func,\n input_sizes,\n ksize,\n strides,\n padding,\n expected,\n use_gpu,\n v2=False,\n one_dim=False,\n use_negative_input=False):\n \"\"\"Verifies the output values of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n ksize: The kernel size dimensions\n strides: The stride dimensions\n padding: Padding type.\n expected: An array containing the expected operation outputs.\n use_gpu: Whether we are running on GPU.\n v2: Whether to use v2 version.\n one_dim: If one dimensional pools should be done instead of two\n dimensional pools.\n use_negative_input: If the input values should be negative.\n \"\"\"\n for (data_format, use_gpu_2) in GetTestConfigs(\n include_nchw_vect_c=True, one_dimensional=one_dim):\n if use_gpu_2 == use_gpu:\n self._VerifyOneTest(pool_func, input_sizes, ksize, strides, padding,\n data_format, expected, use_gpu, v2,\n use_negative_input)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolEmpty(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 0],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 2, 4, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[8.5, 9.5, 10.5, 14.5, 15.5, 16.5],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindow(self, **kwargs):\n # input is:\n # [1.0, 2.0\n # 3.0 4.0]\n #\n # Window of [x, x] should do:\n # [avg(1.0, 2.0), avg(2.0, padded0),\n # avg(3.0, 4.0), avg(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[1.5, 2.0, 3.5, 4.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindow_2(self, **kwargs):\n # Window of [x,\n # x] should do:\n # [avg(1.0, 3.0), avg(2.0, 4.0)\n # avg(3.0, padded0), avg(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 2, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[2.0, 3.0, 3.0, 4.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindowMultiBatch(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[2, 2, 2, 2],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[\n 2.0, 3.0, 3.0, 4.0, 6.0, 7.0, 7.0, 8.0, 10.0, 11.0, 11.0, 12.0,\n 14.0, 15.0, 15.0, 16.0\n ],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingNonSquareWindowMultiBatch_2(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[2, 2, 2, 2],\n ksize=[1, 2, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[\n 3.0, 4.0, 5.0, 6.0, 5.0, 6.0, 7.0, 8.0, 11.0, 12.0, 13.0, 14.0,\n 13.0, 14.0, 15.0, 16.0\n ],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPaddingUnevenStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 2, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0, 16.0, 17.0, 18.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolValidPaddingUnevenStride_2(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 1, 1],\n padding=\"VALID\",\n expected=[7.0, 8.0, 9.0, 10.0, 11.0, 12.0],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePadding_2(self, **kwargs):\n expected_output = [\n 11.0, 12.0, 13.0, 14.0, 19.0, 20.0, 21.0, 22.0, 43.0, 44.0, 45.0, 46.0,\n 51.0, 52.0, 53.0, 54.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingPacket_4(self, **kwargs):\n expected_output = [\n 21.0, 22.0, 23.0, 24.0, 27.0, 28.0, 29.0, 30.0, 45.0, 46.0, 47.0, 48.0,\n 51.0, 52.0, 53.0, 54.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolSamePaddingPacket_8(self, **kwargs):\n expected_output = [\n -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, 4.0, 5.0, 6.0, 7.0,\n 8.0, 9.0, 10.0, 11.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0,\n 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, -3.5, -54.0, -53.0, -52.0,\n -51.0, -50.0, -49.0, -48.0, -47.0, -38.0, -37.0, -36.0, -35.0, -34.0,\n -33.0, -32.0, -31.0, -22.0, -21.0, -20.0, -19.0, -18.0, -17.0, -16.0,\n -15.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -11.0, -10.0,\n -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,\n 12.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 33.0, 34.0, 35.0,\n 36.0, 37.0, 38.0, -3.5, -2.5, -85.0, -84.0, -83.0, -82.0, -81.0, -80.0,\n -79.0, -78.0, -69.0, -68.0, -67.0, -66.0, -65.0, -64.0, -63.0, -62.0,\n -53.0, -52.0, -51.0, -50.0, -49.0, -48.0, -47.0, -46.0, -41.0, -40.0,\n -39.0, -38.0, -37.0, -36.0, -35.0, -34.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolEmptyInput(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[0, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n expected=[13.0, 14.0, 15.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 2, 3, 3],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[13.0, 14.0, 15.0, 16.0, 17.0, 18.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolZeroExplicitPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 0], [0, 0], [0, 0]],\n expected=[9.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolNegativeInputExpPadding(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [2, 1], [2, 1], [0, 0]],\n expected=[-1, -1, -1, -1],\n use_negative_input=True,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding(self, **kwargs):\n expected_output = [9.0, 9.0]\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 2], [0, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPaddingAdvanced(self, **kwargs):\n expected_output = [7, 9, 11, 12, 19, 21, 23, 24, 31, 33, 35, 36, 31, 33,\n 35, 36]\n self._VerifyOneType(\n input_sizes=[1, 6, 6, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [1, 2], [2, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolNegativeInputExpPaddingAdv(self, **kwargs):\n expected_output = [-1, -1, -3, -5, -7, -7, -9, -11, -19, -19, -21, -23, -31,\n -31, -33, -35]", " self._VerifyOneType(\n input_sizes=[1, 6, 6, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [1, 2], [2, 1], [0, 0]],\n expected=expected_output,\n use_negative_input=True,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, nn_ops.max_pool_v2))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding2_(self, **kwargs):\n expected_output = [9.0, 9.0]\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 2], [0, 1], [0, 0]],\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool1d, nn_ops.max_pool_v2, one_dimensional=True))\n @test_util.xla_allow_fallback(\"XLA doesn't support explicit padding\")\n @test_util.run_deprecated_v1\n def testMaxPoolExplicitPadding_1D(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 1],\n ksize=[1, 2, 1],\n strides=[1, 2, 1],\n padding=[[0, 0], [0, 1], [0, 0]],\n expected=[2.0, 3.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingNonSquareWindow(self, **kwargs):\n # input is:\n # [1.0, 2.0\n # 3.0 4.0]\n #\n # Window of [x, x] should do:\n #\n # [max(1.0, 2.0), max(2.0, padded0),\n # max(3.0, 4.0), max(4.0, padded0)]\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 1],\n ksize=[1, 1, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\",\n expected=[2.0, 2.0, 4.0, 4.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPaddingUnevenStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 2, 1],\n padding=\"VALID\",\n expected=[6.0, 8.0, 10.0, 12.0, 14.0, 16.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolValidPaddingUnevenStride2_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 1, 1],\n padding=\"VALID\",\n expected=[6.0, 7.0, 8.0, 14.0, 15.0, 16.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingPacket4_(self, **kwargs):\n expected_output = [\n 21.0, 22.0, 23.0, 24.0, 29.0, 30.0, 31.0, 32.0, 53.0, 54.0, 55.0, 56.0,\n 61.0, 62.0, 63.0, 64.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 4],\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolSamePaddingPacket8_(self, **kwargs):\n expected_output = [\n 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 97.0, 98.0, 99.0, 100.0,\n 101.0, 102.0, 103.0, 104.0, 113.0, 114.0, 115.0, 116.0, 117.0, 118.0,\n 119.0, 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0, 120.0,\n 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 34.0, 35.0, 36.0, 37.0,\n 38.0, 39.0, 40.0, 41.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0,\n 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 82.0, 83.0, 84.0, 85.0,\n 86.0, 87.0, 88.0, 89.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, 104.0,\n 105.0, 114.0, 115.0, 116.0, 117.0, 118.0, 119.0, 120.0, 121.0, 122.0,\n 123.0, 124.0, 125.0, 126.0, 127.0, 120.0, 121.0, -45.0, -44.0, -43.0,\n -42.0, -41.0, -40.0, -39.0, -38.0, -29.0, -28.0, -27.0, -26.0, -25.0,\n -24.0, -23.0, -22.0, -13.0, -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0,\n -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0\n ]\n self._VerifyOneType(\n input_sizes=[1, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=expected_output,\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2))\n @test_util.run_deprecated_v1\n def testMaxPoolEmptyInput(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[0, 8, 8, 8],\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[],\n **kwargs)", " # Tests for DepthwiseMaxPooling on CPU only.\n @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testDepthwiseMaxPool1x1DepthWindow(self, **kwargs):\n # input is:\n # [1.0, ..., 10.0] along depth,\n #\n # We maxpool by depth in patches of 2.\n self._VerifyOneType(\n input_sizes=[1, 1, 1, 10],\n ksize=[1, 1, 1, 2],\n strides=[1, 1, 1, 2],\n padding=\"SAME\",\n expected=[2.0, 4.0, 6.0, 8.0, 10.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testDepthwiseMaxPool2x2DepthWindow(self, **kwargs):\n # input is:\n #\n # a 2x2x6 cube, and we depthwise max across 3 to produce a 2x2x2\n # output. Each node has contiguous values, so the depthwise max\n # should be multiples of 3.0.\n self._VerifyOneType(\n input_sizes=[1, 2, 2, 6],\n ksize=[1, 1, 1, 3],\n strides=[1, 1, 1, 3],\n padding=\"SAME\",\n expected=[3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(\n nn_ops.max_pool, gen_nn_ops.max_pool_v2, allow_gpu=False))\n @test_util.run_deprecated_v1\n def testMaxPoolKernelSmallerThanStrideValid(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 7, 7, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 3, 3, 1],\n padding=\"VALID\",\n expected=[9, 12, 30, 33],\n **kwargs)", " @parameterized.parameters(GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testAvgPoolKernelSmallerThanStride(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 7, 7, 1],\n ksize=[1, 2, 2, 1],\n strides=[1, 3, 3, 1],\n padding=\"VALID\",\n expected=[5, 8, 26, 29],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2) +\n GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testKernelSmallerThanStrideSame1_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 3, 3, 1],\n ksize=[1, 1, 1, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[1, 3, 7, 9],\n **kwargs)", " @parameterized.parameters(\n GetTestConfigsDicts(nn_ops.max_pool, gen_nn_ops.max_pool_v2) +\n GetTestConfigsDicts(nn_ops.avg_pool))\n @test_util.run_deprecated_v1\n def testKernelSmallerThanStrideSame2_(self, **kwargs):\n self._VerifyOneType(\n input_sizes=[1, 4, 4, 1],\n ksize=[1, 1, 1, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\",\n expected=[1, 3, 9, 11],\n **kwargs)", " def _testDepthwiseMaxPoolInvalidConfig(self,\n in_size,\n ksize,\n strides,\n error_msg,\n use_gpu=False):\n with self.cached_session(use_gpu=use_gpu):\n t = constant_op.constant(1.0, shape=in_size)\n with self.assertRaisesRegex(errors_impl.UnimplementedError, error_msg):\n t = nn_ops.max_pool(\n t, ksize=ksize, strides=strides, padding=\"SAME\").eval()", " @test_util.disable_xla(\"b/123338077\") # Passes with XLA\n def testDepthwiseMaxPoolInvalidConfigs(self):\n self._testDepthwiseMaxPoolInvalidConfig(\n [1, 2, 2, 4], [1, 2, 2, 2], [1, 1, 1, 2],\n \"exactly one of pooling across depth\")\n self._testDepthwiseMaxPoolInvalidConfig(\n [1, 2, 2, 4], [1, 1, 1, 2], [1, 1, 1, 1],\n \"depth window to equal the depth stride\")\n self._testDepthwiseMaxPoolInvalidConfig([1, 2, 2, 4], [1, 1, 1, 3],\n [1, 1, 1, 3], \"evenly divide\")\n if test.is_gpu_available():\n with self.session():\n t = variables.Variable(np.ones([1, 2, 2, 4]))\n self.evaluate(variables.global_variables_initializer())\n with self.assertRaisesOpError(\"for CPU devices\"):\n nn_ops.max_pool(\n t, ksize=[1, 1, 1, 2], strides=[1, 1, 1, 2],\n padding=\"SAME\").eval()", " # The following are tests that verify that the CPU and GPU implementations\n # produce the same results.\n def _CompareMaxPoolingFwd(self, input_shape, ksize, strides, padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n tensor_input = np.random.rand(*input_shape).astype(dtype)\n with self.cached_session():\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op, _ = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n gpu_val = self.evaluate(out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n cpu_val = self.evaluate(out_op)\n self.assertAllCloseAccordingToType(cpu_val, gpu_val)", " def _CompareMaxPoolingBk(self, input_shape, output_shape, ksize, strides,\n padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n # Generate numbers in a narrow range, so that there are many duplicates\n # in the input.\n tensor_input = np.random.random_integers(0, 3, input_shape).astype(dtype)\n tensor_output = np.random.rand(*output_shape).astype(dtype)\n with self.cached_session():\n t = constant_op.constant(tensor_input, shape=input_shape)\n _, argmax_op = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n argmax = self.evaluate(argmax_op)\n grad_in = constant_op.constant(tensor_output, shape=output_shape)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(t, grad_in, argmax, ksize,\n strides, padding)\n gpu_val = self.evaluate(out_op)\n self.assertShapeEqual(gpu_val, out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n orig_out = self.evaluate(out_op)\n grad_in = constant_op.constant(tensor_output, shape=output_shape)\n out_op = gen_nn_ops.max_pool_grad(t, orig_out, grad_in, ksize, strides,\n padding)\n cpu_val = self.evaluate(out_op)\n self.assertShapeEqual(cpu_val, out_op)\n # The CPU version accumulates its gradient on fp16, so it's less\n # accurate than the GPU version that does the accumulation on fp32\n self.assertAllCloseAccordingToType(\n cpu_val, gpu_val, half_rtol=0.01, half_atol=0.01)", " def _CompareMaxPoolingGradBk(self, input_shape, output_shape, ksize, strides,\n padding):\n # double datatype is currently not supported for pooling ops\n # on the ROCm platform\n for dtype in [np.float32, np.float16] \\\n + [np.float64] if not test.is_built_with_rocm() else []:\n # Generate numbers in a narrow range, so that there are many duplicates\n # in the input.\n tensor_input = np.random.random_integers(0, 3, input_shape).astype(dtype)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n _, argmax_op = nn_ops.max_pool_with_argmax(t, ksize, strides, padding)\n argmax = self.evaluate(argmax_op)\n grad_in = constant_op.constant(tensor_input, shape=input_shape)\n out_op = gen_nn_ops.max_pool_grad_grad_with_argmax(\n t, grad_in, argmax, ksize, strides, padding)\n gpu_val = self.evaluate(out_op)\n self.assertShapeEqual(gpu_val, out_op)\n with self.cached_session(use_gpu=False):\n t = constant_op.constant(tensor_input, shape=input_shape)\n out_op = nn_ops.max_pool(t, ksize, strides, padding)\n orig_out = self.evaluate(out_op)\n grad_in = constant_op.constant(tensor_input, shape=input_shape)\n out_op = gen_nn_ops.max_pool_grad_grad(t, orig_out, grad_in, ksize,\n strides, padding)\n cpu_val = self.evaluate(out_op)\n self.assertShapeEqual(cpu_val, out_op)\n # The CPU version accumulates its gradient on fp16, so it's less\n # accurate than the GPU version that does the accumulation on fp32\n self.assertAllCloseAccordingToType(\n cpu_val, gpu_val, half_rtol=0.01, half_atol=0.01)", " def testMaxPoolingWithArgmax(self):\n tensor_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\", \"Targmax\"])\n configs = [\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int64),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int64),\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int32),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int32),\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8], dtypes.int64),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17], dtypes.int64),\n ]", " for config in configs:\n with GetDeviceScope(self, use_gpu=config.use_gpu):\n t = constant_op.constant(tensor_input, shape=[2, 3, 3, 1])\n out_op, argmax_op = nn_ops.max_pool_with_argmax(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n Targmax=config.Targmax,\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out, argmax = self.evaluate([out_op, argmax_op])\n self.assertShapeEqual(out, out_op)\n self.assertShapeEqual(argmax, argmax_op)\n self.assertAllClose(out.ravel(),\n [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])\n self.assertAllEqual(argmax.ravel(), config.argmax)", " def testMaxPoolingGradWithArgmax(self):\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\"])\n configs = [\n Config(False, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(False, True, [0, 1, 3, 5, 9, 11, 15, 17]),\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17])\n ]", " for config in configs:\n with GetDeviceScope(self, config.use_gpu):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n config.argmax, shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out = self.evaluate(out_op).flatten()\n self.assertAllClose(out, [\n 11.0, 12.0, 0.0, 13.0, 0.0, 14.0, 0.0, 0.0, 0.0, 21.0, 0.0, 22.0,\n 0.0, 0.0, 0.0, 23.0, 0.0, 24.0\n ])", " def testMaxPoolingGradThrowDeterminismError(self):\n if test.is_gpu_available(cuda_only=True):\n try:\n config_exec.enable_op_determinism()\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " with GetDeviceScope(self, True):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n [0, 1, 3, 5, 0, 2, 6, 8], shape=[2, 2, 2, 1], dtype=dtypes.int64)\n with self.assertRaisesRegexp(\n errors_impl.UnimplementedError, \"Determinism is not yet supported \"\n \"for MaxPoolGradWithArgmax.\"):\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=False)\n self.evaluate(out_op)\n finally:\n config_exec.disable_op_determinism()\n else:\n try:\n config_exec.enable_op_determinism()\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [11.0, 12.0, 13.0, 14.0, 21.0, 22.0, 23.0, 24.0]", " with GetDeviceScope(self, False):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 2, 2, 1])\n argmax_t = constant_op.constant(\n [0, 1, 3, 5, 0, 2, 6, 8], shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=False)\n self.evaluate(out_op)\n finally:\n config_exec.disable_op_determinism()", " def testMaxPoolingGradGradWithArgmax(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n orig_input = [\n 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 1.0\n ]\n tensor_input = [\n 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 21.0, 22.0, 23.0,\n 24.0, 25.0, 26.0, 27.0, 28.0, 29.0\n ]", " Config = collections.namedtuple(\n \"Config\", [\"use_gpu\", \"include_batch_in_index\", \"argmax\"])\n configs = [\n Config(True, False, [0, 1, 3, 5, 0, 2, 6, 8]),\n Config(True, True, [0, 1, 3, 5, 9, 11, 15, 17])\n ]", " for config in configs:\n with GetDeviceScope(self, config.use_gpu):\n orig_in = constant_op.constant(orig_input, shape=[2, 3, 3, 1])\n t = constant_op.constant(tensor_input, shape=[2, 3, 3, 1])\n argmax_t = constant_op.constant(\n config.argmax, shape=[2, 2, 2, 1], dtype=dtypes.int64)\n out_op = gen_nn_ops.max_pool_grad_grad_with_argmax(\n orig_in,\n t,\n argmax_t,\n ksize=[1, 2, 2, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n include_batch_in_index=config.include_batch_in_index)\n out = self.evaluate(out_op).flatten()\n self.assertAllClose(out,\n [11.0, 12.0, 14.0, 16.0, 21.0, 23.0, 27.0, 29.0])", " def _ConstructAndTestGradient(self,\n pool_func,\n input_sizes,\n output_sizes,\n window_rows,\n window_cols,\n row_stride,\n col_stride,\n padding,\n data_format,\n use_gpu,\n x_init_value=None):\n \"\"\"Verifies the gradients of the max or avg pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n output_sizes: Output tensor dimensions.\n window_rows: kernel size in row dim\n window_cols: kernel size in col dim\n row_stride: Row Stride.\n col_stride: Col Stride.\n padding: Padding type.\n data_format: Data format.\n use_gpu: whether we are running on GPU\n x_init_value: Values to be passed to the gradient checker.\n \"\"\"\n assert input_sizes[0] == output_sizes[0]\n assert input_sizes[3] == output_sizes[3]\n total_size = 1\n for s in input_sizes:\n total_size *= s\n # Initializes the input tensor with array containing incrementing\n # numbers from 1.\n x = [f * 1.0 for f in range(1, total_size + 1)]\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = constant_op.constant(x, shape=input_sizes, name=\"input\")\n if pool_func == nn_ops.avg_pool:\n func_name = \"avg_pool\"\n err_tolerance = 1e-4\n else:\n if x_init_value is None:\n x_init_value = np.asfarray(\n np.arange(1, total_size + 1),\n dtype=np.float32).reshape(input_sizes)\n func_name = \"max_pool\"\n err_tolerance = 1e-3\n if data_format == \"NCHW\":\n ksize = [1, 1, window_rows, window_cols]\n strides = [1, 1, row_stride, col_stride]\n if isinstance(padding, list):\n padding = test_util.NHWCToNCHW(padding)\n t = test_util.NHWCToNCHW(input_tensor)\n else:\n ksize = [1, window_rows, window_cols, 1]\n strides = [1, row_stride, col_stride, 1]\n t = input_tensor\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=func_name)\n if data_format == \"NCHW\":\n t = test_util.NCHWToNHWC(t)", " err = gradient_checker.compute_gradient_error(\n input_tensor,\n input_sizes,\n t,\n output_sizes,\n x_init_value=x_init_value,\n delta=1e-2)\n tf_logging.info(\"%s gradient error = %.4f\" % (func_name, err))\n self.assertLess(err, err_tolerance)", " def _ConstructAndTestSecondGradient(self,\n pool_func,\n input_sizes,\n output_sizes,\n window_rows,\n window_cols,\n row_stride,\n col_stride,\n padding,\n data_format,\n use_gpu,\n x_init_value=None):\n \"\"\"Verifies the second-order gradients of the pooling function.", " Args:\n pool_func: Function to be called, co.MaxPool, co.AvgPool,\n or the Lua version.\n input_sizes: Input tensor dimensions.\n output_sizes: Output tensor dimensions.\n window_rows: kernel size in row dim\n window_cols: kernel size in col dim\n row_stride: Row Stride.\n col_stride: Col Stride.\n padding: Padding type.\n data_format: Data format.\n use_gpu: whether we are running on GPU\n x_init_value: Values to be passed to the gradient checker.\n \"\"\"\n assert input_sizes[0] == output_sizes[0]\n assert input_sizes[3] == output_sizes[3]\n total_size = 1\n for s in input_sizes:\n total_size *= s\n # Initializes the input tensor with array containing incrementing\n # numbers from 1.\n x = [f * 1.0 for f in range(1, total_size + 1)]\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = constant_op.constant(x, shape=input_sizes, name=\"input\")\n if pool_func == nn_ops.avg_pool:\n func_name = \"avg_pool\"\n err_tolerance = 1e-3\n else:\n if x_init_value is None:\n x_init_value = np.asfarray(\n np.arange(1, total_size + 1),\n dtype=np.float32).reshape(input_sizes)\n func_name = \"max_pool\"\n err_tolerance = 1e-2\n if data_format == \"NCHW\":\n ksize = [1, 1, window_rows, window_rows]\n strides = [1, 1, row_stride, col_stride]\n t = test_util.NHWCToNCHW(input_tensor)\n else:\n ksize = [1, window_rows, window_rows, 1]\n strides = [1, row_stride, col_stride, 1]\n t = input_tensor\n t = pool_func(\n t,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=func_name)\n if data_format == \"NCHW\":\n t = test_util.NHWCToNCHW(t)", " t_g = gradients_impl.gradients(t**2, input_tensor)[0]\n err = gradient_checker.compute_gradient_error(\n input_tensor,\n input_sizes,\n t_g,\n input_sizes,\n x_init_value=x_init_value,\n delta=1e-2)\n tf_logging.info(\"%s second-order gradient error = %.4f\" % (func_name, err))\n self.assertLess(err, err_tolerance)", " def _testMaxPoolGradValidPadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_1_6(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 6, 6, 3],\n output_sizes=[2, 5, 5, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_1_7(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 7, 7, 3],\n output_sizes=[2, 6, 6, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding1_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 2, 2, 1],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradValidPadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding1_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding2_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradSamePadding3_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPadding_1(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [1, 1], [1, 1], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPadding_2(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 6, 8, 1],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [2, 3], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingLeftGreater(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 6, 8, 1],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [3, 2], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingBatchChannel(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[4, 7, 7, 3],\n output_sizes=[4, 6, 8, 3],\n window_rows=3,\n window_cols=5,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 1], [3, 2], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolExplicitPaddingStrides(self, data_format, use_gpu):\n for pool_func in [nn_ops.max_pool]:\n self._ConstructAndTestGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 4, 3, 1],\n window_rows=3,\n window_cols=3,\n row_stride=2,\n col_stride=3,\n padding=[[0, 0], [1, 1], [1, 1], [0, 0]],\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testMaxPoolGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testMaxPoolGradValidPadding1_1(data_format, use_gpu)\n self._testMaxPoolGradValidPadding1_2(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_1_6(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_1_7(data_format, use_gpu)\n self._testMaxPoolGradValidPadding2_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding1_1(data_format, use_gpu)\n self._testMaxPoolGradSamePadding1_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding2_1(data_format, use_gpu)\n self._testMaxPoolGradSamePadding2_2(data_format, use_gpu)\n self._testMaxPoolGradSamePadding3_1(data_format, use_gpu)\n self._testMaxPoolExplicitPadding_1(data_format, use_gpu)\n self._testMaxPoolExplicitPadding_2(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingStrides(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingLeftGreater(data_format, use_gpu)\n self._testMaxPoolExplicitPaddingBatchChannel(data_format, use_gpu)", " def _MaxPoolGrad(self, orig_input, orig_output, grad, window_rows,\n window_cols, row_stride, col_stride, padding, v2):\n \"\"\"Max Pooling Gradient.", " Args:\n orig_input: A float Tensor. The original input tensor.\n orig_output: A float Tensor. The original output tensor.\n grad: A float Tensor.\n The 4D (batch x rows x cols x depth) output backprop.\n window_rows: integer. Kernel size along rows dimension.\n window_cols: integer. Kernel size along cols dimension.\n row_stride: integer. Stride along rows dimension\n col_stride: integer. Stride along cols dimension\n padding: PoolingOpDef.Padding. Padding type.", " Returns:\n A Tensor.\n \"\"\"\n pool_func = gen_nn_ops.max_pool_grad_v2 if v2 else gen_nn_ops.max_pool_grad\n if v2:\n return pool_func(orig_input, orig_output, grad,\n [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)\n else:\n padding, explicit_paddings = nn_ops.convert_padding(padding)\n return pool_func(orig_input, orig_output, grad,\n [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding,\n explicit_paddings)", " def _testMaxPoolGradDirect(self, input_data, output_backprop,\n expected_input_backprop, input_sizes, output_sizes,\n window_rows, window_cols, row_stride, col_stride,\n padding, use_gpu, v2):\n pool_func = gen_nn_ops.max_pool_v2 if v2 else nn_ops.max_pool\n with self.cached_session(use_gpu=use_gpu):\n input_tensor = variables.Variable(\n np.array(input_data, dtype=np.float32).reshape(input_sizes))\n self.evaluate(variables.global_variables_initializer())\n output_tensor = pool_func(input_tensor, [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)\n output_backprop_tensor = constant_op.constant(\n output_backprop, shape=output_sizes)", " input_backprop_tensor = self._MaxPoolGrad(\n input_tensor, output_tensor, output_backprop_tensor, window_rows,\n window_cols, row_stride, col_stride, padding, v2)", " actual_input_backprop = self.evaluate(input_backprop_tensor)\n self.assertShapeEqual(actual_input_backprop, input_backprop_tensor)\n actual_input_backprop = actual_input_backprop.flatten()\n actual_input_backprop = self._GetNdArray(actual_input_backprop)", " actual_output = self.evaluate(output_tensor).flatten()\n actual_output = self._GetNdArray(actual_output)", " self.assertAllClose(\n expected_input_backprop, actual_input_backprop, rtol=1e-6, atol=1e-6)", " def _testMaxPoolGradDirect1_1(self):\n input_data = [\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 12.0, 13.0, 0.0, 15.0, 16.0, 17.0, 0.0, 19.0, 20.0, 21.0, 0.0,\n 0.0, 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradDirect1_2(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 17.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradDirect1_3(self):\n input_data = [\n 1.0,\n 0.0,\n 1.0,\n 0.0,\n 0.0,\n 1.0,\n 0.0,\n 1.0,\n 1.0,\n 0.0,\n 1.0,\n 0.0,\n 0.0,\n 1.0,\n 0.0,\n 1.0,\n ]\n output_backprop = [\n 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0,\n 23.0, 24.0, 25.0, 26.0\n ]\n expected_input_backprop = [\n 54,\n 0.0,\n 62,\n 0.0,\n 0.0,\n 60,\n 0.0,\n 22.0,\n 47,\n 0.0,\n 51,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]", " for use_gpu in True, False:\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 4, 4, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradZeroExplicitPadding(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 17.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 0], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_1(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,\n 20.0, 21.0, 22.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 49.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 22.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 4, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_2(self):\n input_data = [\n 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n 0.0, 1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n expected_input_backprop = [\n 54.0, 0.0, 30.0, 0.0, 0.0, 0.0, 0.0, 0.0, 39.0, 0.0, 21.0, 0.0, 0.0,\n 0.0, 0.0, 0.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=3,\n window_cols=3,\n row_stride=2,\n col_stride=2,\n padding=[[0, 0], [2, 1], [2, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " def _testMaxPoolGradExplicitPadding_3(self):\n input_data = [\n -1.0, -5.0, -1.0, -5.0, -5.0, -1.0, -5.0, -1.0, -1.0, -5.0, -1.0, -5.0,\n -5.0, -1.0, -5.0, -1.0\n ]\n output_backprop = [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,\n 20.0, 21.0, 22.0]\n expected_input_backprop = [\n 11.0, 0.0, 25.0, 0.0, 0.0, 31.0, 0.0, 49.0, 19.0, 0.0, 41.0, 0.0, 0.0,\n 0.0, 0.0, 22.0\n ]", " for use_gpu in True, False:\n for v2 in [False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 4, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=[[0, 0], [0, 0], [0, 1], [0, 0]],\n use_gpu=use_gpu,\n v2=v2)", " @test_util.no_xla_auto_jit(\"b/123923733\") # NaNs handled differently\n def _testMaxPoolGradDirectWithNans2_1(self):\n input_data = [float(\"nan\")] * 16\n output_backprop = [11.0, 12.0, 13.0, 15.0, 16.0, 17.0, 19.0, 20.0, 21.0]\n # Test the CPU implementation, which propagates diffs in case of NaN\n expected_input_backprop_tf_cpu = [\n 11.0, 12.0, 13.0, 0.0, 15.0, 16.0, 17.0, 0.0, 19.0, 20.0, 21.0, 0.0,\n 0.0, 0.0, 0.0, 0.0\n ]\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_tf_cpu,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=False,\n v2=v2)", " if not test.is_gpu_available():\n return", " # The functionality associated with TF_ENABLE_NANPROP is currently\n # not supported on the ROCm platform, so skip this part of the test\n # NANs in input lead to non-deterministic results, and hence skipping\n # the remaining tests altogether on the ROCm platform\n if test.is_built_with_rocm():\n return", " # Test the GPU implementation that uses cudnn for now.\n saved_nanprop = os.environ.get(\"TF_ENABLE_MAXPOOL_NANPROP\")\n # Do not propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"0\"\n expected_input_backprop_cudnn = [\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0\n ]", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " # Propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"1\"\n expected_input_backprop_cudnn = expected_input_backprop_tf_cpu", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " if saved_nanprop:\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = saved_nanprop\n else:\n del os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"]", " @test_util.no_xla_auto_jit(\"b/123923733\") # NaNs handled differently\n def _testMaxPoolGradDirectWithNans2_2(self):\n input_data = [float(\"nan\")] * 16\n output_backprop = [\n float(\"nan\"), 12.0, 13.0, 15.0,\n float(\"nan\"), 17.0, 19.0, 20.0,\n float(\"nan\")\n ]\n # Test the CPU implementation, which propagates diffs in case of NaN\n expected_input_backprop_tf_cpu = [\n float(\"nan\"), 12.0, 13.0, 0.0, 15.0,\n float(\"nan\"), 17.0, 0.0, 19.0, 20.0,\n float(\"nan\"), 0.0, 0.0, 0.0, 0.0, 0.0\n ]\n for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_tf_cpu,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=False,\n v2=v2)", " if not test.is_gpu_available():\n return", " # The functionality associated with TF_ENABLE_NANPROP is currently\n # not supported on the ROCm platform, so skip this part of the test\n # NANs in input lead to non-deterministic results, and hence skipping\n # the remaining tests altogether on the ROCm platform\n if test.is_built_with_rocm():\n return", " # Test the GPU implementation that uses cudnn for now.\n saved_nanprop = os.environ.get(\"TF_ENABLE_MAXPOOL_NANPROP\")\n # Do not propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"0\"\n expected_input_backprop_cudnn = [\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0\n ]", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " # Propagate the diff in cases of NaNs\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = \"1\"\n expected_input_backprop_cudnn = expected_input_backprop_tf_cpu", " for v2 in [True, False]:\n self._testMaxPoolGradDirect(\n input_data,\n output_backprop,\n expected_input_backprop_cudnn,\n input_sizes=[1, 4, 4, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n use_gpu=True,\n v2=v2)", " if saved_nanprop:\n os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"] = saved_nanprop\n else:\n del os.environ[\"TF_ENABLE_MAXPOOL_NANPROP\"]", " @test_util.run_deprecated_v1\n def testMaxPoolGradDirect(self):\n self._testMaxPoolGradDirect1_1()\n self._testMaxPoolGradDirect1_2()\n self._testMaxPoolGradDirect1_3()\n self._testMaxPoolGradDirectWithNans2_1()\n self._testMaxPoolGradDirectWithNans2_2()\n self._testMaxPoolGradZeroExplicitPadding()\n self._testMaxPoolGradExplicitPadding_1()\n self._testMaxPoolGradExplicitPadding_2()\n self._testMaxPoolGradExplicitPadding_3()", " def _testMaxPoolGradGradValidPadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[1, 3, 3, 1],\n output_sizes=[1, 3, 3, 1],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_1_6(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 6, 6, 3],\n output_sizes=[2, 5, 5, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_1_7(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 7, 7, 3],\n output_sizes=[2, 6, 6, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradValidPadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding1_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding2_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding2_2(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testMaxPoolGradGradSamePadding3_1(self, data_format, use_gpu):\n for pool_func in [gen_nn_ops.max_pool_v2, nn_ops.max_pool]:\n self._ConstructAndTestSecondGradient(\n pool_func,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testMaxPoolGradGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testMaxPoolGradGradValidPadding1_1(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_1_6(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_1_7(data_format, use_gpu)\n self._testMaxPoolGradGradValidPadding2_2(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding1_1(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding2_1(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding2_2(data_format, use_gpu)\n self._testMaxPoolGradGradSamePadding3_1(data_format, use_gpu)", " def _MaxPoolGradGrad(self, orig_input, orig_output, grad, window_rows,\n window_cols, row_stride, col_stride, padding):\n \"\"\"Max Pooling Second-Order Gradient.", " Args:\n orig_input: A float Tensor. The original input tensor.\n orig_output: A float Tensor. The original output tensor.\n grad: A float Tensor.\n The 4D (batch x out_rows x out_cols x depth) output backprop.\n window_rows: integer. Kernel size along rows dimension.\n window_cols: integer. Kernel size along cols dimension.\n row_stride: integer. Stride along rows dimension\n col_stride: integer. Stride along cols dimension\n padding: PoolingOpDef.Padding. Padding type.", " Returns:\n A Tensor.\n \"\"\"\n return gen_nn_ops.max_pool_grad_grad(\n orig_input, orig_output, grad, [1, window_rows, window_cols, 1],\n [1, row_stride, col_stride, 1], padding)", " @test_util.run_deprecated_v1\n def testAvgPoolGrad(self):\n for (data_format, use_gpu) in GetTestConfigs():\n self._testAvgPoolGradValidPadding1_1(data_format, use_gpu)\n self._testAvgPoolGradValidPadding1_2(data_format, use_gpu)\n self._testAvgPoolGradValidPadding2_1(data_format, use_gpu)\n self._testAvgPoolGradValidPadding2_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding1_1(data_format, use_gpu)\n self._testAvgPoolGradSamePadding1_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding2_1(data_format, use_gpu)\n self._testAvgPoolGradSamePadding2_2(data_format, use_gpu)\n self._testAvgPoolGradSamePadding3_1(data_format, use_gpu)", " def _testAvgPoolGradValidPadding1_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 3, 3, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding1_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 2, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding2_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 3, 3, 3],\n output_sizes=[2, 2, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradValidPadding2_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 2, 3],\n output_sizes=[2, 1, 1, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"VALID\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding1_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=1,\n window_cols=1,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding1_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=1,\n window_cols=1,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding2_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 2, 4, 3],\n window_rows=2,\n window_cols=2,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding2_2(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[2, 2, 4, 3],\n output_sizes=[2, 1, 2, 3],\n window_rows=2,\n window_cols=2,\n row_stride=2,\n col_stride=2,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " def _testAvgPoolGradSamePadding3_1(self, data_format, use_gpu):\n self._ConstructAndTestGradient(\n nn_ops.avg_pool,\n input_sizes=[1, 7, 7, 1],\n output_sizes=[1, 7, 7, 1],\n window_rows=3,\n window_cols=3,\n row_stride=1,\n col_stride=1,\n padding=\"SAME\",\n data_format=data_format,\n use_gpu=use_gpu)", " @test_util.run_deprecated_v1\n def testShapeFunctionEdgeCases(self):\n # All shapes unknown.\n for pool_func in [nn_ops.max_pool, nn_ops.avg_pool]:\n p = pool_func(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")\n self.assertEqual([None, None, None, None], p.get_shape().as_list())\n p, am = nn_ops.max_pool_with_argmax(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")\n self.assertEqual([None, None, None, None], p.get_shape().as_list())\n self.assertEqual([None, None, None, None], am.get_shape().as_list())", " # Incorrect input shape.\n for pool_func in [\n nn_ops.max_pool, nn_ops.avg_pool, nn_ops.max_pool_with_argmax\n ]:\n with self.assertRaises(ValueError):\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[1, 3]),\n ksize=[1, 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding=\"SAME\")", " @test_util.run_deprecated_v1\n @test_util.disable_xla(\"b/123337890\") # Error messages differ\n def testOpEdgeCases(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n pool_funcs = [nn_ops.max_pool, nn_ops.avg_pool]\n if test.is_gpu_available():\n pool_funcs.append(nn_ops.max_pool_with_argmax)\n for pool_func in pool_funcs:\n if pool_func != nn_ops.max_pool:\n # Illegal strides.\n with self.assertRaisesRegex(\n errors_impl.UnimplementedError,\n \"Pooling is not yet supported on the batch\"):\n sess.run(\n pool_func(\n array_ops.placeholder(dtypes.float32),\n ksize=[1, 1, 1, 1],\n strides=[2, 1, 1, 1],\n padding=\"SAME\"))", " # Filter too large.\n with self.assertRaisesRegex(ValueError, \"Negative dimension size\"):\n sess.run(\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[32, 20, 20, 3]),\n ksize=[1, 20, 21, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\"))\n with self.assertRaisesRegex(ValueError, \"Negative dimension size\"):\n pool_func(\n array_ops.placeholder(dtypes.float32, shape=[32, 20, 20, 3]),\n ksize=[1, 21, 20, 1],\n strides=[1, 1, 1, 1],\n padding=\"VALID\")", " @test_util.run_deprecated_v1\n def testEdgeCasesRaiseErrors(self):\n with self.assertRaisesRegexp(\n ValueError, \"NCHW_VECT_C.*is not supported with \"\n \"explicit padding|XLA does not support pooling ops with explicit \"\n \"padding\"):\n nn_ops.max_pool(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1]),\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=[[0, 0], [0, 1], [0, 1], [0, 0]],\n data_format=\"NCHW_VECT_C\")\n with self.assertRaisesRegexp(\n ValueError, \"Explicit padding is not supported with an input \"\n \"tensor of rank 5\"):\n nn_ops.max_pool_v2(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1, 1]),\n ksize=[1, 2, 2, 1, 1],\n strides=[1, 2, 2, 1, 1],\n padding=[[0, 0], [0, 1], [0, 1], [0, 0]],\n data_format=\"NCHW\")\n with self.assertRaisesRegexp(\n ValueError, \"Attr 'padding' of 'MaxPoolV2' Op passed \"\n \"string 'EXPLICIT'\"):\n gen_nn_ops.max_pool_v2(\n array_ops.placeholder(dtypes.float32, shape=[1, 3, 3, 1, 1]),\n ksize=[1, 2, 2, 1, 1],\n strides=[1, 2, 2, 1, 1],\n padding=\"EXPLICIT\",\n data_format=\"NHWC\")", " @test_util.run_deprecated_v1\n def testEdgeCasesExcessPadding(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n (errors_impl.UnimplementedError, errors_impl.InvalidArgumentError),\n \"Right padding 2 needs to be smaller than the window size 2|\"\n \"XLA does not support pooling ops with explicit padding\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[0, 0, 0, 1, 0, 2, 0, 0],\n data_format=\"NHWC\"))", " @test_util.run_deprecated_v1\n def testNegativePadding(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n ValueError, \"All elements of explicit_paddings must be \"\n \"nonnegative for\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[0, 0, -1, -1, -1, -1, 0, 0],\n data_format=\"NHWC\"))", " @test_util.run_deprecated_v1\n def testExplicitPaddingBatch(self):\n with self.session(use_gpu=test.is_gpu_available()) as sess:\n with self.assertRaisesRegexp(\n ValueError, \"Nonzero explicit padding in the batch or depth \"\n \"dimensions is not supported\"):\n input_sizes = [1, 3, 3, 1]\n x = [(((f + 128) % 255) - 127) for f in range(9)]\n t = constant_op.constant(x, shape=input_sizes, dtype=dtypes.float32)\n sess.run(gen_nn_ops.max_pool(\n t,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"EXPLICIT\",\n explicit_paddings=[1, 1, 1, 1, 1, 1, 0, 0],\n data_format=\"NHWC\"))", " @test_util.disable_xla(\n \"b/205634417\") # XLA is not throwing shape errors for multiple *Grad ops.\n def testMaxPoolGradEagerShapeErrors(self):\n with context.eager_mode():\n orig_in = array_ops.ones((1, 1, 1, 1))", " # Test invalid orig_out shape\n orig_out = array_ops.ones((1, 1, 1, 2))\n grad = array_ops.ones((1, 1, 1, 1))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected orig_output shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " # Test invalid grad shape\n orig_out = array_ops.ones((1, 1, 1, 1))\n grad = array_ops.ones((1, 1, 1, 2))\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad(\n orig_in, orig_out, grad, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " def testMaxPoolGradWithArgmaxEagerShapeErrors(self):\n with context.eager_mode():\n inp = array_ops.ones((1, 1, 1, 1))", " # Test invalid grad shape\n grad = array_ops.ones((1, 1, 1, 2))\n argmax = array_ops.zeros((1, 1, 1, 1), dtype=dtypes.int64)\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n # max_pool_grad_grad_with_argmax is only implemented for GPUs\n if test.is_gpu_available():\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected grad shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")", " # Test invalid argmax shape\n grad = array_ops.ones((1, 1, 1, 1))\n argmax = array_ops.ones((1, 1, 1, 2), dtype=dtypes.int64)\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected argmax shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n # max_pool_grad_grad_with_argmax is only implemented for GPUs\n if test.is_gpu_available():\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n r\"Expected argmax shape to be \\[1,1,1,1\\], but got \\[1,1,1,2\\]\"):\n gen_nn_ops.max_pool_grad_grad_with_argmax(\n inp, grad, argmax, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1],\n padding=\"VALID\")\n", " def testAvgPoolGradInvalidInputShapeRaiseError(self):\n with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):\n with self.cached_session():\n orig_input_shape = constant_op.constant(\n -536870912, shape=[4], dtype=dtypes.int32)\n grad = constant_op.constant(\n .0890338004362538, shape=[1, 5, 7, 1], dtype=dtypes.float64)\n t = gen_nn_ops.AvgPoolGrad(\n orig_input_shape=orig_input_shape,\n grad=grad,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"VALID\",\n data_format=\"NHWC\")\n self.evaluate(t)\n", "\ndef GetMaxPoolFwdTest(input_size, filter_size, strides, padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingFwd(input_size, filter_size, strides, padding)", " return Test", "\ndef GetMaxPoolGradTest(input_size, filter_size, output_size, strides, padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingBk(input_size, output_size, filter_size, strides,\n padding)", " return Test", "\ndef GetMaxPoolGradGradTest(input_size, filter_size, output_size, strides,\n padding):", " def Test(self):\n # MaxPoolWithArgMax is implemented only on CUDA.\n if not test.is_gpu_available(cuda_only=True):\n return\n self._CompareMaxPoolingGradBk(input_size, output_size, filter_size, strides,\n padding)", " return Test", "\nif __name__ == \"__main__\":\n for (name_, input_size_, filter_size_, output_size_, stride_,\n padding_) in GetShrunkInceptionMaxPoolShapes():\n setattr(PoolingTest, \"testMaxPoolFwd_\" + name_,\n GetMaxPoolFwdTest(input_size_, filter_size_, stride_, padding_))\n setattr(PoolingTest, \"testMaxPoolGrad_\" + name_,\n GetMaxPoolGradTest(input_size_, filter_size_, output_size_, stride_,\n padding_))\n setattr(PoolingTest, \"testMaxPoolGradGrad_\" + name_,\n GetMaxPoolGradGradTest(input_size_, filter_size_, output_size_,\n stride_, padding_))\n test.main()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [547, 2472], "buggy_code_start_loc": [301, 2472], "filenames": ["tensorflow/core/kernels/avgpooling_op.cc", "tensorflow/python/kernel_tests/nn_ops/pooling_ops_test.py"], "fixing_code_end_loc": [547, 2489], "fixing_code_start_loc": [301, 2473], "message": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "C4DFBF2D-5283-42F6-8800-D653BFA5CE82", "versionEndExcluding": "2.7.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F9D273D-02DC-441E-AA91-EAC8DEAA4B44", "versionEndExcluding": "2.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.8.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "FE4F8A81-6CC2-4F7F-9602-C170FDD926E7", "versionEndExcluding": "2.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.9.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc0:*:*:*:*:*:*", "matchCriteriaId": "1DBFBCE2-0A01-4575-BE45-6775ABFB8B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc1:*:*:*:*:*:*", "matchCriteriaId": "89806CF9-E423-4CA6-A01A-8175C260CB24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc2:*:*:*:*:*:*", "matchCriteriaId": "F2B80690-A257-4E16-BD27-9AE045BC56ED", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.10:rc3:*:*:*:*:*:*", "matchCriteriaId": "F335F9A4-5AB8-4E53-BC18-E01F7C653E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an open source platform for machine learning. The `AvgPoolOp` function takes an argument `ksize` that must be positive but is not checked. A negative `ksize` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds to this issue."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto para el aprendizaje autom\u00e1tico. La funci\u00f3n \"AvgPoolOp\" toma un argumento \"ksize\" que debe ser positivo pero no se comprueba. Un \"ksize\" negativo puede desencadenar un fallo de \"CHECK\" y bloquear el programa. Hemos parcheado el problema en el commit 3a6ac52664c6c095aa2b114e742b0aa17fdce78f de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.10.0. Tambi\u00e9n seleccionaremos este compromiso en TensorFlow versi\u00f3n 2.9.1, TensorFlow versi\u00f3n 2.8.1, y TensorFlow versi\u00f3n 2.7.2, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda est\u00e1n en el rango admitido. No se presentan mitigaciones conocidas para este problema"}], "evaluatorComment": null, "id": "CVE-2022-35941", "lastModified": "2022-09-20T18:07:25.377", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-09-16T20:15:10.377", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/avgpooling_op.cc#L56-L98"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mgmh-g2v6-mqw5"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-617"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/3a6ac52664c6c095aa2b114e742b0aa17fdce78f"}, "type": "CWE-617"}
109
Determine whether the {function_name} code is vulnerable or not.
[ "const Promise = require('bluebird');\nconst tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "", "const models = require('../../models');\nconst ALLOWED_INCLUDES = ['count.posts'];", "const messages = {\n notFound: 'Author not found.'\n};", "", "\nmodule.exports = {\n docName: 'authors',", " browse: {\n options: [\n 'include',\n 'filter',\n 'fields',\n 'limit',\n 'order',\n 'page'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Author.findPage(frame.options);", " }\n },", " read: {\n options: [\n 'include',\n 'filter',\n 'fields'\n ],\n data: [\n 'id',\n 'slug',\n 'email',\n 'role'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Author.findOne(frame.data, frame.options)", " .then((model) => {\n if (!model) {\n return Promise.reject(new errors.NotFoundError({\n message: tpl(messages.notFound)\n }));\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const Promise = require('bluebird');\nconst tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "const {mapQuery} = require('@tryghost/mongo-utils');", "const models = require('../../models');\nconst ALLOWED_INCLUDES = ['count.posts'];", "const messages = {\n notFound: 'Author not found.'\n};", "\nconst rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {\n const lowerCaseKey = key.toLowerCase();\n if (lowerCaseKey.startsWith('password') || lowerCaseKey.startsWith('email')) {\n return;\n }", " return {\n [key]: value\n };\n});", "\nmodule.exports = {\n docName: 'authors',", " browse: {\n options: [\n 'include',\n 'filter',\n 'fields',\n 'limit',\n 'order',\n 'page'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Author.findPage(options);", " }\n },", " read: {\n options: [\n 'include',\n 'filter',\n 'fields'\n ],\n data: [\n 'id',\n 'slug',\n 'email',\n 'role'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Author.findOne(frame.data, options)", " .then((model) => {\n if (!model) {\n return Promise.reject(new errors.NotFoundError({\n message: tpl(messages.notFound)\n }));\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "", "const models = require('../../models');", "const ALLOWED_INCLUDES = ['tags', 'authors', 'tiers'];", "const messages = {\n pageNotFound: 'Page not found.'\n};", "", "\nmodule.exports = {\n docName: 'pages',", " browse: {\n options: [\n 'include',\n 'filter',\n 'fields',\n 'formats',\n 'absolute_urls',\n 'page',\n 'limit',\n 'order',\n 'debug'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Post.findPage(frame.options);", " }\n },", " read: {\n options: [\n 'include',\n 'fields',\n 'formats',\n 'debug',\n 'absolute_urls'\n ],\n data: [\n 'id',\n 'slug',\n 'uuid'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Post.findOne(frame.data, frame.options)", " .then((model) => {\n if (!model) {\n throw new errors.NotFoundError({\n message: tpl(messages.pageNotFound)\n });\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "const {mapQuery} = require('@tryghost/mongo-utils');", "const models = require('../../models');", "const ALLOWED_INCLUDES = ['tags', 'authors', 'tiers'];", "const messages = {\n pageNotFound: 'Page not found.'\n};", "\nconst rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {\n let lowerCaseKey = key.toLowerCase();\n if (lowerCaseKey.startsWith('authors.password') || lowerCaseKey.startsWith('authors.email')) {\n return;\n }", " return {\n [key]: value\n };\n});", "\nmodule.exports = {\n docName: 'pages',", " browse: {\n options: [\n 'include',\n 'filter',\n 'fields',\n 'formats',\n 'absolute_urls',\n 'page',\n 'limit',\n 'order',\n 'debug'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Post.findPage(options);", " }\n },", " read: {\n options: [\n 'include',\n 'fields',\n 'formats',\n 'debug',\n 'absolute_urls'\n ],\n data: [\n 'id',\n 'slug',\n 'uuid'\n ],\n validation: {\n options: {\n include: {\n values: ALLOWED_INCLUDES\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Post.findOne(frame.data, options)", " .then((model) => {\n if (!model) {\n throw new errors.NotFoundError({\n message: tpl(messages.pageNotFound)\n });\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const models = require('../../models');\nconst tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "", "const postsPublicService = require('../../services/posts-public');", "const allowedIncludes = ['tags', 'authors', 'tiers', 'sentiment'];", "const messages = {\n postNotFound: 'Post not found.'\n};", "", "\nmodule.exports = {\n docName: 'posts',", " browse: {\n cache: postsPublicService.api?.cache,\n options: [\n 'include',\n 'filter',\n 'fields',\n 'formats',\n 'limit',\n 'order',\n 'page',\n 'debug',\n 'absolute_urls'\n ],\n validation: {\n options: {\n include: {\n values: allowedIncludes\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Post.findPage(frame.options);", " }\n },", " read: {\n options: [\n 'include',\n 'fields',\n 'formats',\n 'debug',\n 'absolute_urls'\n ],\n data: [\n 'id',\n 'slug',\n 'uuid'\n ],\n validation: {\n options: {\n include: {\n values: allowedIncludes\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " return models.Post.findOne(frame.data, frame.options)", " .then((model) => {\n if (!model) {\n throw new errors.NotFoundError({\n message: tpl(messages.postNotFound)\n });\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const models = require('../../models');\nconst tpl = require('@tryghost/tpl');\nconst errors = require('@tryghost/errors');", "const {mapQuery} = require('@tryghost/mongo-utils');", "const postsPublicService = require('../../services/posts-public');", "const allowedIncludes = ['tags', 'authors', 'tiers', 'sentiment'];", "const messages = {\n postNotFound: 'Post not found.'\n};", "\nconst rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {\n const lowerCaseKey = key.toLowerCase();\n if (lowerCaseKey.startsWith('authors.password') || lowerCaseKey.startsWith('authors.email')) {\n return;\n }", " return {\n [key]: value\n };\n});", "\nmodule.exports = {\n docName: 'posts',", " browse: {\n cache: postsPublicService.api?.cache,\n options: [\n 'include',\n 'filter',\n 'fields',\n 'formats',\n 'limit',\n 'order',\n 'page',\n 'debug',\n 'absolute_urls'\n ],\n validation: {\n options: {\n include: {\n values: allowedIncludes\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Post.findPage(options);", " }\n },", " read: {\n options: [\n 'include',\n 'fields',\n 'formats',\n 'debug',\n 'absolute_urls'\n ],\n data: [\n 'id',\n 'slug',\n 'uuid'\n ],\n validation: {\n options: {\n include: {\n values: allowedIncludes\n },\n formats: {\n values: models.Post.allowedFormats\n }\n }\n },\n permissions: true,\n query(frame) {", " const options = {\n ...frame.options,\n mongoTransformer: rejectPrivateFieldsTransformer\n };\n return models.Post.findOne(frame.data, options)", " .then((model) => {\n if (!model) {\n throw new errors.NotFoundError({\n message: tpl(messages.postNotFound)\n });\n }", " return model;\n });\n }\n }\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst localUtils = require('./utils');\nconst testUtils = require('../../../utils');\nconst configUtils = require('../../../utils/configUtils');\nconst config = require('../../../../core/shared/config');", "describe('Authors Content API', function () {\n const validKey = localUtils.getValidKey();\n let request;", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('owner:post', 'users', 'user:inactive', 'posts', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();", "", " });", " it('can read authors with fields', function () {\n return request.get(localUtils.API.getApiQuery(`authors/1/?key=${validKey}&fields=name`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n should.not.exist(res.headers['x-cache-invalidate']);", " // We don't expose any other attrs.\n localUtils.API.checkResponse(res.body.authors[0], 'author', null, null, ['id', 'name']);\n });\n });", " it('browse authors with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`authors/?key=${validKey}&filter=slug:[joe-bloggs,ghost,slimer-mcectoplasm]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.authors.should.be.an.Array().with.lengthOf(3);\n jsonResponse.authors[0].slug.should.equal('joe-bloggs');\n jsonResponse.authors[1].slug.should.equal('ghost');\n jsonResponse.authors[2].slug.should.equal('slimer-mcectoplasm');\n });\n });\n});" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst localUtils = require('./utils');\nconst testUtils = require('../../../utils');\nconst configUtils = require('../../../utils/configUtils');\nconst config = require('../../../../core/shared/config');", "describe('Authors Content API', function () {\n const validKey = localUtils.getValidKey();\n let request;", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('owner:post', 'users', 'user:inactive', 'posts', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();", " });", " it('can not filter authors by password', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: 'bruteforcepasswordtestuser@example.com',\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('slug', 'welcome');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`authors/?key=${validKey}&filter=password:'${hashedPassword}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.authors.length === 1) {\n throw new Error('fuck');\n }\n });", " it('can not filter authors by email', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userEmail = 'bruteforcepasswordtestuser@example.com';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: userEmail,\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('slug', 'welcome');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`authors/?key=${validKey}&filter=email:'${userEmail}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.authors.length === 1) {\n throw new Error('fuck');\n }", " });", " it('can read authors with fields', function () {\n return request.get(localUtils.API.getApiQuery(`authors/1/?key=${validKey}&fields=name`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n should.not.exist(res.headers['x-cache-invalidate']);", " // We don't expose any other attrs.\n localUtils.API.checkResponse(res.body.authors[0], 'author', null, null, ['id', 'name']);\n });\n });", " it('browse authors with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`authors/?key=${validKey}&filter=slug:[joe-bloggs,ghost,slimer-mcectoplasm]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.authors.should.be.an.Array().with.lengthOf(3);\n jsonResponse.authors[0].slug.should.equal('joe-bloggs');\n jsonResponse.authors[1].slug.should.equal('ghost');\n jsonResponse.authors[2].slug.should.equal('slimer-mcectoplasm');\n });\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst testUtils = require('../../../utils');\nconst localUtils = require('./utils');\nconst configUtils = require('../../../utils/configUtils');\nconst config = require('../../../../core/shared/config');", "let request;", "describe('api/endpoints/content/pages', function () {\n const key = localUtils.getValidKey();", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('users', 'user:inactive', 'posts', 'tags:extra', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();", "", " });", " it('Returns a validation error when unsupported \"page\" filter is used', function () {\n return request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=page:false`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.private)\n .expect(400);\n });", " it('browse pages with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=slug:[static-page-test]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.pages.should.be.an.Array().with.lengthOf(1);\n jsonResponse.pages[0].slug.should.equal('static-page-test');\n });\n });", " it('can\\'t read post', function () {\n return request\n .get(localUtils.API.getApiQuery(`pages/${testUtils.DataGenerator.Content.posts[0].id}/?key=${key}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.noCache)\n .expect(404);\n });\n});" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst testUtils = require('../../../utils');\nconst localUtils = require('./utils');\nconst configUtils = require('../../../utils/configUtils');\nconst config = require('../../../../core/shared/config');", "let request;", "describe('api/endpoints/content/pages', function () {\n const key = localUtils.getValidKey();", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('users', 'user:inactive', 'posts', 'tags:extra', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();", " });", " it('can not filter pages by author.password or authors.password', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: 'bruteforcepasswordtestuseremail@example.com',\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('type', 'page');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=authors.password:'${hashedPassword}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.pages.length === 1) {\n throw new Error('fuck');\n }\n });", " it('can not filter pages by author.email or authors.email', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userEmail = 'bruteforcepasswordtestuseremail@example.com';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: userEmail,\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('type', 'page');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=authors.email:'${userEmail}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.pages.length === 1) {\n throw new Error('fuck');\n }", " });", " it('Returns a validation error when unsupported \"page\" filter is used', function () {\n return request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=page:false`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.private)\n .expect(400);\n });", " it('browse pages with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`pages/?key=${key}&filter=slug:[static-page-test]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.pages.should.be.an.Array().with.lengthOf(1);\n jsonResponse.pages[0].slug.should.equal('static-page-test');\n });\n });", " it('can\\'t read post', function () {\n return request\n .get(localUtils.API.getApiQuery(`pages/${testUtils.DataGenerator.Content.posts[0].id}/?key=${key}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.noCache)\n .expect(404);\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst _ = require('lodash');\nconst testUtils = require('../../../utils');\nconst localUtils = require('./utils');\nconst configUtils = require('../../../utils/configUtils');\nconst urlUtils = require('../../../utils/urlUtils');\nconst config = require('../../../../core/shared/config');", "describe('api/endpoints/content/posts', function () {\n let request;", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('users', 'user:inactive', 'posts', 'tags:extra', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();\n urlUtils.restore();\n });", " const validKey = localUtils.getValidKey();", "", "\n it('browse posts', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(11);\n localUtils.API.checkResponse(jsonResponse.posts[0], 'post');\n localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " // Default order 'published_at desc' check\n jsonResponse.posts[0].slug.should.eql('welcome');\n jsonResponse.posts[6].slug.should.eql('integrations');", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(11);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);", " done();\n });\n });", " it('browse posts with related authors/tags also returns primary_author/primary_tag', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&include=authors,tags`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(11);\n localUtils.API.checkResponse(\n jsonResponse.posts[0],\n 'post',\n ['authors', 'tags', 'primary_tag', 'primary_author'],\n null\n );", " localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " // Default order 'published_at desc' check\n jsonResponse.posts[0].slug.should.eql('welcome');\n jsonResponse.posts[6].slug.should.eql('integrations');", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(11);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);", " done();\n });\n });", " it('browse posts with unsupported \"page\" filter returns a request validation error', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=page:true,featured:true`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.private)\n .expect(400);\n });", " it('browse posts with published and draft status, should not return drafts', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=status:published,status:draft`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(11);", " done();\n });\n });", " it('browse posts with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=slug:[write,ghostly-kitchen-sink,grow]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(3);\n jsonResponse.posts[0].slug.should.equal('write');\n jsonResponse.posts[1].slug.should.equal('ghostly-kitchen-sink');\n jsonResponse.posts[2].slug.should.equal('grow');\n });\n });", " it('browse posts with slug filter should order taking order parameter into account', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&order=slug%20DESC&filter=slug:[write,ghostly-kitchen-sink,grow]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(3);\n jsonResponse.posts[0].slug.should.equal('write');\n jsonResponse.posts[1].slug.should.equal('grow');\n jsonResponse.posts[2].slug.should.equal('ghostly-kitchen-sink');\n });\n });", " it('ensure origin header on redirect is not getting lost', function (done) {\n // NOTE: force a redirect to the admin url\n configUtils.set('admin:url', 'http://localhost:9999');\n urlUtils.stubUrlUtilsFromConfig();", " request.get(localUtils.API.getApiQuery(`posts?key=${validKey}`))\n .set('Origin', 'https://example.com')\n // 301 Redirects _should_ be cached\n .expect('Cache-Control', testUtils.cacheRules.year)\n .expect(301)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept, Accept-Encoding');\n res.headers.location.should.eql(`http://localhost:9999/ghost/api/content/posts/?key=${validKey}`);\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);\n done();\n });\n });", " it('can\\'t read page', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${testUtils.DataGenerator.Content.posts[5].id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.noCache)\n .expect(404);\n });", " it('can read post with fields', function () {\n const complexPostId = testUtils.DataGenerator.Content.posts.find(p => p.slug === 'not-so-short-bit-complex').id;", " return request\n .get(localUtils.API.getApiQuery(`posts/${complexPostId}/?key=${validKey}&fields=title,slug,excerpt&formats=plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n localUtils.API.checkResponse(res.body.posts[0], 'post', null, null, ['id', 'title', 'slug', 'excerpt', 'plaintext']);", " // excerpt should transform links to absolute URLs\n res.body.posts[0].excerpt.should.match(/\\* Aliquam/);\n });\n });", " describe('content gating', function () {\n let publicPost;\n let membersPost;\n let paidPost;\n let membersPostWithPaywallCard;", " before (function () {\n publicPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'free-to-see',\n visibility: 'public'\n });", " membersPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-not-be-seen',\n visibility: 'members'\n });", " paidPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-be-paid-for',\n visibility: 'paid'\n });", " membersPostWithPaywallCard = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-have-a-taste',\n visibility: 'members',\n mobiledoc: '{\"version\":\"0.3.1\",\"markups\":[],\"atoms\":[],\"cards\":[[\"paywall\",{}]],\"sections\":[[1,\"p\",[[0,[],0,\"Free content\"]]],[10,0],[1,\"p\",[[0,[],0,\"Members content\"]]]]}',\n html: '<p>Free content</p><!--members-only--><p>Members content</p>'\n });", " return testUtils.fixtures.insertPosts([\n publicPost,\n membersPost,\n paidPost,\n membersPostWithPaywallCard\n ]);\n });", " it('public post fields are always visible', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${publicPost.id}/?key=${validKey}&fields=slug,html,plaintext&formats=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null, ['id', 'slug', 'html', 'plaintext']);\n post.slug.should.eql('free-to-see');\n post.html.should.not.eql('');\n post.plaintext.should.not.eql('');\n });\n });", " it('cannot read members only post content', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPost.id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null);\n post.slug.should.eql('thou-shalt-not-be-seen');\n post.html.should.eql('');\n post.excerpt.should.eql('');\n });\n });", " it('cannot read paid only post content', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${paidPost.id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null);\n post.slug.should.eql('thou-shalt-be-paid-for');\n post.html.should.eql('');\n post.excerpt.should.eql('');\n });\n });", " it('cannot read members only post plaintext', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPost.id}/?key=${validKey}&formats=html,plaintext&fields=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null, ['id', 'html', 'plaintext']);\n post.html.should.eql('');\n post.plaintext.should.eql('');\n });\n });", " it('can read \"free\" html and plaintext content of members post when using paywall card', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPostWithPaywallCard.id}/?key=${validKey}&formats=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', ['plaintext']);\n post.html.should.eql('<p>Free content</p>');\n post.plaintext.should.eql('Free content');\n post.excerpt.should.eql('Free content');\n });\n });", " it('cannot browse members only posts content', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(15);\n localUtils.API.checkResponse(jsonResponse.posts[0], 'post', null, null);\n localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " const membersOnlySlugs = [\n 'thou-shalt-not-be-seen',\n 'thou-shalt-be-paid-for'\n ];", " const freeToSeeSlugs = [\n 'free-to-see',\n 'thou-shalt-have-a-taste',\n 'sell'\n ];", " let seen = 0;", " jsonResponse.posts.forEach((post) => {\n if (membersOnlySlugs.indexOf(post.slug) > -1) {\n post.html.should.eql('');\n post.excerpt.should.eql('');\n seen += 1;\n } else if (freeToSeeSlugs.indexOf(post.slug) > -1) {\n post.html.should.not.eql('');\n post.excerpt.should.not.eql('');\n seen += 1;\n }\n });", " seen.should.eql(membersOnlySlugs.length + freeToSeeSlugs.length);", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(15);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);\n });\n });\n });\n});" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "const should = require('should');\nconst supertest = require('supertest');\nconst _ = require('lodash');\nconst testUtils = require('../../../utils');\nconst localUtils = require('./utils');\nconst configUtils = require('../../../utils/configUtils');\nconst urlUtils = require('../../../utils/urlUtils');\nconst config = require('../../../../core/shared/config');", "describe('api/endpoints/content/posts', function () {\n let request;", " before(async function () {\n await localUtils.startGhost();\n request = supertest.agent(config.get('url'));\n await testUtils.initFixtures('users', 'user:inactive', 'posts', 'tags:extra', 'api_keys');\n });", " afterEach(async function () {\n await configUtils.restore();\n urlUtils.restore();\n });", " const validKey = localUtils.getValidKey();", "\n it('can not filter posts by author.password or authors.password', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: 'bruteforcepasswordtestuseremail@example.com',\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('slug', 'welcome');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=authors.password:'${hashedPassword}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.posts.length === 1) {\n throw new Error('fuck');\n }\n });", " it('can not filter posts by author.email or authors.email', async function () {\n const hashedPassword = '$2a$10$FxFlCsNBgXw42cBj0l1GFu39jffibqTqyAGBz7uCLwetYAdBYJEe6';\n const userEmail = 'bruteforcepasswordtestuseremail@example.com';\n const userId = '644fd18ca1f0b764b0279b2d';", " await testUtils.knex('users').insert({\n id: userId,\n slug: 'brute-force-password-test-user',\n name: 'Brute Force Password Test User',\n email: userEmail,\n password: hashedPassword,\n status: 'active',\n created_at: '2019-01-01 00:00:00',\n created_by: '1'\n });", " const {id: postId} = await testUtils.knex('posts').first('id').where('slug', 'welcome');", " await testUtils.knex('posts_authors').insert({\n id: '644fd18ca1f0b764b0279b2f',\n post_id: postId,\n author_id: userId\n });", " const res = await request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=authors.email:'${userEmail}'`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200);", " const data = JSON.parse(res.text);", " await testUtils.knex('posts_authors').where('id', '644fd18ca1f0b764b0279b2f').del();\n await testUtils.knex('users').where('id', userId).del();", " if (data.posts.length === 1) {\n throw new Error('fuck');\n }\n });", "\n it('browse posts', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(11);\n localUtils.API.checkResponse(jsonResponse.posts[0], 'post');\n localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " // Default order 'published_at desc' check\n jsonResponse.posts[0].slug.should.eql('welcome');\n jsonResponse.posts[6].slug.should.eql('integrations');", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(11);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);", " done();\n });\n });", " it('browse posts with related authors/tags also returns primary_author/primary_tag', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&include=authors,tags`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(11);\n localUtils.API.checkResponse(\n jsonResponse.posts[0],\n 'post',\n ['authors', 'tags', 'primary_tag', 'primary_author'],\n null\n );", " localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " // Default order 'published_at desc' check\n jsonResponse.posts[0].slug.should.eql('welcome');\n jsonResponse.posts[6].slug.should.eql('integrations');", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(11);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);", " done();\n });\n });", " it('browse posts with unsupported \"page\" filter returns a request validation error', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=page:true,featured:true`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.private)\n .expect(400);\n });", " it('browse posts with published and draft status, should not return drafts', function (done) {\n request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=status:published,status:draft`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(11);", " done();\n });\n });", " it('browse posts with slug filter, should order in slug order', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&filter=slug:[write,ghostly-kitchen-sink,grow]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(3);\n jsonResponse.posts[0].slug.should.equal('write');\n jsonResponse.posts[1].slug.should.equal('ghostly-kitchen-sink');\n jsonResponse.posts[2].slug.should.equal('grow');\n });\n });", " it('browse posts with slug filter should order taking order parameter into account', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}&order=slug%20DESC&filter=slug:[write,ghostly-kitchen-sink,grow]`))\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;", " jsonResponse.posts.should.be.an.Array().with.lengthOf(3);\n jsonResponse.posts[0].slug.should.equal('write');\n jsonResponse.posts[1].slug.should.equal('grow');\n jsonResponse.posts[2].slug.should.equal('ghostly-kitchen-sink');\n });\n });", " it('ensure origin header on redirect is not getting lost', function (done) {\n // NOTE: force a redirect to the admin url\n configUtils.set('admin:url', 'http://localhost:9999');\n urlUtils.stubUrlUtilsFromConfig();", " request.get(localUtils.API.getApiQuery(`posts?key=${validKey}`))\n .set('Origin', 'https://example.com')\n // 301 Redirects _should_ be cached\n .expect('Cache-Control', testUtils.cacheRules.year)\n .expect(301)\n .end(function (err, res) {\n if (err) {\n return done(err);\n }", " res.headers.vary.should.eql('Accept-Version, Accept, Accept-Encoding');\n res.headers.location.should.eql(`http://localhost:9999/ghost/api/content/posts/?key=${validKey}`);\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);\n done();\n });\n });", " it('can\\'t read page', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${testUtils.DataGenerator.Content.posts[5].id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.noCache)\n .expect(404);\n });", " it('can read post with fields', function () {\n const complexPostId = testUtils.DataGenerator.Content.posts.find(p => p.slug === 'not-so-short-bit-complex').id;", " return request\n .get(localUtils.API.getApiQuery(`posts/${complexPostId}/?key=${validKey}&fields=title,slug,excerpt&formats=plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n localUtils.API.checkResponse(res.body.posts[0], 'post', null, null, ['id', 'title', 'slug', 'excerpt', 'plaintext']);", " // excerpt should transform links to absolute URLs\n res.body.posts[0].excerpt.should.match(/\\* Aliquam/);\n });\n });", " describe('content gating', function () {\n let publicPost;\n let membersPost;\n let paidPost;\n let membersPostWithPaywallCard;", " before (function () {\n publicPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'free-to-see',\n visibility: 'public'\n });", " membersPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-not-be-seen',\n visibility: 'members'\n });", " paidPost = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-be-paid-for',\n visibility: 'paid'\n });", " membersPostWithPaywallCard = testUtils.DataGenerator.forKnex.createPost({\n slug: 'thou-shalt-have-a-taste',\n visibility: 'members',\n mobiledoc: '{\"version\":\"0.3.1\",\"markups\":[],\"atoms\":[],\"cards\":[[\"paywall\",{}]],\"sections\":[[1,\"p\",[[0,[],0,\"Free content\"]]],[10,0],[1,\"p\",[[0,[],0,\"Members content\"]]]]}',\n html: '<p>Free content</p><!--members-only--><p>Members content</p>'\n });", " return testUtils.fixtures.insertPosts([\n publicPost,\n membersPost,\n paidPost,\n membersPostWithPaywallCard\n ]);\n });", " it('public post fields are always visible', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${publicPost.id}/?key=${validKey}&fields=slug,html,plaintext&formats=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null, ['id', 'slug', 'html', 'plaintext']);\n post.slug.should.eql('free-to-see');\n post.html.should.not.eql('');\n post.plaintext.should.not.eql('');\n });\n });", " it('cannot read members only post content', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPost.id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null);\n post.slug.should.eql('thou-shalt-not-be-seen');\n post.html.should.eql('');\n post.excerpt.should.eql('');\n });\n });", " it('cannot read paid only post content', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${paidPost.id}/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null);\n post.slug.should.eql('thou-shalt-be-paid-for');\n post.html.should.eql('');\n post.excerpt.should.eql('');\n });\n });", " it('cannot read members only post plaintext', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPost.id}/?key=${validKey}&formats=html,plaintext&fields=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', null, null, ['id', 'html', 'plaintext']);\n post.html.should.eql('');\n post.plaintext.should.eql('');\n });\n });", " it('can read \"free\" html and plaintext content of members post when using paywall card', function () {\n return request\n .get(localUtils.API.getApiQuery(`posts/${membersPostWithPaywallCard.id}/?key=${validKey}&formats=html,plaintext`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n const post = jsonResponse.posts[0];", " localUtils.API.checkResponse(post, 'post', ['plaintext']);\n post.html.should.eql('<p>Free content</p>');\n post.plaintext.should.eql('Free content');\n post.excerpt.should.eql('Free content');\n });\n });", " it('cannot browse members only posts content', function () {\n return request.get(localUtils.API.getApiQuery(`posts/?key=${validKey}`))\n .set('Origin', testUtils.API.getURL())\n .expect('Content-Type', /json/)\n .expect('Cache-Control', testUtils.cacheRules.public)\n .expect(200)\n .then((res) => {\n res.headers.vary.should.eql('Accept-Version, Accept-Encoding');\n should.exist(res.headers['access-control-allow-origin']);\n should.not.exist(res.headers['x-cache-invalidate']);", " const jsonResponse = res.body;\n should.exist(jsonResponse.posts);\n localUtils.API.checkResponse(jsonResponse, 'posts');\n jsonResponse.posts.should.have.length(15);\n localUtils.API.checkResponse(jsonResponse.posts[0], 'post', null, null);\n localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination');\n _.isBoolean(jsonResponse.posts[0].featured).should.eql(true);", " const membersOnlySlugs = [\n 'thou-shalt-not-be-seen',\n 'thou-shalt-be-paid-for'\n ];", " const freeToSeeSlugs = [\n 'free-to-see',\n 'thou-shalt-have-a-taste',\n 'sell'\n ];", " let seen = 0;", " jsonResponse.posts.forEach((post) => {\n if (membersOnlySlugs.indexOf(post.slug) > -1) {\n post.html.should.eql('');\n post.excerpt.should.eql('');\n seen += 1;\n } else if (freeToSeeSlugs.indexOf(post.slug) > -1) {\n post.html.should.not.eql('');\n post.excerpt.should.not.eql('');\n seen += 1;\n }\n });", " seen.should.eql(membersOnlySlugs.length + freeToSeeSlugs.length);", " // check meta response for this test\n jsonResponse.meta.pagination.page.should.eql(1);\n jsonResponse.meta.pagination.limit.should.eql(15);\n jsonResponse.meta.pagination.pages.should.eql(1);\n jsonResponse.meta.pagination.total.should.eql(15);\n jsonResponse.meta.pagination.hasOwnProperty('next').should.be.true();\n jsonResponse.meta.pagination.hasOwnProperty('prev').should.be.true();\n should.not.exist(jsonResponse.meta.pagination.next);\n should.not.exist(jsonResponse.meta.pagination.prev);\n });\n });\n });\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "require('../../core/server/overrides');", "// Utility Packages\nconst {sequence} = require('@tryghost/promise');\nconst debug = require('@tryghost/debug')('test:utils');", "const _ = require('lodash');", "// Ghost Internals\nconst models = require('../../core/server/models');", "// Other Test Utilities\nconst e2eUtils = require('./e2e-utils');\nconst APIUtils = require('./api');\nconst dbUtils = require('./db-utils');\nconst fixtureUtils = require('./fixture-utils');\nconst redirects = require('./redirects');\nconst cacheRules = require('./fixtures/cache-rules');\nconst context = require('./fixtures/context');\nconst DataGenerator = require('./fixtures/data-generator');\nconst filterData = require('./fixtures/filter-param');", "// Require additional assertions which help us keep our tests small and clear\nrequire('./assertions');", "// ## Test Setup and Teardown", "const initFixtures = function initFixtures() {\n const options = _.merge({init: true}, _.transform(arguments, function (result, val) {\n result[val] = true;\n }));", " const fixtureOps = fixtureUtils.getFixtureOps(options);", " return sequence(fixtureOps);\n};", "/**\n * ## Setup Integration Tests\n * Setup takes a list of arguments like: 'default', 'tag', 'perms:tag', 'perms:init'\n * Setup does 'init' (DB) by default\n */\nconst setup = function setup() {\n /*eslint no-invalid-this: \"off\"*/\n const self = this;", " const args = arguments;", " return function innerSetup() {\n debug('Setup start');\n models.init();\n return initFixtures\n .apply(self, args)\n .finally(() => {\n debug('Setup end');\n });\n };\n};", "const createUser = function createUser(options) {\n const user = options.user;\n const role = options.role;", " return models.Role.fetchAll(context.internal)\n .then(function (roles) {\n roles = roles.toJSON();\n user.roles = [_.find(roles, {name: role})];", " return models.User.add(user, context.internal)\n .then(function () {\n return user;\n });\n });\n};", "const createPost = function createPost(options) {\n const post = DataGenerator.forKnex.createPost(options.post);", " return models.Post.add(post, context.internal);\n};", "const createEmail = function createEmail(options) {\n const email = DataGenerator.forKnex.createEmail(options.email);\n return models.Email.add(email, context.internal);\n};", "const createEmailedPost = async function createEmailedPost({postOptions, emailOptions}) {\n const post = await createPost(postOptions);\n emailOptions.email.post_id = post.id;\n const email = await createEmail(emailOptions);", " return {post, email};\n};", "module.exports = {\n startGhost: e2eUtils.startGhost,\n stopGhost: e2eUtils.stopGhost,\n getExistingData: e2eUtils.getExistingData,", " teardownDb: dbUtils.teardown,\n truncate: dbUtils.truncate,", "", " setup: setup,\n createUser: createUser,\n createPost: createPost,\n createEmailedPost,", " /**\n * renderObject: res.render(view, dbResponse)\n * templateOptions: hbs.updateTemplateOptions(...)\n */\n createHbsResponse: function createHbsResponse(options) {\n const renderObject = options.renderObject || {};\n const templateOptions = options.templateOptions;\n const locals = options.locals || {};", " const hbsStructure = {\n data: {\n site: {},\n config: {},\n labs: {},\n root: {\n _locals: {}\n }\n }\n };", " _.merge(hbsStructure.data, templateOptions);\n _.merge(hbsStructure.data.root, renderObject);\n _.merge(hbsStructure.data.root, locals);\n hbsStructure.data.root._locals = locals;", " return hbsStructure;\n },", " initFixtures: initFixtures,\n initData: dbUtils.initData,\n clearData: dbUtils.clearData,\n setupRedirectsFile: redirects.setupFile,", " fixtures: fixtureUtils.fixtures,", " DataGenerator: DataGenerator,\n filterData: filterData,\n API: APIUtils({getFixtureOps: fixtureUtils.getFixtureOps}),", " // Helpers to make it easier to write tests which are easy to read\n context: context,\n permissions: {\n owner: {user: {roles: [DataGenerator.Content.roles[3]]}},\n admin: {user: {roles: [DataGenerator.Content.roles[0]]}},\n editor: {user: {roles: [DataGenerator.Content.roles[1]]}},\n author: {user: {roles: [DataGenerator.Content.roles[2]]}},\n contributor: {user: {roles: [DataGenerator.Content.roles[4]]}}\n },\n roles: {\n ids: {\n owner: DataGenerator.Content.roles[3].id,\n admin: DataGenerator.Content.roles[0].id,\n editor: DataGenerator.Content.roles[1].id,\n author: DataGenerator.Content.roles[2].id,\n contributor: DataGenerator.Content.roles[4].id\n }\n },\n cacheRules: cacheRules\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "require('../../core/server/overrides');", "// Utility Packages\nconst {sequence} = require('@tryghost/promise');\nconst debug = require('@tryghost/debug')('test:utils');", "const _ = require('lodash');", "// Ghost Internals\nconst models = require('../../core/server/models');", "// Other Test Utilities\nconst e2eUtils = require('./e2e-utils');\nconst APIUtils = require('./api');\nconst dbUtils = require('./db-utils');\nconst fixtureUtils = require('./fixture-utils');\nconst redirects = require('./redirects');\nconst cacheRules = require('./fixtures/cache-rules');\nconst context = require('./fixtures/context');\nconst DataGenerator = require('./fixtures/data-generator');\nconst filterData = require('./fixtures/filter-param');", "// Require additional assertions which help us keep our tests small and clear\nrequire('./assertions');", "// ## Test Setup and Teardown", "const initFixtures = function initFixtures() {\n const options = _.merge({init: true}, _.transform(arguments, function (result, val) {\n result[val] = true;\n }));", " const fixtureOps = fixtureUtils.getFixtureOps(options);", " return sequence(fixtureOps);\n};", "/**\n * ## Setup Integration Tests\n * Setup takes a list of arguments like: 'default', 'tag', 'perms:tag', 'perms:init'\n * Setup does 'init' (DB) by default\n */\nconst setup = function setup() {\n /*eslint no-invalid-this: \"off\"*/\n const self = this;", " const args = arguments;", " return function innerSetup() {\n debug('Setup start');\n models.init();\n return initFixtures\n .apply(self, args)\n .finally(() => {\n debug('Setup end');\n });\n };\n};", "const createUser = function createUser(options) {\n const user = options.user;\n const role = options.role;", " return models.Role.fetchAll(context.internal)\n .then(function (roles) {\n roles = roles.toJSON();\n user.roles = [_.find(roles, {name: role})];", " return models.User.add(user, context.internal)\n .then(function () {\n return user;\n });\n });\n};", "const createPost = function createPost(options) {\n const post = DataGenerator.forKnex.createPost(options.post);", " return models.Post.add(post, context.internal);\n};", "const createEmail = function createEmail(options) {\n const email = DataGenerator.forKnex.createEmail(options.email);\n return models.Email.add(email, context.internal);\n};", "const createEmailedPost = async function createEmailedPost({postOptions, emailOptions}) {\n const post = await createPost(postOptions);\n emailOptions.email.post_id = post.id;\n const email = await createEmail(emailOptions);", " return {post, email};\n};", "module.exports = {\n startGhost: e2eUtils.startGhost,\n stopGhost: e2eUtils.stopGhost,\n getExistingData: e2eUtils.getExistingData,", " teardownDb: dbUtils.teardown,\n truncate: dbUtils.truncate,", " knex: dbUtils.knex,", " setup: setup,\n createUser: createUser,\n createPost: createPost,\n createEmailedPost,", " /**\n * renderObject: res.render(view, dbResponse)\n * templateOptions: hbs.updateTemplateOptions(...)\n */\n createHbsResponse: function createHbsResponse(options) {\n const renderObject = options.renderObject || {};\n const templateOptions = options.templateOptions;\n const locals = options.locals || {};", " const hbsStructure = {\n data: {\n site: {},\n config: {},\n labs: {},\n root: {\n _locals: {}\n }\n }\n };", " _.merge(hbsStructure.data, templateOptions);\n _.merge(hbsStructure.data.root, renderObject);\n _.merge(hbsStructure.data.root, locals);\n hbsStructure.data.root._locals = locals;", " return hbsStructure;\n },", " initFixtures: initFixtures,\n initData: dbUtils.initData,\n clearData: dbUtils.clearData,\n setupRedirectsFile: redirects.setupFile,", " fixtures: fixtureUtils.fixtures,", " DataGenerator: DataGenerator,\n filterData: filterData,\n API: APIUtils({getFixtureOps: fixtureUtils.getFixtureOps}),", " // Helpers to make it easier to write tests which are easy to read\n context: context,\n permissions: {\n owner: {user: {roles: [DataGenerator.Content.roles[3]]}},\n admin: {user: {roles: [DataGenerator.Content.roles[0]]}},\n editor: {user: {roles: [DataGenerator.Content.roles[1]]}},\n author: {user: {roles: [DataGenerator.Content.roles[2]]}},\n contributor: {user: {roles: [DataGenerator.Content.roles[4]]}}\n },\n roles: {\n ids: {\n owner: DataGenerator.Content.roles[3].id,\n admin: DataGenerator.Content.roles[0].id,\n editor: DataGenerator.Content.roles[1].id,\n author: DataGenerator.Content.roles[2].id,\n contributor: DataGenerator.Content.roles[4].id\n }\n },\n cacheRules: cacheRules\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58, 68, 70, 19, 20, 24, 101], "buggy_code_start_loc": [3, 2, 3, 19, 20, 24, 101], "filenames": ["ghost/core/core/server/api/endpoints/authors-public.js", "ghost/core/core/server/api/endpoints/pages-public.js", "ghost/core/core/server/api/endpoints/posts-public.js", "ghost/core/test/regression/api/content/authors.test.js", "ghost/core/test/regression/api/content/pages.test.js", "ghost/core/test/regression/api/content/posts.test.js", "ghost/core/test/utils/index.js"], "fixing_code_end_loc": [78, 88, 90, 99, 100, 104, 103], "fixing_code_start_loc": [4, 3, 4, 20, 21, 25, 102], "message": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ghost:ghost:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "019CF5DA-91CB-485C-8C00-7E82585A682E", "versionEndExcluding": "5.46.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ghost is an app for new-media creators with tools to build a website, publish content, send newsletters, and offer paid subscriptions to members. Prior to version 5.46.1, due to a lack of validation when filtering on the public API endpoints, it is possible to reveal private fields via a brute force attack.\n\nGhost(Pro) has already been patched. Maintainers can find no evidence that the issue was exploited on Ghost(Pro) prior to the patch being added. Self-hosters are impacted if running Ghost a version below v5.46.1. v5.46.1 contains a fix for this issue. As a workaround, add a block for requests to `/ghost/api/content/*` where the `filter` query parameter contains `password` or `email`."}], "evaluatorComment": null, "id": "CVE-2023-31133", "lastModified": "2023-05-15T18:19:28.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-08T21:15:11.600", "references": [{"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, {"source": "security-advisories@github.com", "tags": ["Release Notes"], "url": "https://github.com/TryGhost/Ghost/releases/tag/v5.46.1"}, {"source": "security-advisories@github.com", "tags": ["Vendor Advisory"], "url": "https://github.com/TryGhost/Ghost/security/advisories/GHSA-r97q-ghch-82j9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/TryGhost/Ghost/commit/b3caf16005289cc9909488391b4a26f3f4a66a90"}, "type": "NVD-CWE-noinfo"}
110
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title\" id=\"myModalLabel\">\n <span class=\"material-icons\">info_outline</span>&nbsp;<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Build your avatar')?>\n </h4>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n <div class=\"modal-body\">", " <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','We will generate avatar based on this string if you do not choose some parts')?></label>\n <input type=\"text\" id=\"id_avatar_string_construct\" class=\"form-control form-control-sm\" value=\"<?php echo htmlspecialchars($id)?>\">\n </div>", " <?php $partsNames = [\n 'clo' => 'Clothes',\n 'head' => 'Head',\n 'mouth' => 'Mouth',\n 'eyes' => 'Eyes',\n 'top' => 'Top'];\n foreach (['clo','head','mouth','eyes','top'] as $item) : ?>\n <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo htmlspecialchars($partsNames[$item])?></label>\n <select id=\"scope_<?php echo $item?>\" class=\"form-control form-control-sm avatar-scope\">\n <option value=\"\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Choose')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '00') : ?>selected=\"selected\"<?php endif; ?> value=\"00\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Robo')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '01') : ?>selected=\"selected\"<?php endif; ?> value=\"01\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Girl')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '02') : ?>selected=\"selected\"<?php endif; ?> value=\"02\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Blonde')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '03') : ?>selected=\"selected\"<?php endif; ?> value=\"03\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Evilnormie')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '04') : ?>selected=\"selected\"<?php endif; ?> value=\"04\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Country')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '05') : ?>selected=\"selected\"<?php endif; ?> value=\"05\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Johnyold')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '06') : ?>selected=\"selected\"<?php endif; ?> value=\"06\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Asian')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '07') : ?>selected=\"selected\"<?php endif; ?> value=\"07\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Punk')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '08') : ?>selected=\"selected\"<?php endif; ?> value=\"08\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Afrohair')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '09') : ?>selected=\"selected\"<?php endif; ?> value=\"09\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Normie female')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '10') : ?>selected=\"selected\"<?php endif; ?> value=\"10\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Older')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '11') : ?>selected=\"selected\"<?php endif; ?> value=\"11\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Firehair')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '12') : ?>selected=\"selected\"<?php endif; ?> value=\"12\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Blond')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '13') : ?>selected=\"selected\"<?php endif; ?> value=\"13\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Ateam')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '14') : ?>selected=\"selected\"<?php endif; ?> value=\"14\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Rasta')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '15') : ?>selected=\"selected\"<?php endif; ?> value=\"15\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Meta')?></option>\n </select>\n </div>\n </div>\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Color')?></label>\n <select id=\"variant_<?php echo $item?>\" class=\"form-control form-control-sm avatar-variant\">\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'A') : ?>selected=\"selected\"<?php endif; ?> value=\"A\">A</option>\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'B') : ?>selected=\"selected\"<?php endif; ?> value=\"B\">B</option>\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'C') : ?>selected=\"selected\"<?php endif; ?> value=\"C\">C</option>\n </select>\n </div>\n </div>\n </div>\n <?php endforeach; ?>\n </div>\n <div class=\"col-6\">", " <img width=\"w-100\" id=\"id_avatar_img\" src='<?php echo erLhcoreClassDesign::baseurl('widgetrestapi/avatar')?>/<?php echo htmlspecialchars($id)?>' alt=\"\" title=\"\" />", " </div>\n </div>", " <div class=\"row\">\n <div class=\"col-12\">\n <button type=\"button\" id=\"set_avatar_action\" class=\"btn btn-secondary\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Set')?></button>\n </div>\n </div>", " <script>\n (function() {\n var avatarString = '';", " function buildAvatar() {\n avatarString = $('#id_avatar_string_construct').val() != '' ? $('#id_avatar_string_construct').val() : 'tmp';\n var elements = ['clo','head','mouth','eyes','top'];\n elements.forEach(function(item) {\n if ($('#scope_' + item).val() != '') {\n avatarString += '__' + item.substr(0,1) +'_'+$('#scope_' + item).val()+'_'+$('#variant_' + item).val();\n }\n });\n $('#id_avatar_img').attr('src','<?php echo erLhcoreClassDesign::baseurl('widgetrestapi/avatar')?>'+'/'+avatarString);\n }", " $('.avatar-scope, .avatar-variant').change(function(){\n buildAvatar();\n });", " $('#id_avatar_string_construct').keyup(function(){\n buildAvatar();\n });", " $('#set_avatar_action').click(function(){\n $('#<?php echo htmlspecialchars($prefix)?>id_avatar_string').val(avatarString);\n $('#<?php echo htmlspecialchars($prefix)?>avatar_string_img').attr('src',$('#id_avatar_img').attr('src'));\n $('#myModal').modal('hide');\n });", " buildAvatar();", " })();\n </script>", "<?php include(erLhcoreClassDesign::designtpl('lhkernel/modal_footer.tpl.php'));?>" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [67, 5], "buggy_code_start_loc": [66, 4], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/avatarbuilder.tpl.php", "lhc_web/modules/lhuser/avatarbuilder.php"], "fixing_code_end_loc": [67, 5], "fixing_code_start_loc": [66, 4], "message": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "5F68A743-8655-4AE7-9E50-75FF9F872F55", "versionEndExcluding": null, "versionEndIncluding": "3.90", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "livehelperchat es vulnerable a una Neutralizaci\u00f3n Inapropiada de la Entrada Durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-4169", "lastModified": "2021-12-30T21:07:23.753", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-26T12:15:07.753", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/91bbb411-6502-4dc1-8b59-b31f7d1c1f72"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, "type": "CWE-79"}
111
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title\" id=\"myModalLabel\">\n <span class=\"material-icons\">info_outline</span>&nbsp;<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Build your avatar')?>\n </h4>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n <div class=\"modal-body\">", " <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','We will generate avatar based on this string if you do not choose some parts')?></label>\n <input type=\"text\" id=\"id_avatar_string_construct\" class=\"form-control form-control-sm\" value=\"<?php echo htmlspecialchars($id)?>\">\n </div>", " <?php $partsNames = [\n 'clo' => 'Clothes',\n 'head' => 'Head',\n 'mouth' => 'Mouth',\n 'eyes' => 'Eyes',\n 'top' => 'Top'];\n foreach (['clo','head','mouth','eyes','top'] as $item) : ?>\n <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo htmlspecialchars($partsNames[$item])?></label>\n <select id=\"scope_<?php echo $item?>\" class=\"form-control form-control-sm avatar-scope\">\n <option value=\"\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Choose')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '00') : ?>selected=\"selected\"<?php endif; ?> value=\"00\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Robo')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '01') : ?>selected=\"selected\"<?php endif; ?> value=\"01\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Girl')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '02') : ?>selected=\"selected\"<?php endif; ?> value=\"02\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Blonde')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '03') : ?>selected=\"selected\"<?php endif; ?> value=\"03\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Evilnormie')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '04') : ?>selected=\"selected\"<?php endif; ?> value=\"04\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Country')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '05') : ?>selected=\"selected\"<?php endif; ?> value=\"05\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Johnyold')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '06') : ?>selected=\"selected\"<?php endif; ?> value=\"06\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Asian')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '07') : ?>selected=\"selected\"<?php endif; ?> value=\"07\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Punk')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '08') : ?>selected=\"selected\"<?php endif; ?> value=\"08\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Afrohair')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '09') : ?>selected=\"selected\"<?php endif; ?> value=\"09\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Normie female')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '10') : ?>selected=\"selected\"<?php endif; ?> value=\"10\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Older')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '11') : ?>selected=\"selected\"<?php endif; ?> value=\"11\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Firehair')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '12') : ?>selected=\"selected\"<?php endif; ?> value=\"12\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Blond')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '13') : ?>selected=\"selected\"<?php endif; ?> value=\"13\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Ateam')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '14') : ?>selected=\"selected\"<?php endif; ?> value=\"14\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Rasta')?></option>\n <option <?php if (isset($props[$item]['part']) && $props[$item]['part'] === '15') : ?>selected=\"selected\"<?php endif; ?> value=\"15\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Meta')?></option>\n </select>\n </div>\n </div>\n <div class=\"col-6\">\n <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Color')?></label>\n <select id=\"variant_<?php echo $item?>\" class=\"form-control form-control-sm avatar-variant\">\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'A') : ?>selected=\"selected\"<?php endif; ?> value=\"A\">A</option>\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'B') : ?>selected=\"selected\"<?php endif; ?> value=\"B\">B</option>\n <option <?php if (isset($props[$item]['theme']) && $props[$item]['theme'] === 'C') : ?>selected=\"selected\"<?php endif; ?> value=\"C\">C</option>\n </select>\n </div>\n </div>\n </div>\n <?php endforeach; ?>\n </div>\n <div class=\"col-6\">", " <img width=\"w-100\" id=\"id_avatar_img\" src='<?php echo erLhcoreClassDesign::baseurl('widgetrestapi/avatar')?>/<?php echo urlencode(htmlspecialchars($id))?>' alt=\"\" title=\"\" />", " </div>\n </div>", " <div class=\"row\">\n <div class=\"col-12\">\n <button type=\"button\" id=\"set_avatar_action\" class=\"btn btn-secondary\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/avatarbuilder','Set')?></button>\n </div>\n </div>", " <script>\n (function() {\n var avatarString = '';", " function buildAvatar() {\n avatarString = $('#id_avatar_string_construct').val() != '' ? $('#id_avatar_string_construct').val() : 'tmp';\n var elements = ['clo','head','mouth','eyes','top'];\n elements.forEach(function(item) {\n if ($('#scope_' + item).val() != '') {\n avatarString += '__' + item.substr(0,1) +'_'+$('#scope_' + item).val()+'_'+$('#variant_' + item).val();\n }\n });\n $('#id_avatar_img').attr('src','<?php echo erLhcoreClassDesign::baseurl('widgetrestapi/avatar')?>'+'/'+avatarString);\n }", " $('.avatar-scope, .avatar-variant').change(function(){\n buildAvatar();\n });", " $('#id_avatar_string_construct').keyup(function(){\n buildAvatar();\n });", " $('#set_avatar_action').click(function(){\n $('#<?php echo htmlspecialchars($prefix)?>id_avatar_string').val(avatarString);\n $('#<?php echo htmlspecialchars($prefix)?>avatar_string_img').attr('src',$('#id_avatar_img').attr('src'));\n $('#myModal').modal('hide');\n });", " buildAvatar();", " })();\n </script>", "<?php include(erLhcoreClassDesign::designtpl('lhkernel/modal_footer.tpl.php'));?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [67, 5], "buggy_code_start_loc": [66, 4], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/avatarbuilder.tpl.php", "lhc_web/modules/lhuser/avatarbuilder.php"], "fixing_code_end_loc": [67, 5], "fixing_code_start_loc": [66, 4], "message": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "5F68A743-8655-4AE7-9E50-75FF9F872F55", "versionEndExcluding": null, "versionEndIncluding": "3.90", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "livehelperchat es vulnerable a una Neutralizaci\u00f3n Inapropiada de la Entrada Durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-4169", "lastModified": "2021-12-30T21:07:23.753", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-26T12:15:07.753", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/91bbb411-6502-4dc1-8b59-b31f7d1c1f72"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, "type": "CWE-79"}
111
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n$tpl = erLhcoreClassTemplate::getInstance('lhchat/avatarbuilder.tpl.php');\n", "$id = $Params['user_parameters']['id'];", "\n$prefix = isset($_GET['prefix']) ? strip_tags($_GET['prefix']) : '';", "if (empty($id)) {\n $id = erLhcoreClassModelForgotPassword::randomPassword();\n} else {\n $idProps = explode('__', $id);\n $id = $idProps[0];", " $propsMapping = [\n 'c' => 'clo',\n 'h' => 'head',\n 'm' => 'mouth',\n 'e' => 'eyes',\n 't' => 'top',\n ];", " $ver = null;", " foreach ($idProps as $prop) {\n $propParts = explode('_', $prop);", " if (count($propParts) == 3) {\n if (isset($propsMapping[$propParts[0]])) {\n $ver[$propsMapping[$propParts[0]]] = ['part' => $propParts[1], 'theme' => $propParts[2]];\n }\n }\n }", " $tpl->set('props',$ver);\n}", "$tpl->set('id',$id);\n$tpl->set('prefix',$prefix);", "echo $tpl->fetch();\nexit();", "?>" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [67, 5], "buggy_code_start_loc": [66, 4], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/avatarbuilder.tpl.php", "lhc_web/modules/lhuser/avatarbuilder.php"], "fixing_code_end_loc": [67, 5], "fixing_code_start_loc": [66, 4], "message": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "5F68A743-8655-4AE7-9E50-75FF9F872F55", "versionEndExcluding": null, "versionEndIncluding": "3.90", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "livehelperchat es vulnerable a una Neutralizaci\u00f3n Inapropiada de la Entrada Durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-4169", "lastModified": "2021-12-30T21:07:23.753", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-26T12:15:07.753", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/91bbb411-6502-4dc1-8b59-b31f7d1c1f72"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, "type": "CWE-79"}
111
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n$tpl = erLhcoreClassTemplate::getInstance('lhchat/avatarbuilder.tpl.php');\n", "$id = strip_tags($Params['user_parameters']['id']);", "\n$prefix = isset($_GET['prefix']) ? strip_tags($_GET['prefix']) : '';", "if (empty($id)) {\n $id = erLhcoreClassModelForgotPassword::randomPassword();\n} else {\n $idProps = explode('__', $id);\n $id = $idProps[0];", " $propsMapping = [\n 'c' => 'clo',\n 'h' => 'head',\n 'm' => 'mouth',\n 'e' => 'eyes',\n 't' => 'top',\n ];", " $ver = null;", " foreach ($idProps as $prop) {\n $propParts = explode('_', $prop);", " if (count($propParts) == 3) {\n if (isset($propsMapping[$propParts[0]])) {\n $ver[$propsMapping[$propParts[0]]] = ['part' => $propParts[1], 'theme' => $propParts[2]];\n }\n }\n }", " $tpl->set('props',$ver);\n}", "$tpl->set('id',$id);\n$tpl->set('prefix',$prefix);", "echo $tpl->fetch();\nexit();", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [67, 5], "buggy_code_start_loc": [66, 4], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/avatarbuilder.tpl.php", "lhc_web/modules/lhuser/avatarbuilder.php"], "fixing_code_end_loc": [67, 5], "fixing_code_start_loc": [66, 4], "message": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "5F68A743-8655-4AE7-9E50-75FF9F872F55", "versionEndExcluding": null, "versionEndIncluding": "3.90", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"}, {"lang": "es", "value": "livehelperchat es vulnerable a una Neutralizaci\u00f3n Inapropiada de la Entrada Durante la Generaci\u00f3n de la P\u00e1gina Web (\"Cross-site Scripting\")"}], "evaluatorComment": null, "id": "CVE-2021-4169", "lastModified": "2021-12-30T21:07:23.753", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-26T12:15:07.753", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/91bbb411-6502-4dc1-8b59-b31f7d1c1f72"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/8f6ddadffcd683c16fbbe622acf374eea1e39c74"}, "type": "CWE-79"}
111
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Patient matching and selection dialog.\n *\n * @package OpenEMR\n * @link https://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2013-2015 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(\"../globals.php\");\nrequire_once(\"$srcdir/patient.inc\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;", "$form_key = $_REQUEST['key'];\n$args = unserialize($form_key, ['allowed_classes' => false]);\n$form_ss = preg_replace('/[^0-9]/', '', $args['ss']);\n$form_fname = $args['fname'];\n$form_lname = $args['lname'];\n$form_DOB = $args['DOB'];\n?>\n<!DOCTYPE html>\n<html>\n<head>\n<?php Header::setupHeader(['opener']); ?>\n<style>\n .oneResult {\n }\n</style>\n<script>", " $(function () {\n $(\".oneresult\").mouseover(function () {\n $(this).addClass(\"highlight\");\n });\n $(\".oneresult\").mouseout(function () {\n $(this).removeClass(\"highlight\");\n });\n });", " function myRestoreSession() {\n if (top.restoreSession) top.restoreSession(); else opener.top.restoreSession();\n return true;\n }", " function openPatient(ptid) {\n var f = opener.document.forms[0];", " var ename = '<?php echo addslashes(\"select[$form_key]\"); ?>';", " if (f[ename]) {\n f[ename].value = ptid;\n window.close();\n }\n else {\n alert(<?php echo xlj('Form element not found'); ?> + ': ' + ename);\n }\n }", "</script>\n</head>", "<body class=\"body_top\">\n<form method='post' action='patient_select.php' onsubmit='return myRestoreSession()'>\n<input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n<?php\nif ($form_key) {\n $clarr = array();\n $clsql = \"0\";\n// First name.\n if ($form_fname !== '') {\n $clsql .= \" + ((fname IS NOT NULL AND fname = ?) * 5)\";\n $clarr[] = $form_fname;\n }", "// Last name.\n if ($form_lname !== '') {\n $clsql .= \" + ((lname IS NOT NULL AND lname = ?) * 5)\";\n $clarr[] = $form_lname;\n }", "// Birth date.\n if ($form_DOB !== '') {\n $clsql .= \" + ((DOB IS NOT NULL AND DOB = ?) * 5)\";\n $clarr[] = $form_DOB;\n }", "// SSN match is worth a lot and we allow for matching on last 4 digits.\n if (strlen($form_ss) > 3) {\n $clsql .= \" + ((ss IS NOT NULL AND ss LIKE ?) * 10)\";\n $clarr[] = \"%$form_ss\";\n }", " $sql = \"SELECT $clsql AS closeness, \" .\n \"pid, pubpid, fname, lname, mname, DOB, ss, postal_code, street, \" .\n \"phone_biz, phone_home, phone_cell, phone_contact \" .\n \"FROM patient_data \" .\n \"ORDER BY closeness DESC, lname, fname LIMIT 10\";\n $res = sqlStatement($sql, $clarr);\n ?>", " <div id=\"searchResults\">", " <table class=\"table table-striped table-sm\">\n <h5>\n <?php\n echo xlt('Matching for Patient') . \": \" .\n text(\"$form_lname, $form_fname\") . text(\" Dob = $form_DOB\") .\n \" SS = \" . text(($form_ss ? $form_ss : \"unk\"))\n ?>\n </h5>\n <tr>\n <th><?php echo xlt('Name'); ?></th>\n <th><?php echo xlt('Phone'); ?></th>\n <th><?php echo xlt('SS'); ?></th>\n <th><?php echo xlt('DOB'); ?></th>\n <th><?php echo xlt('Address'); ?></th>\n </tr>", " <?php\n while ($row = sqlFetchArray($res)) {\n if ($row['closeness'] == 0) {\n continue;\n }", " $phone = $row['phone_biz'];\n if (empty($phone)) {\n $phone = $row['phone_home'];\n }", " if (empty($phone)) {\n $phone = $row['phone_cell'];\n }", " if (empty($phone)) {\n $phone = $row['phone_contact'];\n }", " echo \" <tr class='oneresult'\";\n echo \" onclick=\\\"openPatient(\" . attr_js($row['pid']) . \")\\\">\\n\";\n echo \" <td>\" . text($row['lname'] . \", \" . $row['fname']) . \"</td>\\n\";\n echo \" <td>\" . text($phone) . \"</td>\\n\";\n echo \" <td>\" . text($row['ss']) . \"</td>\\n\";\n echo \" <td>\" . text($row['DOB']) . \"</td>\\n\";\n echo \" <td>\" . text($row['street'] . ' ' . $row['postal_code']) . \"</td>\\n\";\n echo \" </tr>\\n\";\n }\n ?>\n </table>\n </div>\n <?php\n}\n?>", "<p>\n <input type='button' value='<?php echo xla('Add New Patient'); ?>' onclick=\"openPatient(0)\"/>\n <input type='button' value='<?php echo xla('Cancel'); ?>' onclick=\"window.close()\"/>\n</p>", "</form>\n</center>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Patient matching and selection dialog.\n *\n * @package OpenEMR\n * @link https://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2013-2015 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(\"../globals.php\");\nrequire_once(\"$srcdir/patient.inc\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;", "$form_key = $_REQUEST['key'];\n$args = unserialize($form_key, ['allowed_classes' => false]);\n$form_ss = preg_replace('/[^0-9]/', '', $args['ss']);\n$form_fname = $args['fname'];\n$form_lname = $args['lname'];\n$form_DOB = $args['DOB'];\n?>\n<!DOCTYPE html>\n<html>\n<head>\n<?php Header::setupHeader(['opener']); ?>\n<style>\n .oneResult {\n }\n</style>\n<script>", " $(function () {\n $(\".oneresult\").mouseover(function () {\n $(this).addClass(\"highlight\");\n });\n $(\".oneresult\").mouseout(function () {\n $(this).removeClass(\"highlight\");\n });\n });", " function myRestoreSession() {\n if (top.restoreSession) top.restoreSession(); else opener.top.restoreSession();\n return true;\n }", " function openPatient(ptid) {\n var f = opener.document.forms[0];", " var ename = <?php echo js_escape(\"select[$form_key]\"); ?>;", " if (f[ename]) {\n f[ename].value = ptid;\n window.close();\n }\n else {\n alert(<?php echo xlj('Form element not found'); ?> + ': ' + ename);\n }\n }", "</script>\n</head>", "<body class=\"body_top\">\n<form method='post' action='patient_select.php' onsubmit='return myRestoreSession()'>\n<input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n<?php\nif ($form_key) {\n $clarr = array();\n $clsql = \"0\";\n// First name.\n if ($form_fname !== '') {\n $clsql .= \" + ((fname IS NOT NULL AND fname = ?) * 5)\";\n $clarr[] = $form_fname;\n }", "// Last name.\n if ($form_lname !== '') {\n $clsql .= \" + ((lname IS NOT NULL AND lname = ?) * 5)\";\n $clarr[] = $form_lname;\n }", "// Birth date.\n if ($form_DOB !== '') {\n $clsql .= \" + ((DOB IS NOT NULL AND DOB = ?) * 5)\";\n $clarr[] = $form_DOB;\n }", "// SSN match is worth a lot and we allow for matching on last 4 digits.\n if (strlen($form_ss) > 3) {\n $clsql .= \" + ((ss IS NOT NULL AND ss LIKE ?) * 10)\";\n $clarr[] = \"%$form_ss\";\n }", " $sql = \"SELECT $clsql AS closeness, \" .\n \"pid, pubpid, fname, lname, mname, DOB, ss, postal_code, street, \" .\n \"phone_biz, phone_home, phone_cell, phone_contact \" .\n \"FROM patient_data \" .\n \"ORDER BY closeness DESC, lname, fname LIMIT 10\";\n $res = sqlStatement($sql, $clarr);\n ?>", " <div id=\"searchResults\">", " <table class=\"table table-striped table-sm\">\n <h5>\n <?php\n echo xlt('Matching for Patient') . \": \" .\n text(\"$form_lname, $form_fname\") . text(\" Dob = $form_DOB\") .\n \" SS = \" . text(($form_ss ? $form_ss : \"unk\"))\n ?>\n </h5>\n <tr>\n <th><?php echo xlt('Name'); ?></th>\n <th><?php echo xlt('Phone'); ?></th>\n <th><?php echo xlt('SS'); ?></th>\n <th><?php echo xlt('DOB'); ?></th>\n <th><?php echo xlt('Address'); ?></th>\n </tr>", " <?php\n while ($row = sqlFetchArray($res)) {\n if ($row['closeness'] == 0) {\n continue;\n }", " $phone = $row['phone_biz'];\n if (empty($phone)) {\n $phone = $row['phone_home'];\n }", " if (empty($phone)) {\n $phone = $row['phone_cell'];\n }", " if (empty($phone)) {\n $phone = $row['phone_contact'];\n }", " echo \" <tr class='oneresult'\";\n echo \" onclick=\\\"openPatient(\" . attr_js($row['pid']) . \")\\\">\\n\";\n echo \" <td>\" . text($row['lname'] . \", \" . $row['fname']) . \"</td>\\n\";\n echo \" <td>\" . text($phone) . \"</td>\\n\";\n echo \" <td>\" . text($row['ss']) . \"</td>\\n\";\n echo \" <td>\" . text($row['DOB']) . \"</td>\\n\";\n echo \" <td>\" . text($row['street'] . ' ' . $row['postal_code']) . \"</td>\\n\";\n echo \" </tr>\\n\";\n }\n ?>\n </table>\n </div>\n <?php\n}\n?>", "<p>\n <input type='button' value='<?php echo xla('Add New Patient'); ?>' onclick=\"openPatient(0)\"/>\n <input type='button' value='<?php echo xla('Cancel'); ?>' onclick=\"window.close()\"/>\n</p>", "</form>\n</center>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Patient report\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2017-2018 Brady Miller <brady.g.miller@gmail.com>\n * @author Stephen Nielson <stephen@nielson.org>\n * @copyright Copyright (c) 2019 Stephen Nielson <stephen@nielson.org>\n * @author Jerry Padgett <sjpadgett@gmail.com>\n * @copyright Copyright (c) 2019 Jerry Padgett <sjpadgett@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(\"../../globals.php\");\nrequire_once(\"$srcdir/lists.inc\");\nrequire_once(\"$srcdir/forms.inc\");\nrequire_once(\"$srcdir/patient.inc\");", "use OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\Events\\PatientReport\\PatientReportEvent;\nuse OpenEMR\\Menu\\PatientMenuRole;\nuse OpenEMR\\OeUI\\OemrUI;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;", "if (!AclMain::aclCheckCore('patients', 'pat_rep')) {\n die(xlt('Not authorized'));\n}\n// get various authorization levels\n$auth_notes_a = AclMain::aclCheckCore('encounters', 'notes_a');\n$auth_notes = AclMain::aclCheckCore('encounters', 'notes');\n$auth_coding_a = AclMain::aclCheckCore('encounters', 'coding_a');\n$auth_coding = AclMain::aclCheckCore('encounters', 'coding');\n$auth_relaxed = AclMain::aclCheckCore('encounters', 'relaxed');\n$auth_med = AclMain::aclCheckCore('patients', 'med');\n$auth_demo = AclMain::aclCheckCore('patients', 'demo');", "$oefax = !empty($GLOBALS['oefax_enable']) ? $GLOBALS['oefax_enable'] : 0;\n/**\n * @var EventDispatcherInterface $eventDispatcher The event dispatcher / listener object\n */\n$eventDispatcher = $GLOBALS['kernel']->getEventDispatcher();\n?>\n<html>\n<head>\n<title><?php echo xlt(\"Patient Reports\"); ?></title>", "<?php Header::setupHeader(['datetime-picker', 'common']); ?>\n<script>", "function checkAll(check) {\n var f = document.forms['report_form'];\n for (var i = 0; i < f.elements.length; ++i) {\n if (f.elements[i].type == 'checkbox') f.elements[i].checked = check;\n }\n return false;\n}", "function show_date_fun(){\n if(document.getElementById('show_date').checked == true){\n document.getElementById('date_div').style.display = '';\n }else{\n document.getElementById('date_div').style.display = 'none';\n }\n return;\n}\n<?php require_once(\"$include_root/patient_file/erx_patient_portal_js.php\"); // jQuery for popups for eRx and patient portal ?>\n</script>\n<?php\n$arrOeUiSettings = array(\n 'heading_title' => xl('Patient Reports'),\n 'include_patient_name' => true,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => true,\n 'help_file_name' => \"report_dashboard_help.php\"\n);\n$oemr_ui = new OemrUI($arrOeUiSettings);\n?>\n</head>", "<body>\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?> mt-3\">\n <div id=\"patient_reports\"> <!-- large outer DIV -->\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php require_once(\"$include_root/patient_file/summary/dashboard_header.php\");?>\n </div>\n </div>\n <?php\n $list_id = \"report\"; // to indicate nav item is active, count and give correct id\n // Collect the patient menu then build it\n $menuPatient = new PatientMenuRole();\n $menuPatient->displayHorizNavBarMenu();\n ?>", " <?php\n if ($GLOBALS['activate_ccr_ccd_report']) { // show CCR/CCD reporting options ?>\n <div class=\"mt-3\" id=\"ccr_report\">\n <form name='ccr_form' id='ccr_form' method='post' action='../../../ccr/createCCR.php'>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Continuity of Care Record (CCR)'); ?></span>\n <span class='text'>(<?php echo xlt('Pop ups need to be enabled to see these reports'); ?>)</span>\n <br/>\n <br/>\n <input type='hidden' name='ccrAction' />\n <input type='hidden' name='raw' />\n <input type=\"checkbox\" name=\"show_date\" id=\"show_date\" onchange=\"show_date_fun();\" ><span class='text'><?php echo xlt('Use Date Range'); ?>\n <br />\n <br />\n <div id=\"date_div\" style=\"display: none\">\n <div class=\"form-row\">\n <div class=\"col-12 col-sm-2\">\n <label for=\"Start\" class='font-weight-bold'><?php echo xlt('Start Date');?>: </label>\n </div>\n <div class=\"col-12 col-sm-4\">\n <input type='text' class='datepicker form-control' size='10' name='Start' id='Start' title='<?php echo xla('yyyy-mm-dd'); ?>' />\n </div>\n <div class=\"col-12 col-sm-2\">\n <label for=\"End\" class='font-weight-bold'><?php echo xlt('End Date');?>: </label>\n </div>\n <div class=\"col-12 col-sm-4\">\n <input type='text' class='datepicker form-control' size='10' name='End' id='End' title='<?php echo xla('yyyy-mm-dd'); ?>' />\n </div>\n </div>\n </div>\n <br />\n <button type=\"button\" class=\"generateCCR btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <!--<input type=\"button\" class=\"generateCCR_raw\" value=\"<?php echo xlt('Raw Report'); ?>\" /> -->\n <button type=\"button\" class=\"generateCCR_download_p btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download'); ?>\" ><?php echo xlt('Download'); ?></button>", " <?php\n if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccr_enable'] == true) { ?>\n <button type=\"button\" class=\"viewCCR_send_dialog btn btn-primary btn-transmit btn-sm\" value=\"<?php echo xla('Transmit'); ?>\"><?php echo xlt('Transmit'); ?></button>\n <br />\n <div id=\"ccr_send_dialog\" style=\"display: none\">\n <br />\n <div class=\"table-responsive\">\n <table class=\"table border-0\">\n <tr>\n <td>\n <span class='font-weight-bold'><?php echo xlt('Enter Recipient\\'s Direct Address');?>: </span>\n <input type=\"text\" size=\"64\" name=\"ccr_send_to\" id=\"ccr_send_to\" value=\"\" />\n <input type=\"hidden\" name=\"ccr_sent_by\" id=\"ccr_sent_by\" value=\"user\" />\n <button type=\"button\" class=\"viewCCR_transmit btn btn-primary btn-send-msg btn-sm\" value=\"<?php echo xla('Send CCR'); ?>\"><?php echo xlt('Send CCR'); ?></button>\n <div id=\"ccr_send_result\" style=\"display: none\">\n <span class=\"text\" id=\"ccr_send_message\"></span>\n </div>\n </td>\n </tr>\n </table>\n </div>\n </div>\n <?php } ?>\n </div>\n </fieldset>\n <hr/>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Continuity of Care Document (CCD)'); ?></span>&nbsp;&nbsp;\n <span class='text'>(<?php echo xlt('Pop ups need to be enabled to see these reports'); ?>)</span>\n <br/>\n <br/>\n <button type=\"button\" class=\"viewCCD btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"viewCCD_download btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download'); ?>\" ><?php echo xlt('Download'); ?></button>\n <?php\n if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccd_enable'] == true) { ?>\n <button type=\"button\" class=\"viewCCD_send_dialog btn btn-primary btn-transmit btn-sm\" value=\"<?php echo xla('Transmit'); ?>\" ><?php echo xlt('Transmit'); ?></button>\n <br />\n <div id=\"ccd_send_dialog\" style=\"display: none\">\n <div class=\"form-row mt-3\">\n <div class=\"col-12\">\n <label for=\"\" class=\"font-weight-bold\">\n <?php echo xlt('Enter Recipient\\'s Direct Address');?>:\n </label>\n </div>\n <div class=\"col-md\">\n <input type=\"text\" class=\"form-control\" size=\"64\" name=\"ccd_send_to\" id=\"ccd_send_to\" value=\"\" />\n <input type=\"hidden\" name=\"ccd_sent_by\" id=\"ccd_sent_by\" value=\"user\" />\n </div>\n <div class=\"col-md\">\n <button type=\"button\" class=\"viewCCD_transmit btn btn-primary btn-send-msg btn-sm\" value=\"<?php echo xla('Send CCD'); ?>\"><?php echo xlt('Send CCD'); ?></button>\n </div>\n </div>\n <div id=\"ccd_send_result\" style=\"display: none\">\n <span class=\"text\" id=\"ccd_send_message\"></span>\n </div>\n </div>\n <?php } ?>\n </div>\n </fieldset>\n </form>\n <hr/>\n </div>\n <?php\n } // end CCR/CCD reporting options ?>", " <form name='report_form' id=\"report_form\" method='post' action='custom_report.php'>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Patient Report'); ?></span>&nbsp;&nbsp;\n <!--\n <a class=\"link_submit\" href=\"full_report.php\" onclick=\"top.restoreSession()\">\n [<?php echo xlt('View Comprehensive Patient Report'); ?>]</a>\n -->\n <a class=\"link_submit btn btn-secondary btn-sm btn-save\" href=\"#\" onclick=\"return checkAll(true)\">\n <?php echo xla('Check All'); ?>\n </a>\n <a class=\"link_submit btn btn-secondary btn-sm btn-undo\" href=\"#\" onclick=\"return checkAll(false)\">\n <?php echo xla('Clear All'); ?>\n </a>", " <table class=\"includes mt-3\">\n <tr>\n <td class='text'>\n <input type='checkbox' name='include_demographics' id='include_demographics' value=\"demographics\" checked /><?php echo xlt('Demographics'); ?>\n <br />\n <?php if (AclMain::aclCheckCore('patients', 'med')) : ?>\n <input type='checkbox' name='include_history' id='include_history' value=\"history\" /><?php echo xlt('History'); ?>\n <br />\n <?php endif; ?>\n <!--\n <input type='checkbox' name='include_employer' id='include_employer' value=\"employer\"><?php echo xlt('Employer'); ?><br />\n -->\n <input type='checkbox' name='include_insurance' id='include_insurance' value=\"insurance\" /><?php echo xlt('Insurance'); ?>\n <br />\n <input type='checkbox' name='include_billing' id='include_billing' value=\"billing\"\n <?php\n if (!$GLOBALS['simplified_demographics']) {\n echo 'checked';\n } ?> /><?php echo xlt('Billing'); ?>\n <br />\n </td>\n <td class='text'>\n <!--\n <input type='checkbox' name='include_allergies' id='include_allergies' value=\"allergies\">Allergies<br />\n <input type='checkbox' name='include_medications' id='include_medications' value=\"medications\">Medications<br />\n -->\n <input type='checkbox' name='include_immunizations' id='include_immunizations' value=\"immunizations\" /><?php echo xlt('Immunizations'); ?>\n <br />\n <!--\n <input type='checkbox' name='include_medical_problems' id='include_medical_problems' value=\"medical_problems\">Medical Problems<br />\n -->\n <input type='checkbox' name='include_notes' id='include_notes' value=\"notes\" /><?php echo xlt('Patient Notes'); ?>\n <br />\n <input type='checkbox' name='include_transactions' id='include_transactions' value=\"transactions\" /><?php echo xlt('Transactions'); ?>\n <br />\n <input type='checkbox' name='include_batchcom' id='include_batchcom' value=\"batchcom\" /><?php echo xlt('Communications'); ?>\n <br />\n </td>\n <td class=\"text\">\n <input type='checkbox' name='include_recurring_days' id='include_recurring_days' value=\"recurring_days\" /><?php echo xlt('Recurrent Appointments'); ?>\n <br />\n </td>\n </tr>\n </table>\n <br />\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>", " <?php\n if ($oefax) {\n $eventDispatcher->dispatch(PatientReportEvent::ACTIONS_RENDER_POST, new GenericEvent());\n }\n ?>\n <input type='hidden' name='pdf' value='0' />\n <br />", " <!-- old ccr button position -->\n <hr/>", " <div class=\"row issues_encounters_forms\">\n <!-- Issues -->\n <div class=\"col-md-6\">\n <div class=\"issues table-responsive\">\n <span class='font-weight-bold oe-report-section-header'><?php echo xlt('Issues'); ?>:</span>\n <br />\n <br />", " <?php if (! AclMain::aclCheckCore('patients', 'med')) { ?>\n <br />(Issues not authorized)\n <?php } else { ?>\n <table class=\"table table-borderless\">\n <?php\n // get issues\n $pres = sqlStatement(\"SELECT * FROM lists WHERE pid = ? \" .\n \"ORDER BY type, begdate\", array($pid));\n $lasttype = \"\";\n while ($prow = sqlFetchArray($pres)) {\n if ($lasttype != $prow['type']) {\n $lasttype = $prow['type'];", " /****\n $disptype = $lasttype;\n switch ($lasttype) {\n case \"allergy\" : $disptype = \"Allergies\" ; break;\n case \"problem\" :\n case \"medical_problem\": $disptype = \"Medical Problems\"; break;\n case \"medication\" : $disptype = \"Medications\" ; break;\n case \"surgery\" : $disptype = \"Surgeries\" ; break;\n }\n ****/\n $disptype = $ISSUE_TYPES[$lasttype][0];", " echo \" <tr>\\n\";\n echo \" <td colspan='4' class='font-weight-bold'><span class='oe-report-section-header'>\" . xlt($disptype) . \":</span></td>\\n\";\n echo \" </tr>\\n\";\n }", " $rowid = $prow['id'];\n $disptitle = trim($prow['title']) ? $prow['title'] : \"[Missing Title]\";", " $ieres = sqlStatement(\"SELECT encounter FROM issue_encounter WHERE \" .\n \"pid = ? AND list_id = ?\", array($pid, $rowid));", " echo \" <tr class='text'>\\n\";\n echo \" <td>&nbsp;</td>\\n\";\n echo \" <td>\";\n echo \"<input type='checkbox' name='issue_\" . attr($rowid) . \"' id='issue_\" . attr($rowid) . \"' class='issuecheckbox' value='/\";\n while ($ierow = sqlFetchArray($ieres)) {\n echo attr($ierow['encounter']) . \"/\";\n }\n", " echo \"' />$disptitle</td>\\n\";", " echo \" <td>\" . text($prow['begdate']);", " if ($prow['enddate']) {\n echo \" - \" . text($prow['enddate']);\n } else {\n echo \" Active\";\n }", " echo \"</td>\\n\";\n echo \"</tr>\\n\";\n }\n ?>\n </table>\n <?php } // end of Issues output ?>\n </div> <!-- end issues DIV -->\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n </div>\n <!-- Encounters and Forms -->\n <div class=\"col-md-6\">\n <div class='encounters table-responsive'>\n <span class='font-weight-bold oe-report-section-header'><?php echo xlt('Encounters & Forms'); ?>:</span>\n <br />\n <br />", " <?php\n if (!($auth_notes_a || $auth_notes || $auth_coding_a || $auth_coding || $auth_med || $auth_relaxed)) { ?>\n (Encounters not authorized)\n <?php\n } else { ?>\n <?php\n $isfirst = 1;\n $res = sqlStatement(\"SELECT forms.encounter, forms.form_id, forms.form_name, \" .\n \"forms.formdir, forms.date AS fdate, form_encounter.date \" .\n \",form_encounter.reason \" .\n \"FROM forms, form_encounter WHERE \" .\n \"forms.pid = ? AND form_encounter.pid = ? AND \" .\n \"form_encounter.encounter = forms.encounter \" .\n \" AND forms.deleted=0 \" . // --JRM--\n \"ORDER BY form_encounter.encounter DESC, form_encounter.date DESC, fdate ASC\", array($pid, $pid));\n $res2 = sqlStatement(\"SELECT name FROM registry ORDER BY priority\");\n $html_strings = array();\n $registry_form_name = array();\n while ($result2 = sqlFetchArray($res2)) {\n array_push($registry_form_name, trim($result2['name']));\n }", " while ($result = sqlFetchArray($res)) {\n if ($result[\"form_name\"] == \"New Patient Encounter\") {\n if ($isfirst == 0) {\n foreach ($registry_form_name as $var) {\n if ($toprint = $html_strings[$var]) {\n foreach ($toprint as $var) {\n print $var;\n }\n }\n }\n $html_strings = array();\n echo \"</div>\\n\"; // end DIV encounter_forms\n echo \"</div>\\n\\n\"; //end DIV encounter_data\n echo \"<br />\";\n }\n $isfirst = 0;\n echo \"<div class='encounter_data'>\\n\";\n echo \"<input type=checkbox \" .\n \" name='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" id='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" value='\" . attr($result[\"encounter\"]) . \"'\" .\n \" class='encounter'\" .\n \" >\";\n // show encounter reason, not just 'New Encounter'\n // trim to a reasonable length for display purposes --cfapress\n $maxReasonLength = 20;\n if (strlen($result[\"reason\"]) > $maxReasonLength) {\n // The default encoding for this mb_substr() call is set near top of globals.php\n $result['reason'] = mb_substr($result['reason'], 0, $maxReasonLength) . \" ... \";\n }\n echo text($result[\"reason\"]) .\n \" (\" . text(date(\"Y-m-d\", strtotime($result[\"date\"]))) .\n \")\\n\";\n echo \"<div class='encounter_forms'>\\n\";\n } else {\n $form_name = trim($result[\"form_name\"]);\n //if form name is not in registry, look for the closest match by\n // finding a registry name which is at the start of the form name.\n //this is to allow for forms to put additional helpful information\n //in the database in the same string as their form name after the name\n $form_name_found_flag = 0;\n foreach ($registry_form_name as $var) {\n if ($var == $form_name) {\n $form_name_found_flag = 1;\n }\n }\n // if the form does not match precisely with any names in the registry, now see if any front partial matches\n // and change $form_name appropriately so it will print above in $toprint = $html_strings[$var]\n if (!$form_name_found_flag) {\n foreach ($registry_form_name as $var) {\n if (strpos($form_name, $var) == 0) {\n $form_name = $var;\n }\n }\n }\n if (empty($html_strings[$form_name]) || !is_array($html_strings[$form_name])) {\n $html_strings[$form_name] = array();\n }\n array_push($html_strings[$form_name], \"<input type='checkbox' \" .\n \" name='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" id='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" value='\" . attr($result[\"encounter\"]) . \"'\" .\n \" class='encounter_form' \" .\n \">\" . text(xl_form_title($result[\"form_name\"])) . \"<br />\\n\");\n }\n }", " foreach ($registry_form_name as $var) {\n if (!empty($html_strings[$var])) {\n if ($toprint = $html_strings[$var]) {\n foreach ($toprint as $var) {\n print $var;\n }\n }\n }\n }\n ?>", " <?php\n } ?>\n </div> <!-- end encounters DIV -->\n </div>\n </div>\n </div>", " <div class=\"col-sm-12\">\n <!-- Procedure Orders -->\n <hr/>\n <div class=\"table-responsive\">\n <table class=\"table table-borderless\">\n <tr>\n <td class='font-weight-bold'><span class='oe-report-section-header'><?php echo xlt('Procedures'); ?>:</span></td>\n <td class='text'>&nbsp;<?php echo xlt('Order Date'); ?>&nbsp;&nbsp;</td>\n <td class='text'><?php echo xlt('Encounter Date'); ?>&nbsp;&nbsp;</td>\n <td class='text'><?php echo xlt('Order Descriptions'); ?></td>\n </tr>\n <?php\n $res = sqlStatement(\n \"SELECT po.procedure_order_id, po.date_ordered, fe.date \" .\n \"FROM procedure_order AS po \" .\n \"LEFT JOIN forms AS f ON f.pid = po.patient_id AND f.formdir = 'procedure_order' AND \" .\n \"f.form_id = po.procedure_order_id AND f.deleted = 0 \" .\n \"LEFT JOIN form_encounter AS fe ON fe.pid = f.pid AND fe.encounter = f.encounter \" .\n \"WHERE po.patient_id = ? \" .\n \"ORDER BY po.date_ordered DESC, po.procedure_order_id DESC\",\n array($pid)\n );\n while ($row = sqlFetchArray($res)) {\n $poid = $row['procedure_order_id'];\n echo \" <tr>\\n\";\n echo \" <td class='text text-center'>\" .\n \"<input type='checkbox' name='procedures[]' value='\" . attr($poid) . \"' />&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text(oeFormatShortDate($row['date_ordered'])) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text(oeFormatShortDate($row['date'])) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\";\n $opres = sqlStatement(\n \"SELECT procedure_code, procedure_name FROM procedure_order_code \" .\n \"WHERE procedure_order_id = ? ORDER BY procedure_order_seq\",\n array($poid)\n );\n while ($oprow = sqlFetchArray($opres)) {\n $tmp = $oprow['procedure_name'];\n if (empty($tmp)) {\n $tmp = $oprow['procedure_code'];\n }\n echo text($tmp) . \"<br />\";\n }\n echo \"</td>\\n\";\n echo \" </tr>\\n\";\n }\n ?>\n </table>\n </div>", " <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n <hr/>\n <div>", " <span class=\"font-weight-bold oe-report-section-header\"><?php echo xlt('Documents'); ?>:</span><br />\n <ul>\n <?php\n // show available documents\n $db = $GLOBALS['adodb']['db'];\n $sql = \"SELECT d.id, d.url, d.name as document_name, c.name, c.aco_spec FROM documents AS d \" .\n \"LEFT JOIN categories_to_documents AS ctd ON d.id=ctd.document_id \" .\n \"LEFT JOIN categories AS c ON c.id = ctd.category_id WHERE \" .\n \"d.foreign_id = ? AND d.deleted = 0\";\n $result = $db->Execute($sql, array($pid));\n if ($db->ErrorMsg()) {\n echo $db->ErrorMsg();\n }\n while ($result && !$result->EOF) {\n if (empty($result->fields['aco_spec']) || AclMain::aclCheckAcoSpec($result->fields['aco_spec'])) {\n echo \"<li class='font-weight-bold'>\";\n echo '<input type=\"checkbox\" name=\"documents[]\" value=\"' .\n attr($result->fields['id']) . '\">';\n echo '&nbsp;&nbsp;<i>' . text(xl_document_category($result->fields['name'])) . \"</i>\";\n echo '&nbsp;&nbsp;' . xlt('Name') . ': <i>' . text($result->fields['document_name']) . '-' . text($result->fields['id']) . \"</i>\";\n echo '</li>';\n }\n $result->MoveNext();\n }\n ?>\n </ul>\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n </fieldset>\n </form>\n </div> <!-- close patient_reports DIV -->\n </div><!--end of container div-->\n <?php $oemr_ui->oeBelowContainerDiv();?>", "<script>", "// jQuery stuff to make the page a little easier to use\n$(function () {\n $('.datepicker').datetimepicker({\n <?php $datetimepicker_timepicker = false; ?>\n <?php $datetimepicker_showseconds = false; ?>\n <?php $datetimepicker_formatInput = false; ?>\n <?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?>\n <?php // can add any additional javascript settings to datetimepicker here; need to prepend first setting with a comma ?>\n });", " $(\".genreport\").click(function() { top.restoreSession(); document.report_form.pdf.value = 0; $(\"#report_form\").submit(); });\n $(\".genpdfrep\").click(function() { top.restoreSession(); document.report_form.pdf.value = 1; $(\"#report_form\").submit(); });\n $(\".genportal\").click(function() { top.restoreSession(); document.report_form.pdf.value = 2; $(\"#report_form\").submit(); });\n $(\"#genfullreport\").click(function() { location.href='<?php echo \"$rootdir/patient_file/encounter/\" . ($returnurl ?? ''); ?>'; });\n //$(\"#printform\").click(function() { PrintForm(); });\n $(\".issuecheckbox\").click(function() { issueClick(this); });", " // check/uncheck all Forms of an encounter\n $(\".encounter\").click(function() { SelectForms($(this)); });", " $(\".generateCCR\").click(function() {\n if(document.getElementById('show_date').checked == true){\n if(document.getElementById('Start').value == '' || document.getElementById('End').value == ''){\n alert(<?php echo xlj('Please select a start date and end date') ?>);\n return false;\n }\n }\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'no';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".generateCCR_raw\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'yes';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".generateCCR_download_h\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'hybrid';\n top.restoreSession();\n $(\"#ccr_form\").submit();\n });\n $(\".generateCCR_download_p\").click(function() {\n if(document.getElementById('show_date').checked == true){\n if(document.getElementById('Start').value == '' || document.getElementById('End').value == ''){\n alert(<?php echo xlj('Please select a start date and end date'); ?>);\n return false;\n }\n }\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'pure';\n top.restoreSession();\n $(\"#ccr_form\").submit();\n });\n $(\".viewCCD\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'no';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".viewCCD_raw\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'yes';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".viewCCD_download\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'pure';\n $(\"#ccr_form\").submit();\n });", " <?php if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccr_enable'] == true) { ?>\n $(\".viewCCR_send_dialog\").click(function() {\n $(\"#ccr_send_dialog\").toggle();\n });\n $(\".viewCCR_transmit\").click(function() {\n $(\".viewCCR_transmit\").attr('disabled','disabled');\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var ccrRecipient = $(\"#ccr_send_to\").val();\n var raw = document.getElementsByName('raw');\n raw[0].value = 'send '+ccrRecipient;\n if(ccrRecipient==\"\") {\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Please enter a valid Direct Address above.'); ?>);\n $(\"#ccr_send_result\").show();\n } else {\n $(\".viewCCR_transmit\").attr('disabled','disabled');\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Working... this may take a minute.'); ?>);\n $(\"#ccr_send_result\").show();\n var action=$(\"#ccr_form\").attr('action');\n $.post(action,\n {\n ccrAction:'generate',\n raw:'send '+ccrRecipient,\n requested_by:'user'\n },\n function(data) {\n if(data==\"SUCCESS\") {\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Your message was submitted for delivery to');\n ?>+ \" \" + ccrRecipient);\n $(\"#ccr_send_to\").val(\"\");\n } else {\n $(\"#ccr_send_message\").html(data);\n }\n $(\".viewCCR_transmit\").removeAttr('disabled');\n });\n }\n });\n <?php }", " if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccd_enable'] == true) { ?>\n $(\".viewCCD_send_dialog\").click(function() {\n $(\"#ccd_send_dialog\").toggle();\n });\n $(\".viewCCD_transmit\").click(function() {\n $(\".viewCCD_transmit\").attr('disabled','disabled');\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var ccdRecipient = $(\"#ccd_send_to\").val();\n var raw = document.getElementsByName('raw');\n raw[0].value = 'send '+ccdRecipient;\n if(ccdRecipient==\"\") {\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Please enter a valid Direct Address above.'); ?>);\n $(\"#ccd_send_result\").show();\n } else {\n $(\".viewCCD_transmit\").attr('disabled','disabled');\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Working... this may take a minute.'); ?>);\n $(\"#ccd_send_result\").show();\n var action=$(\"#ccr_form\").attr('action');\n $.post(action,\n {\n ccrAction:'viewccd',\n raw:'send '+ccdRecipient,\n requested_by:'user'\n },\n function(data) {\n if(data==\"SUCCESS\") {\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Your message was submitted for delivery to');\n ?> + \" \" + ccdRecipient);\n $(\"#ccd_send_to\").val(\"\");\n } else {\n $(\"#ccd_send_message\").html(data);\n }\n $(\".viewCCD_transmit\").removeAttr('disabled');\n });\n }\n });\n <?php } ?>", " <?php\n if ($oefax) {\n $eventDispatcher->dispatch(PatientReportEvent::JAVASCRIPT_READY_POST, new GenericEvent());\n }\n ?>", "});", "// select/deselect the Forms related to the selected Encounter\n// (it ain't pretty code folks)\nvar SelectForms = function (selectedEncounter) {\n if ($(selectedEncounter).prop(\"checked\")) {\n $(selectedEncounter).parent().children().each(function(i, obj) {\n $(this).children().each(function(i, obj) {\n $(this).prop(\"checked\", true);\n });\n });\n }\n else {\n $(selectedEncounter).parent().children().each(function(i, obj) {\n $(this).children().each(function(i, obj) {\n $(this).prop(\"checked\", false);\n });\n });\n }\n}", "// When an issue is checked, auto-check all the related encounters and forms\nfunction issueClick(issue) {\n // do nothing when unchecked\n if (! $(issue).attr(\"checked\")) return;", " $(\"#report_form :checkbox\").each(function(i, obj) {\n if ($(issue).val().indexOf('/' + $(this).val() + '/') >= 0) {\n $(this).attr(\"checked\", \"checked\");\n }\n });\n}", "var listId = '#' + <?php echo js_escape($list_id); ?>;\n$(function () {\n $(listId).addClass(\"active\");\n});", "</script>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Patient report\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2017-2018 Brady Miller <brady.g.miller@gmail.com>\n * @author Stephen Nielson <stephen@nielson.org>\n * @copyright Copyright (c) 2019 Stephen Nielson <stephen@nielson.org>\n * @author Jerry Padgett <sjpadgett@gmail.com>\n * @copyright Copyright (c) 2019 Jerry Padgett <sjpadgett@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(\"../../globals.php\");\nrequire_once(\"$srcdir/lists.inc\");\nrequire_once(\"$srcdir/forms.inc\");\nrequire_once(\"$srcdir/patient.inc\");", "use OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\Events\\PatientReport\\PatientReportEvent;\nuse OpenEMR\\Menu\\PatientMenuRole;\nuse OpenEMR\\OeUI\\OemrUI;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;", "if (!AclMain::aclCheckCore('patients', 'pat_rep')) {\n die(xlt('Not authorized'));\n}\n// get various authorization levels\n$auth_notes_a = AclMain::aclCheckCore('encounters', 'notes_a');\n$auth_notes = AclMain::aclCheckCore('encounters', 'notes');\n$auth_coding_a = AclMain::aclCheckCore('encounters', 'coding_a');\n$auth_coding = AclMain::aclCheckCore('encounters', 'coding');\n$auth_relaxed = AclMain::aclCheckCore('encounters', 'relaxed');\n$auth_med = AclMain::aclCheckCore('patients', 'med');\n$auth_demo = AclMain::aclCheckCore('patients', 'demo');", "$oefax = !empty($GLOBALS['oefax_enable']) ? $GLOBALS['oefax_enable'] : 0;\n/**\n * @var EventDispatcherInterface $eventDispatcher The event dispatcher / listener object\n */\n$eventDispatcher = $GLOBALS['kernel']->getEventDispatcher();\n?>\n<html>\n<head>\n<title><?php echo xlt(\"Patient Reports\"); ?></title>", "<?php Header::setupHeader(['datetime-picker', 'common']); ?>\n<script>", "function checkAll(check) {\n var f = document.forms['report_form'];\n for (var i = 0; i < f.elements.length; ++i) {\n if (f.elements[i].type == 'checkbox') f.elements[i].checked = check;\n }\n return false;\n}", "function show_date_fun(){\n if(document.getElementById('show_date').checked == true){\n document.getElementById('date_div').style.display = '';\n }else{\n document.getElementById('date_div').style.display = 'none';\n }\n return;\n}\n<?php require_once(\"$include_root/patient_file/erx_patient_portal_js.php\"); // jQuery for popups for eRx and patient portal ?>\n</script>\n<?php\n$arrOeUiSettings = array(\n 'heading_title' => xl('Patient Reports'),\n 'include_patient_name' => true,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => true,\n 'help_file_name' => \"report_dashboard_help.php\"\n);\n$oemr_ui = new OemrUI($arrOeUiSettings);\n?>\n</head>", "<body>\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?> mt-3\">\n <div id=\"patient_reports\"> <!-- large outer DIV -->\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php require_once(\"$include_root/patient_file/summary/dashboard_header.php\");?>\n </div>\n </div>\n <?php\n $list_id = \"report\"; // to indicate nav item is active, count and give correct id\n // Collect the patient menu then build it\n $menuPatient = new PatientMenuRole();\n $menuPatient->displayHorizNavBarMenu();\n ?>", " <?php\n if ($GLOBALS['activate_ccr_ccd_report']) { // show CCR/CCD reporting options ?>\n <div class=\"mt-3\" id=\"ccr_report\">\n <form name='ccr_form' id='ccr_form' method='post' action='../../../ccr/createCCR.php'>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Continuity of Care Record (CCR)'); ?></span>\n <span class='text'>(<?php echo xlt('Pop ups need to be enabled to see these reports'); ?>)</span>\n <br/>\n <br/>\n <input type='hidden' name='ccrAction' />\n <input type='hidden' name='raw' />\n <input type=\"checkbox\" name=\"show_date\" id=\"show_date\" onchange=\"show_date_fun();\" ><span class='text'><?php echo xlt('Use Date Range'); ?>\n <br />\n <br />\n <div id=\"date_div\" style=\"display: none\">\n <div class=\"form-row\">\n <div class=\"col-12 col-sm-2\">\n <label for=\"Start\" class='font-weight-bold'><?php echo xlt('Start Date');?>: </label>\n </div>\n <div class=\"col-12 col-sm-4\">\n <input type='text' class='datepicker form-control' size='10' name='Start' id='Start' title='<?php echo xla('yyyy-mm-dd'); ?>' />\n </div>\n <div class=\"col-12 col-sm-2\">\n <label for=\"End\" class='font-weight-bold'><?php echo xlt('End Date');?>: </label>\n </div>\n <div class=\"col-12 col-sm-4\">\n <input type='text' class='datepicker form-control' size='10' name='End' id='End' title='<?php echo xla('yyyy-mm-dd'); ?>' />\n </div>\n </div>\n </div>\n <br />\n <button type=\"button\" class=\"generateCCR btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <!--<input type=\"button\" class=\"generateCCR_raw\" value=\"<?php echo xlt('Raw Report'); ?>\" /> -->\n <button type=\"button\" class=\"generateCCR_download_p btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download'); ?>\" ><?php echo xlt('Download'); ?></button>", " <?php\n if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccr_enable'] == true) { ?>\n <button type=\"button\" class=\"viewCCR_send_dialog btn btn-primary btn-transmit btn-sm\" value=\"<?php echo xla('Transmit'); ?>\"><?php echo xlt('Transmit'); ?></button>\n <br />\n <div id=\"ccr_send_dialog\" style=\"display: none\">\n <br />\n <div class=\"table-responsive\">\n <table class=\"table border-0\">\n <tr>\n <td>\n <span class='font-weight-bold'><?php echo xlt('Enter Recipient\\'s Direct Address');?>: </span>\n <input type=\"text\" size=\"64\" name=\"ccr_send_to\" id=\"ccr_send_to\" value=\"\" />\n <input type=\"hidden\" name=\"ccr_sent_by\" id=\"ccr_sent_by\" value=\"user\" />\n <button type=\"button\" class=\"viewCCR_transmit btn btn-primary btn-send-msg btn-sm\" value=\"<?php echo xla('Send CCR'); ?>\"><?php echo xlt('Send CCR'); ?></button>\n <div id=\"ccr_send_result\" style=\"display: none\">\n <span class=\"text\" id=\"ccr_send_message\"></span>\n </div>\n </td>\n </tr>\n </table>\n </div>\n </div>\n <?php } ?>\n </div>\n </fieldset>\n <hr/>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Continuity of Care Document (CCD)'); ?></span>&nbsp;&nbsp;\n <span class='text'>(<?php echo xlt('Pop ups need to be enabled to see these reports'); ?>)</span>\n <br/>\n <br/>\n <button type=\"button\" class=\"viewCCD btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"viewCCD_download btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download'); ?>\" ><?php echo xlt('Download'); ?></button>\n <?php\n if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccd_enable'] == true) { ?>\n <button type=\"button\" class=\"viewCCD_send_dialog btn btn-primary btn-transmit btn-sm\" value=\"<?php echo xla('Transmit'); ?>\" ><?php echo xlt('Transmit'); ?></button>\n <br />\n <div id=\"ccd_send_dialog\" style=\"display: none\">\n <div class=\"form-row mt-3\">\n <div class=\"col-12\">\n <label for=\"\" class=\"font-weight-bold\">\n <?php echo xlt('Enter Recipient\\'s Direct Address');?>:\n </label>\n </div>\n <div class=\"col-md\">\n <input type=\"text\" class=\"form-control\" size=\"64\" name=\"ccd_send_to\" id=\"ccd_send_to\" value=\"\" />\n <input type=\"hidden\" name=\"ccd_sent_by\" id=\"ccd_sent_by\" value=\"user\" />\n </div>\n <div class=\"col-md\">\n <button type=\"button\" class=\"viewCCD_transmit btn btn-primary btn-send-msg btn-sm\" value=\"<?php echo xla('Send CCD'); ?>\"><?php echo xlt('Send CCD'); ?></button>\n </div>\n </div>\n <div id=\"ccd_send_result\" style=\"display: none\">\n <span class=\"text\" id=\"ccd_send_message\"></span>\n </div>\n </div>\n <?php } ?>\n </div>\n </fieldset>\n </form>\n <hr/>\n </div>\n <?php\n } // end CCR/CCD reporting options ?>", " <form name='report_form' id=\"report_form\" method='post' action='custom_report.php'>\n <fieldset>\n <div class=\"col-sm-12\">\n <span class='title oe-report-section-header'><?php echo xlt('Patient Report'); ?></span>&nbsp;&nbsp;\n <!--\n <a class=\"link_submit\" href=\"full_report.php\" onclick=\"top.restoreSession()\">\n [<?php echo xlt('View Comprehensive Patient Report'); ?>]</a>\n -->\n <a class=\"link_submit btn btn-secondary btn-sm btn-save\" href=\"#\" onclick=\"return checkAll(true)\">\n <?php echo xla('Check All'); ?>\n </a>\n <a class=\"link_submit btn btn-secondary btn-sm btn-undo\" href=\"#\" onclick=\"return checkAll(false)\">\n <?php echo xla('Clear All'); ?>\n </a>", " <table class=\"includes mt-3\">\n <tr>\n <td class='text'>\n <input type='checkbox' name='include_demographics' id='include_demographics' value=\"demographics\" checked /><?php echo xlt('Demographics'); ?>\n <br />\n <?php if (AclMain::aclCheckCore('patients', 'med')) : ?>\n <input type='checkbox' name='include_history' id='include_history' value=\"history\" /><?php echo xlt('History'); ?>\n <br />\n <?php endif; ?>\n <!--\n <input type='checkbox' name='include_employer' id='include_employer' value=\"employer\"><?php echo xlt('Employer'); ?><br />\n -->\n <input type='checkbox' name='include_insurance' id='include_insurance' value=\"insurance\" /><?php echo xlt('Insurance'); ?>\n <br />\n <input type='checkbox' name='include_billing' id='include_billing' value=\"billing\"\n <?php\n if (!$GLOBALS['simplified_demographics']) {\n echo 'checked';\n } ?> /><?php echo xlt('Billing'); ?>\n <br />\n </td>\n <td class='text'>\n <!--\n <input type='checkbox' name='include_allergies' id='include_allergies' value=\"allergies\">Allergies<br />\n <input type='checkbox' name='include_medications' id='include_medications' value=\"medications\">Medications<br />\n -->\n <input type='checkbox' name='include_immunizations' id='include_immunizations' value=\"immunizations\" /><?php echo xlt('Immunizations'); ?>\n <br />\n <!--\n <input type='checkbox' name='include_medical_problems' id='include_medical_problems' value=\"medical_problems\">Medical Problems<br />\n -->\n <input type='checkbox' name='include_notes' id='include_notes' value=\"notes\" /><?php echo xlt('Patient Notes'); ?>\n <br />\n <input type='checkbox' name='include_transactions' id='include_transactions' value=\"transactions\" /><?php echo xlt('Transactions'); ?>\n <br />\n <input type='checkbox' name='include_batchcom' id='include_batchcom' value=\"batchcom\" /><?php echo xlt('Communications'); ?>\n <br />\n </td>\n <td class=\"text\">\n <input type='checkbox' name='include_recurring_days' id='include_recurring_days' value=\"recurring_days\" /><?php echo xlt('Recurrent Appointments'); ?>\n <br />\n </td>\n </tr>\n </table>\n <br />\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>", " <?php\n if ($oefax) {\n $eventDispatcher->dispatch(PatientReportEvent::ACTIONS_RENDER_POST, new GenericEvent());\n }\n ?>\n <input type='hidden' name='pdf' value='0' />\n <br />", " <!-- old ccr button position -->\n <hr/>", " <div class=\"row issues_encounters_forms\">\n <!-- Issues -->\n <div class=\"col-md-6\">\n <div class=\"issues table-responsive\">\n <span class='font-weight-bold oe-report-section-header'><?php echo xlt('Issues'); ?>:</span>\n <br />\n <br />", " <?php if (! AclMain::aclCheckCore('patients', 'med')) { ?>\n <br />(Issues not authorized)\n <?php } else { ?>\n <table class=\"table table-borderless\">\n <?php\n // get issues\n $pres = sqlStatement(\"SELECT * FROM lists WHERE pid = ? \" .\n \"ORDER BY type, begdate\", array($pid));\n $lasttype = \"\";\n while ($prow = sqlFetchArray($pres)) {\n if ($lasttype != $prow['type']) {\n $lasttype = $prow['type'];", " /****\n $disptype = $lasttype;\n switch ($lasttype) {\n case \"allergy\" : $disptype = \"Allergies\" ; break;\n case \"problem\" :\n case \"medical_problem\": $disptype = \"Medical Problems\"; break;\n case \"medication\" : $disptype = \"Medications\" ; break;\n case \"surgery\" : $disptype = \"Surgeries\" ; break;\n }\n ****/\n $disptype = $ISSUE_TYPES[$lasttype][0];", " echo \" <tr>\\n\";\n echo \" <td colspan='4' class='font-weight-bold'><span class='oe-report-section-header'>\" . xlt($disptype) . \":</span></td>\\n\";\n echo \" </tr>\\n\";\n }", " $rowid = $prow['id'];\n $disptitle = trim($prow['title']) ? $prow['title'] : \"[Missing Title]\";", " $ieres = sqlStatement(\"SELECT encounter FROM issue_encounter WHERE \" .\n \"pid = ? AND list_id = ?\", array($pid, $rowid));", " echo \" <tr class='text'>\\n\";\n echo \" <td>&nbsp;</td>\\n\";\n echo \" <td>\";\n echo \"<input type='checkbox' name='issue_\" . attr($rowid) . \"' id='issue_\" . attr($rowid) . \"' class='issuecheckbox' value='/\";\n while ($ierow = sqlFetchArray($ieres)) {\n echo attr($ierow['encounter']) . \"/\";\n }\n", " echo \"' />\" . text($disptitle) . \"</td>\\n\";", " echo \" <td>\" . text($prow['begdate']);", " if ($prow['enddate']) {\n echo \" - \" . text($prow['enddate']);\n } else {\n echo \" Active\";\n }", " echo \"</td>\\n\";\n echo \"</tr>\\n\";\n }\n ?>\n </table>\n <?php } // end of Issues output ?>\n </div> <!-- end issues DIV -->\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n </div>\n <!-- Encounters and Forms -->\n <div class=\"col-md-6\">\n <div class='encounters table-responsive'>\n <span class='font-weight-bold oe-report-section-header'><?php echo xlt('Encounters & Forms'); ?>:</span>\n <br />\n <br />", " <?php\n if (!($auth_notes_a || $auth_notes || $auth_coding_a || $auth_coding || $auth_med || $auth_relaxed)) { ?>\n (Encounters not authorized)\n <?php\n } else { ?>\n <?php\n $isfirst = 1;\n $res = sqlStatement(\"SELECT forms.encounter, forms.form_id, forms.form_name, \" .\n \"forms.formdir, forms.date AS fdate, form_encounter.date \" .\n \",form_encounter.reason \" .\n \"FROM forms, form_encounter WHERE \" .\n \"forms.pid = ? AND form_encounter.pid = ? AND \" .\n \"form_encounter.encounter = forms.encounter \" .\n \" AND forms.deleted=0 \" . // --JRM--\n \"ORDER BY form_encounter.encounter DESC, form_encounter.date DESC, fdate ASC\", array($pid, $pid));\n $res2 = sqlStatement(\"SELECT name FROM registry ORDER BY priority\");\n $html_strings = array();\n $registry_form_name = array();\n while ($result2 = sqlFetchArray($res2)) {\n array_push($registry_form_name, trim($result2['name']));\n }", " while ($result = sqlFetchArray($res)) {\n if ($result[\"form_name\"] == \"New Patient Encounter\") {\n if ($isfirst == 0) {\n foreach ($registry_form_name as $var) {\n if ($toprint = $html_strings[$var]) {\n foreach ($toprint as $var) {\n print $var;\n }\n }\n }\n $html_strings = array();\n echo \"</div>\\n\"; // end DIV encounter_forms\n echo \"</div>\\n\\n\"; //end DIV encounter_data\n echo \"<br />\";\n }\n $isfirst = 0;\n echo \"<div class='encounter_data'>\\n\";\n echo \"<input type=checkbox \" .\n \" name='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" id='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" value='\" . attr($result[\"encounter\"]) . \"'\" .\n \" class='encounter'\" .\n \" >\";\n // show encounter reason, not just 'New Encounter'\n // trim to a reasonable length for display purposes --cfapress\n $maxReasonLength = 20;\n if (strlen($result[\"reason\"]) > $maxReasonLength) {\n // The default encoding for this mb_substr() call is set near top of globals.php\n $result['reason'] = mb_substr($result['reason'], 0, $maxReasonLength) . \" ... \";\n }\n echo text($result[\"reason\"]) .\n \" (\" . text(date(\"Y-m-d\", strtotime($result[\"date\"]))) .\n \")\\n\";\n echo \"<div class='encounter_forms'>\\n\";\n } else {\n $form_name = trim($result[\"form_name\"]);\n //if form name is not in registry, look for the closest match by\n // finding a registry name which is at the start of the form name.\n //this is to allow for forms to put additional helpful information\n //in the database in the same string as their form name after the name\n $form_name_found_flag = 0;\n foreach ($registry_form_name as $var) {\n if ($var == $form_name) {\n $form_name_found_flag = 1;\n }\n }\n // if the form does not match precisely with any names in the registry, now see if any front partial matches\n // and change $form_name appropriately so it will print above in $toprint = $html_strings[$var]\n if (!$form_name_found_flag) {\n foreach ($registry_form_name as $var) {\n if (strpos($form_name, $var) == 0) {\n $form_name = $var;\n }\n }\n }\n if (empty($html_strings[$form_name]) || !is_array($html_strings[$form_name])) {\n $html_strings[$form_name] = array();\n }\n array_push($html_strings[$form_name], \"<input type='checkbox' \" .\n \" name='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" id='\" . attr($result[\"formdir\"]) . \"_\" . attr($result[\"form_id\"]) . \"'\" .\n \" value='\" . attr($result[\"encounter\"]) . \"'\" .\n \" class='encounter_form' \" .\n \">\" . text(xl_form_title($result[\"form_name\"])) . \"<br />\\n\");\n }\n }", " foreach ($registry_form_name as $var) {\n if (!empty($html_strings[$var])) {\n if ($toprint = $html_strings[$var]) {\n foreach ($toprint as $var) {\n print $var;\n }\n }\n }\n }\n ?>", " <?php\n } ?>\n </div> <!-- end encounters DIV -->\n </div>\n </div>\n </div>", " <div class=\"col-sm-12\">\n <!-- Procedure Orders -->\n <hr/>\n <div class=\"table-responsive\">\n <table class=\"table table-borderless\">\n <tr>\n <td class='font-weight-bold'><span class='oe-report-section-header'><?php echo xlt('Procedures'); ?>:</span></td>\n <td class='text'>&nbsp;<?php echo xlt('Order Date'); ?>&nbsp;&nbsp;</td>\n <td class='text'><?php echo xlt('Encounter Date'); ?>&nbsp;&nbsp;</td>\n <td class='text'><?php echo xlt('Order Descriptions'); ?></td>\n </tr>\n <?php\n $res = sqlStatement(\n \"SELECT po.procedure_order_id, po.date_ordered, fe.date \" .\n \"FROM procedure_order AS po \" .\n \"LEFT JOIN forms AS f ON f.pid = po.patient_id AND f.formdir = 'procedure_order' AND \" .\n \"f.form_id = po.procedure_order_id AND f.deleted = 0 \" .\n \"LEFT JOIN form_encounter AS fe ON fe.pid = f.pid AND fe.encounter = f.encounter \" .\n \"WHERE po.patient_id = ? \" .\n \"ORDER BY po.date_ordered DESC, po.procedure_order_id DESC\",\n array($pid)\n );\n while ($row = sqlFetchArray($res)) {\n $poid = $row['procedure_order_id'];\n echo \" <tr>\\n\";\n echo \" <td class='text text-center'>\" .\n \"<input type='checkbox' name='procedures[]' value='\" . attr($poid) . \"' />&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text(oeFormatShortDate($row['date_ordered'])) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\" . text(oeFormatShortDate($row['date'])) . \"&nbsp;&nbsp;</td>\\n\";\n echo \" <td class='text'>\";\n $opres = sqlStatement(\n \"SELECT procedure_code, procedure_name FROM procedure_order_code \" .\n \"WHERE procedure_order_id = ? ORDER BY procedure_order_seq\",\n array($poid)\n );\n while ($oprow = sqlFetchArray($opres)) {\n $tmp = $oprow['procedure_name'];\n if (empty($tmp)) {\n $tmp = $oprow['procedure_code'];\n }\n echo text($tmp) . \"<br />\";\n }\n echo \"</td>\\n\";\n echo \" </tr>\\n\";\n }\n ?>\n </table>\n </div>", " <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n <hr/>\n <div>", " <span class=\"font-weight-bold oe-report-section-header\"><?php echo xlt('Documents'); ?>:</span><br />\n <ul>\n <?php\n // show available documents\n $db = $GLOBALS['adodb']['db'];\n $sql = \"SELECT d.id, d.url, d.name as document_name, c.name, c.aco_spec FROM documents AS d \" .\n \"LEFT JOIN categories_to_documents AS ctd ON d.id=ctd.document_id \" .\n \"LEFT JOIN categories AS c ON c.id = ctd.category_id WHERE \" .\n \"d.foreign_id = ? AND d.deleted = 0\";\n $result = $db->Execute($sql, array($pid));\n if ($db->ErrorMsg()) {\n echo $db->ErrorMsg();\n }\n while ($result && !$result->EOF) {\n if (empty($result->fields['aco_spec']) || AclMain::aclCheckAcoSpec($result->fields['aco_spec'])) {\n echo \"<li class='font-weight-bold'>\";\n echo '<input type=\"checkbox\" name=\"documents[]\" value=\"' .\n attr($result->fields['id']) . '\">';\n echo '&nbsp;&nbsp;<i>' . text(xl_document_category($result->fields['name'])) . \"</i>\";\n echo '&nbsp;&nbsp;' . xlt('Name') . ': <i>' . text($result->fields['document_name']) . '-' . text($result->fields['id']) . \"</i>\";\n echo '</li>';\n }\n $result->MoveNext();\n }\n ?>\n </ul>\n <button type=\"button\" class=\"genreport btn btn-primary btn-save btn-sm\" value=\"<?php echo xla('Generate Report'); ?>\" ><?php echo xlt('Generate Report'); ?></button>\n <button type=\"button\" class=\"genpdfrep btn btn-primary btn-download btn-sm\" value=\"<?php echo xla('Download PDF'); ?>\" ><?php echo xlt('Download PDF'); ?></button>\n </fieldset>\n </form>\n </div> <!-- close patient_reports DIV -->\n </div><!--end of container div-->\n <?php $oemr_ui->oeBelowContainerDiv();?>", "<script>", "// jQuery stuff to make the page a little easier to use\n$(function () {\n $('.datepicker').datetimepicker({\n <?php $datetimepicker_timepicker = false; ?>\n <?php $datetimepicker_showseconds = false; ?>\n <?php $datetimepicker_formatInput = false; ?>\n <?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?>\n <?php // can add any additional javascript settings to datetimepicker here; need to prepend first setting with a comma ?>\n });", " $(\".genreport\").click(function() { top.restoreSession(); document.report_form.pdf.value = 0; $(\"#report_form\").submit(); });\n $(\".genpdfrep\").click(function() { top.restoreSession(); document.report_form.pdf.value = 1; $(\"#report_form\").submit(); });\n $(\".genportal\").click(function() { top.restoreSession(); document.report_form.pdf.value = 2; $(\"#report_form\").submit(); });\n $(\"#genfullreport\").click(function() { location.href='<?php echo \"$rootdir/patient_file/encounter/\" . ($returnurl ?? ''); ?>'; });\n //$(\"#printform\").click(function() { PrintForm(); });\n $(\".issuecheckbox\").click(function() { issueClick(this); });", " // check/uncheck all Forms of an encounter\n $(\".encounter\").click(function() { SelectForms($(this)); });", " $(\".generateCCR\").click(function() {\n if(document.getElementById('show_date').checked == true){\n if(document.getElementById('Start').value == '' || document.getElementById('End').value == ''){\n alert(<?php echo xlj('Please select a start date and end date') ?>);\n return false;\n }\n }\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'no';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".generateCCR_raw\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'yes';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".generateCCR_download_h\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'hybrid';\n top.restoreSession();\n $(\"#ccr_form\").submit();\n });\n $(\".generateCCR_download_p\").click(function() {\n if(document.getElementById('show_date').checked == true){\n if(document.getElementById('Start').value == '' || document.getElementById('End').value == ''){\n alert(<?php echo xlj('Please select a start date and end date'); ?>);\n return false;\n }\n }\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'pure';\n top.restoreSession();\n $(\"#ccr_form\").submit();\n });\n $(\".viewCCD\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'no';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".viewCCD_raw\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'yes';\n top.restoreSession();\n ccr_form.setAttribute(\"target\", \"_blank\");\n $(\"#ccr_form\").submit();\n ccr_form.setAttribute(\"target\", \"\");\n });\n $(\".viewCCD_download\").click(function() {\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var raw = document.getElementsByName('raw');\n raw[0].value = 'pure';\n $(\"#ccr_form\").submit();\n });", " <?php if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccr_enable'] == true) { ?>\n $(\".viewCCR_send_dialog\").click(function() {\n $(\"#ccr_send_dialog\").toggle();\n });\n $(\".viewCCR_transmit\").click(function() {\n $(\".viewCCR_transmit\").attr('disabled','disabled');\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'generate';\n var ccrRecipient = $(\"#ccr_send_to\").val();\n var raw = document.getElementsByName('raw');\n raw[0].value = 'send '+ccrRecipient;\n if(ccrRecipient==\"\") {\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Please enter a valid Direct Address above.'); ?>);\n $(\"#ccr_send_result\").show();\n } else {\n $(\".viewCCR_transmit\").attr('disabled','disabled');\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Working... this may take a minute.'); ?>);\n $(\"#ccr_send_result\").show();\n var action=$(\"#ccr_form\").attr('action');\n $.post(action,\n {\n ccrAction:'generate',\n raw:'send '+ccrRecipient,\n requested_by:'user'\n },\n function(data) {\n if(data==\"SUCCESS\") {\n $(\"#ccr_send_message\").html(<?php\n echo xlj('Your message was submitted for delivery to');\n ?>+ \" \" + ccrRecipient);\n $(\"#ccr_send_to\").val(\"\");\n } else {\n $(\"#ccr_send_message\").html(data);\n }\n $(\".viewCCR_transmit\").removeAttr('disabled');\n });\n }\n });\n <?php }", " if ($GLOBALS['phimail_enable'] == true && $GLOBALS['phimail_ccd_enable'] == true) { ?>\n $(\".viewCCD_send_dialog\").click(function() {\n $(\"#ccd_send_dialog\").toggle();\n });\n $(\".viewCCD_transmit\").click(function() {\n $(\".viewCCD_transmit\").attr('disabled','disabled');\n var ccrAction = document.getElementsByName('ccrAction');\n ccrAction[0].value = 'viewccd';\n var ccdRecipient = $(\"#ccd_send_to\").val();\n var raw = document.getElementsByName('raw');\n raw[0].value = 'send '+ccdRecipient;\n if(ccdRecipient==\"\") {\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Please enter a valid Direct Address above.'); ?>);\n $(\"#ccd_send_result\").show();\n } else {\n $(\".viewCCD_transmit\").attr('disabled','disabled');\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Working... this may take a minute.'); ?>);\n $(\"#ccd_send_result\").show();\n var action=$(\"#ccr_form\").attr('action');\n $.post(action,\n {\n ccrAction:'viewccd',\n raw:'send '+ccdRecipient,\n requested_by:'user'\n },\n function(data) {\n if(data==\"SUCCESS\") {\n $(\"#ccd_send_message\").html(<?php\n echo xlj('Your message was submitted for delivery to');\n ?> + \" \" + ccdRecipient);\n $(\"#ccd_send_to\").val(\"\");\n } else {\n $(\"#ccd_send_message\").html(data);\n }\n $(\".viewCCD_transmit\").removeAttr('disabled');\n });\n }\n });\n <?php } ?>", " <?php\n if ($oefax) {\n $eventDispatcher->dispatch(PatientReportEvent::JAVASCRIPT_READY_POST, new GenericEvent());\n }\n ?>", "});", "// select/deselect the Forms related to the selected Encounter\n// (it ain't pretty code folks)\nvar SelectForms = function (selectedEncounter) {\n if ($(selectedEncounter).prop(\"checked\")) {\n $(selectedEncounter).parent().children().each(function(i, obj) {\n $(this).children().each(function(i, obj) {\n $(this).prop(\"checked\", true);\n });\n });\n }\n else {\n $(selectedEncounter).parent().children().each(function(i, obj) {\n $(this).children().each(function(i, obj) {\n $(this).prop(\"checked\", false);\n });\n });\n }\n}", "// When an issue is checked, auto-check all the related encounters and forms\nfunction issueClick(issue) {\n // do nothing when unchecked\n if (! $(issue).attr(\"checked\")) return;", " $(\"#report_form :checkbox\").each(function(i, obj) {\n if ($(issue).val().indexOf('/' + $(this).val() + '/') >= 0) {\n $(this).attr(\"checked\", \"checked\");\n }\n });\n}", "var listId = '#' + <?php echo js_escape($list_id); ?>;\n$(function () {\n $(listId).addClass(\"active\");\n});", "</script>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Multi-Factor Authentication Management\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "require_once(\"../globals.php\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "function writeRow($method, $name, $allowEdit = false)\n{\n echo \" <tr><td>&nbsp;\";\n if ($name == '') {\n echo '<i class=\"fa fa-exclamation-circle oe-text-orange\" aria-hidden=\"true\"></i>' . ' ' . text($method);\n } else {\n echo text($method);\n }\n echo \"&nbsp;</td><td>&nbsp;\";\n echo text($name);\n echo \"&nbsp;</td><td>\";\n if ($allowEdit) {\n echo \"<button type='button' class='btn btn-secondary btn-search' onclick='editclick(\" . attr_js($method) . \")'>\" . xlt('View') . \"</button> &nbsp\";\n }\n if ($name) {\n echo \"<button type='button' class='btn btn-secondary btn-delete' onclick='delclick(\" . attr_js($method) . \", \" .\n attr_js($name) . \")'>\" . xlt('Delete') . \"</button>\";\n }\n echo \"</td></tr>\\n\";\n}", "$userid = $_SESSION['authUserID'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];\n$message = '';\nif (!empty($_POST['form_delete_method'])) {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n // Delete the indicated MFA instance.\n sqlStatement(\n \"DELETE FROM login_mfa_registrations WHERE user_id = ? AND method = ? AND name = ?\",\n array($userid, $_POST['form_delete_method'], $_POST['form_delete_name'])\n );\n $message = xl('Delete successful.');\n}\n?>\n<!DOCTYPE html>\n<html>\n<head>\n <?php Header::setupHeader(); ?>", "<title><?php echo xlt('Manage Multi Factor Authentication'); ?></title>\n<script>", "function delclick(mfamethod, mfaname) {\n var f = document.forms[0];\n f.form_delete_method.value = mfamethod;\n f.form_delete_name.value = mfaname;\n top.restoreSession();\n f.submit();\n}", "function editclick(method) {\n top.restoreSession();\n if (method == 'TOTP') {\n window.location.href = 'mfa_totp.php?action=reg1';\n }\n else {\n alert(<?php echo xlj('Not yet implemented.'); ?>);\n }\n}", "function addclick(sel) {\n top.restoreSession();\n if (sel.value) {\n if (sel.value == 'U2F') {\n window.location.href = 'mfa_u2f.php?action=reg1';\n } else if (sel.value == 'TOTP') {\n window.location.href = 'mfa_totp.php?action=reg1';\n }\n else {\n alert(<?php echo xlj('Not yet implemented.'); ?>);\n }\n }\n sel.selectedIndex = 0;\n}", "</script>\n<?php\n$arrOeUiSettings = array(\n 'heading_title' => xl('Manage Multi Factor Authentication'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => true,\n 'help_file_name' => \"mfa_help.php\"\n);\n$oemr_ui = new OemrUI($arrOeUiSettings);\n?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php\n if ($message) {?>\n <div id=\"display_msg\" class=\"alert alert-danger\" style=\"font-size:100%; font-weight:700\"><?php echo text($message); ?></div>\n <?php\n }\n ?>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <form method='post' action='mfa_registrations.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n <div>\n <fieldset>", " <legend><?php echo xlt('Current Authentication Method for') . \" \" . $user_full_name; ?></legend>", " <table class='table'>\n <tr>\n <th align='left'>&nbsp;<?php echo xlt('Method'); ?>&nbsp;</th>\n <th align='left'>&nbsp;<?php echo xlt('Key Name'); ?>&nbsp;</th>\n <th align='left'>&nbsp;<?php echo xlt('Action'); ?>&nbsp;</th>\n </tr>\n <?php\n $res = sqlStatement(\"SELECT name, method FROM login_mfa_registrations WHERE \" .\n \"user_id = ? ORDER BY method, name\", array($userid));\n $disableNewTotp = false;\n if (sqlNumRows($res)) {\n while ($row = sqlFetchArray($res)) {\n if ($row['method'] == \"TOTP\") {\n $disableNewTotp = true;\n writeRow($row['method'], $row['name'], true);\n } else {\n writeRow($row['method'], $row['name']);\n }\n }\n } else {\n writeRow(xl(\"No method enabled\"), '');\n }\n ?>\n </table>\n </fieldset>\n </div>\n <div>\n <fieldset>", " <legend><?php echo xlt('Select/Add New Authentication Method for') . \" \" . $user_full_name; ?></legend>", " <div class='col-sm-4 offset-sm-4'>\n <select name='form_add' onchange='addclick(this)'class='col-sm-12'>\n <option value=''><?php echo xlt('Add New...'); ?></option>\n <option value='U2F'><?php echo xlt('U2F USB Device'); ?></option>\n <option value='TOTP'\n <?php echo ($disableNewTotp) ? 'title=\"' . xla('Only one TOTP Key can be set up per user') . '\"' : ''; ?>\n <?php echo ($disableNewTotp) ? 'disabled' : ''; ?>>\n <?php echo xlt('TOTP Key'); ?>\n </option>\n </select>\n </div>\n <input type='hidden' name='form_delete_method' value='' />\n <input type='hidden' name='form_delete_name' value='' />\n </fieldset>\n </div>\n </form>\n </div>\n </div>", " </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Multi-Factor Authentication Management\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "require_once(\"../globals.php\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "function writeRow($method, $name, $allowEdit = false)\n{\n echo \" <tr><td>&nbsp;\";\n if ($name == '') {\n echo '<i class=\"fa fa-exclamation-circle oe-text-orange\" aria-hidden=\"true\"></i>' . ' ' . text($method);\n } else {\n echo text($method);\n }\n echo \"&nbsp;</td><td>&nbsp;\";\n echo text($name);\n echo \"&nbsp;</td><td>\";\n if ($allowEdit) {\n echo \"<button type='button' class='btn btn-secondary btn-search' onclick='editclick(\" . attr_js($method) . \")'>\" . xlt('View') . \"</button> &nbsp\";\n }\n if ($name) {\n echo \"<button type='button' class='btn btn-secondary btn-delete' onclick='delclick(\" . attr_js($method) . \", \" .\n attr_js($name) . \")'>\" . xlt('Delete') . \"</button>\";\n }\n echo \"</td></tr>\\n\";\n}", "$userid = $_SESSION['authUserID'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];\n$message = '';\nif (!empty($_POST['form_delete_method'])) {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n // Delete the indicated MFA instance.\n sqlStatement(\n \"DELETE FROM login_mfa_registrations WHERE user_id = ? AND method = ? AND name = ?\",\n array($userid, $_POST['form_delete_method'], $_POST['form_delete_name'])\n );\n $message = xl('Delete successful.');\n}\n?>\n<!DOCTYPE html>\n<html>\n<head>\n <?php Header::setupHeader(); ?>", "<title><?php echo xlt('Manage Multi Factor Authentication'); ?></title>\n<script>", "function delclick(mfamethod, mfaname) {\n var f = document.forms[0];\n f.form_delete_method.value = mfamethod;\n f.form_delete_name.value = mfaname;\n top.restoreSession();\n f.submit();\n}", "function editclick(method) {\n top.restoreSession();\n if (method == 'TOTP') {\n window.location.href = 'mfa_totp.php?action=reg1';\n }\n else {\n alert(<?php echo xlj('Not yet implemented.'); ?>);\n }\n}", "function addclick(sel) {\n top.restoreSession();\n if (sel.value) {\n if (sel.value == 'U2F') {\n window.location.href = 'mfa_u2f.php?action=reg1';\n } else if (sel.value == 'TOTP') {\n window.location.href = 'mfa_totp.php?action=reg1';\n }\n else {\n alert(<?php echo xlj('Not yet implemented.'); ?>);\n }\n }\n sel.selectedIndex = 0;\n}", "</script>\n<?php\n$arrOeUiSettings = array(\n 'heading_title' => xl('Manage Multi Factor Authentication'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => true,\n 'help_file_name' => \"mfa_help.php\"\n);\n$oemr_ui = new OemrUI($arrOeUiSettings);\n?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php\n if ($message) {?>\n <div id=\"display_msg\" class=\"alert alert-danger\" style=\"font-size:100%; font-weight:700\"><?php echo text($message); ?></div>\n <?php\n }\n ?>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <form method='post' action='mfa_registrations.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n <div>\n <fieldset>", " <legend><?php echo xlt('Current Authentication Method for') . \" \" . text($user_full_name); ?></legend>", " <table class='table'>\n <tr>\n <th align='left'>&nbsp;<?php echo xlt('Method'); ?>&nbsp;</th>\n <th align='left'>&nbsp;<?php echo xlt('Key Name'); ?>&nbsp;</th>\n <th align='left'>&nbsp;<?php echo xlt('Action'); ?>&nbsp;</th>\n </tr>\n <?php\n $res = sqlStatement(\"SELECT name, method FROM login_mfa_registrations WHERE \" .\n \"user_id = ? ORDER BY method, name\", array($userid));\n $disableNewTotp = false;\n if (sqlNumRows($res)) {\n while ($row = sqlFetchArray($res)) {\n if ($row['method'] == \"TOTP\") {\n $disableNewTotp = true;\n writeRow($row['method'], $row['name'], true);\n } else {\n writeRow($row['method'], $row['name']);\n }\n }\n } else {\n writeRow(xl(\"No method enabled\"), '');\n }\n ?>\n </table>\n </fieldset>\n </div>\n <div>\n <fieldset>", " <legend><?php echo xlt('Select/Add New Authentication Method for') . \" \" . text($user_full_name); ?></legend>", " <div class='col-sm-4 offset-sm-4'>\n <select name='form_add' onchange='addclick(this)'class='col-sm-12'>\n <option value=''><?php echo xlt('Add New...'); ?></option>\n <option value='U2F'><?php echo xlt('U2F USB Device'); ?></option>\n <option value='TOTP'\n <?php echo ($disableNewTotp) ? 'title=\"' . xla('Only one TOTP Key can be set up per user') . '\"' : ''; ?>\n <?php echo ($disableNewTotp) ? 'disabled' : ''; ?>>\n <?php echo xlt('TOTP Key'); ?>\n </option>\n </select>\n </div>\n <input type='hidden' name='form_delete_method' value='' />\n <input type='hidden' name='form_delete_name' value='' />\n </fieldset>\n </div>\n </form>\n </div>\n </div>", " </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * App Based TOTP Support\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Anthony Zullo <anthonykzullo@gmail.com>\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2019 Anthony Zullo <anthonykzullo@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "// Set $sessionAllowWrite to true to prevent session concurrency issues during authorization related code\n$sessionAllowWrite = true;\nrequire_once('../globals.php');\nrequire_once(\"$srcdir/classes/Totp.class.php\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Auth\\AuthUtils;\nuse OpenEMR\\Common\\Crypto\\CryptoGen;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "$userid = $_SESSION['authUserID'];\n$action = $_REQUEST['action'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];", "?>\n<html>\n<head>\n <?php Header::setupHeader(); ?>\n <title><?php echo xlt('TOTP Registration'); ?></title>\n <script>", " function doregister(step, error) {\n var f = document.forms[0];\n f.action.value = step;\n if (error) {\n f.error.value = error;\n }\n f.action.value = step;\n top.restoreSession();\n f.submit();\n }", " function docancel() {\n var redirectUrl = 'mfa_registrations.php';\n window.location.href = 'mfa_registrations.php';\n }", " $(function () {\n $('#clearPass').focus();\n });\n </script>\n <style>\n p {\n text-align: center\n }\n .alert-msg {\n font-size:100%;\n font-weight:700;\n }\n </style>\n <?php\n $arrOeUiSettings = array(\n 'heading_title' => xl('Register Time Based One Time Password Key') . \" - \" . xl('TOTP'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => false,\n 'help_file_name' => \"\"\n );\n $oemr_ui = new OemrUI($arrOeUiSettings);\n ?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <?php\n // If current step is reg1 or reg2, display the header\n if ($action == 'reg1' || $action == 'reg2') { ?>\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <?php\n } ?> <div class=\"row\">\n <div class=\"col-sm-12\">\n <form method='post' class=\"form-horizontal\" action='mfa_totp.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />", "", "\n <?php\n // step 1 is to verify the password\n if ($action == 'reg1') {\n $error = (isset($_GET[\"error\"])) ? $_GET[\"error\"] : false;\n ?>\n <div>\n <fieldset>", " <legend><?php echo xlt('Provide Password for') . \" \" . $user_full_name; ?></legend>", " <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php if ($error == \"auth\") { ?>\n <div class=\"alert alert-danger alert-msg login-failure m-1\">\n <?php echo xlt('Invalid password'); ?>\n </div>\n <?php } ?>\n <p><?php echo xlt('In order to register your device, please provide your OpenEMR login password'); ?></p>\n <div class=\"col-sm-4 offset-sm-4\">\n <input type=\"password\" class=\"form-control\" id=\"clearPass\" name=\"clearPass\" placeholder=\"<?php echo xla('Password'); ?>:\" >\n </div>\n </div>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value=\"<?php echo xla('Submit'); ?>\" onclick=\"doregister('reg2')\"><?php echo xlt('Submit'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n </div>\n </div>\n </div>\n <?php\n // step 2 is to validate password and display qr code\n } elseif ($action == 'reg2') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }", " // Redirect back to step 1 if user password is incorrect\n if (!(new AuthUtils())->confirmPassword($_SESSION['authUser'], $_POST['clearPass'])) {\n header(\"Location: mfa_totp.php?action=reg1&error=auth\");\n exit();\n }", " // Determines whether existing TOTP method exists already\n $existingSecret = privQuery(\n \"SELECT var1 FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `method` = 'TOTP'\",\n array($userid)\n );\n if (empty($existingSecret['var1'])) {\n $secret = false;\n $doesExist = false;\n } else {\n $cryptoGen = new CryptoGen();\n $secret = $cryptoGen->decryptStandard($existingSecret['var1']);\n $doesExist = true;\n }", " // Generate a new QR code or existing QR code\n $googleAuth = new Totp($secret, $_SESSION['authUser']);\n $qr = $googleAuth->generateQrCode();", "\n // if secret did not exist previously, stores secret in session variable for saving\n if (!$doesExist) {\n $_SESSION['totpSecret'] = $googleAuth->getSecret();\n }\n ?>\n <fieldset>", " <legend><?php echo xlt('Register TOTP Key for') . \" \" . $user_full_name; ?></legend>", " <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php if (!$doesExist) { ?>\n <p>\n <?php echo xlt('Scan the following QR code with your preferred authenticator app to register a new TOTP key.'); ?>\n </p>\n <?php } else { // $doesExist ?>\n <p>\n <?php echo xlt('Your current TOTP key QR code is displayed below.'); ?>\n </p>\n <?php } ?>\n <br />\n <img src=\"<?php echo attr($qr); ?>\" class=\"img-responsive center-block\" style=\"height:200px !Important\"/>\n <br />\n <p><?php echo xlt('Example authenticator apps include'); ?></p>:\n <div class=\"col-sm-4 offset-sm-4\">\n <ul>\n <li><?php echo xlt('Google Auth'); ?>\n (<a href=\"https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8\" target=\"_blank\" rel=\"noopener\">\n <?php echo xlt('ios'); ?>\n </a>,\n <a href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en\" target=\"_blank\" rel=\"noopener\">\n <?php echo xlt('android'); ?>\n </a>)</li>\n <li><?php echo xlt('Authy'); ?>\n (<a href=\"https://itunes.apple.com/us/app/authy/id494168017?mt=8\" target=\"_blank\" rel=\"noopener\"><?php echo xlt('ios'); ?></a>, <a href=\"https://play.google.com/store/apps/details?id=com.authy.authy&hl=en\" target=\"_blank\" rel=\"noopener\"><?php echo xlt('android'); ?></a>)</li>\n </ul>\n </div>\n </div>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <?php if (!$doesExist) { ?>\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value=\"<?php echo xla('Register'); ?>\" onclick=\"doregister('reg3')\"><?php echo xlt('Register'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n <?php } else { // $doesExist ?>\n <button type=\"button\" class=\"btn btn-link btn-back\" value=\"<?php echo xla('Back'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Back'); ?></button>\n <?php } ?>\n </div>\n </div>\n </div>\n <?php\n // step 3 is to save the qr code\n } elseif ($action == 'reg3') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }", " echo \"<script>\\n\";", " // Verify that no TOTP method exists already\n $row = privQuery(\n \"SELECT COUNT(*) AS count FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `method` = 'TOTP'\",\n array($userid)\n );", "\n if (empty($row['count']) && isset($_SESSION['totpSecret'])) {\n $cryptoGen = new CryptoGen();\n privStatement(\n \"INSERT INTO login_mfa_registrations \" .\n \"(`user_id`, `method`, `name`, `var1`, `var2`) VALUES \" .\n \"(?, 'TOTP', 'App Based 2FA', ?, '')\",\n array($userid, $cryptoGen->encryptStandard($_SESSION['totpSecret']))\n );\n unset($_SESSION['totpSecret']);\n } else {\n echo \" alert(\" . xlj('TOTP Method already exists and is enabled. Try again.') . \");\\n\";\n }", " echo \"window.location.href = 'mfa_registrations.php';\\n\";\n echo \"</script>\\n\";\n }\n ?>", " <input type='hidden' name='action' value='' />\n <input type='hidden' name='error' value='' />\n </form>\n </div>\n </div>\n </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * App Based TOTP Support\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Anthony Zullo <anthonykzullo@gmail.com>\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2019 Anthony Zullo <anthonykzullo@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018-2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "// Set $sessionAllowWrite to true to prevent session concurrency issues during authorization related code\n$sessionAllowWrite = true;\nrequire_once('../globals.php');\nrequire_once(\"$srcdir/classes/Totp.class.php\");\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Auth\\AuthUtils;\nuse OpenEMR\\Common\\Crypto\\CryptoGen;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "$userid = $_SESSION['authUserID'];\n$action = $_REQUEST['action'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];", "?>\n<html>\n<head>\n <?php Header::setupHeader(); ?>\n <title><?php echo xlt('TOTP Registration'); ?></title>\n <script>", " function doregister(step, error) {\n var f = document.forms[0];\n f.action.value = step;\n if (error) {\n f.error.value = error;\n }\n f.action.value = step;\n top.restoreSession();\n f.submit();\n }", " function docancel() {\n var redirectUrl = 'mfa_registrations.php';\n window.location.href = 'mfa_registrations.php';\n }", " $(function () {\n $('#clearPass').focus();\n });\n </script>\n <style>\n p {\n text-align: center\n }\n .alert-msg {\n font-size:100%;\n font-weight:700;\n }\n </style>\n <?php\n $arrOeUiSettings = array(\n 'heading_title' => xl('Register Time Based One Time Password Key') . \" - \" . xl('TOTP'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => false,\n 'help_file_name' => \"\"\n );\n $oemr_ui = new OemrUI($arrOeUiSettings);\n ?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <?php\n // If current step is reg1 or reg2, display the header\n if ($action == 'reg1' || $action == 'reg2') { ?>\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <?php\n } ?> <div class=\"row\">\n <div class=\"col-sm-12\">\n <form method='post' class=\"form-horizontal\" action='mfa_totp.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />", "", "\n <?php\n // step 1 is to verify the password\n if ($action == 'reg1') {\n $error = (isset($_GET[\"error\"])) ? $_GET[\"error\"] : false;\n ?>\n <div>\n <fieldset>", " <legend><?php echo xlt('Provide Password for') . \" \" . text($user_full_name); ?></legend>", " <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php if ($error == \"auth\") { ?>\n <div class=\"alert alert-danger alert-msg login-failure m-1\">\n <?php echo xlt('Invalid password'); ?>\n </div>\n <?php } ?>\n <p><?php echo xlt('In order to register your device, please provide your OpenEMR login password'); ?></p>\n <div class=\"col-sm-4 offset-sm-4\">\n <input type=\"password\" class=\"form-control\" id=\"clearPass\" name=\"clearPass\" placeholder=\"<?php echo xla('Password'); ?>:\" >\n </div>\n </div>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value=\"<?php echo xla('Submit'); ?>\" onclick=\"doregister('reg2')\"><?php echo xlt('Submit'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n </div>\n </div>\n </div>\n <?php\n // step 2 is to validate password and display qr code\n } elseif ($action == 'reg2') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }", " // Redirect back to step 1 if user password is incorrect\n if (!(new AuthUtils())->confirmPassword($_SESSION['authUser'], $_POST['clearPass'])) {\n header(\"Location: mfa_totp.php?action=reg1&error=auth\");\n exit();\n }", " // Determines whether existing TOTP method exists already\n $existingSecret = privQuery(\n \"SELECT var1 FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `method` = 'TOTP'\",\n array($userid)\n );\n if (empty($existingSecret['var1'])) {\n $secret = false;\n $doesExist = false;\n } else {\n $cryptoGen = new CryptoGen();\n $secret = $cryptoGen->decryptStandard($existingSecret['var1']);\n $doesExist = true;\n }", " // Generate a new QR code or existing QR code\n $googleAuth = new Totp($secret, $_SESSION['authUser']);\n $qr = $googleAuth->generateQrCode();", "\n // if secret did not exist previously, stores secret in session variable for saving\n if (!$doesExist) {\n $_SESSION['totpSecret'] = $googleAuth->getSecret();\n }\n ?>\n <fieldset>", " <legend><?php echo xlt('Register TOTP Key for') . \" \" . text($user_full_name); ?></legend>", " <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php if (!$doesExist) { ?>\n <p>\n <?php echo xlt('Scan the following QR code with your preferred authenticator app to register a new TOTP key.'); ?>\n </p>\n <?php } else { // $doesExist ?>\n <p>\n <?php echo xlt('Your current TOTP key QR code is displayed below.'); ?>\n </p>\n <?php } ?>\n <br />\n <img src=\"<?php echo attr($qr); ?>\" class=\"img-responsive center-block\" style=\"height:200px !Important\"/>\n <br />\n <p><?php echo xlt('Example authenticator apps include'); ?></p>:\n <div class=\"col-sm-4 offset-sm-4\">\n <ul>\n <li><?php echo xlt('Google Auth'); ?>\n (<a href=\"https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8\" target=\"_blank\" rel=\"noopener\">\n <?php echo xlt('ios'); ?>\n </a>,\n <a href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en\" target=\"_blank\" rel=\"noopener\">\n <?php echo xlt('android'); ?>\n </a>)</li>\n <li><?php echo xlt('Authy'); ?>\n (<a href=\"https://itunes.apple.com/us/app/authy/id494168017?mt=8\" target=\"_blank\" rel=\"noopener\"><?php echo xlt('ios'); ?></a>, <a href=\"https://play.google.com/store/apps/details?id=com.authy.authy&hl=en\" target=\"_blank\" rel=\"noopener\"><?php echo xlt('android'); ?></a>)</li>\n </ul>\n </div>\n </div>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <?php if (!$doesExist) { ?>\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value=\"<?php echo xla('Register'); ?>\" onclick=\"doregister('reg3')\"><?php echo xlt('Register'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n <?php } else { // $doesExist ?>\n <button type=\"button\" class=\"btn btn-link btn-back\" value=\"<?php echo xla('Back'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Back'); ?></button>\n <?php } ?>\n </div>\n </div>\n </div>\n <?php\n // step 3 is to save the qr code\n } elseif ($action == 'reg3') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }", " echo \"<script>\\n\";", " // Verify that no TOTP method exists already\n $row = privQuery(\n \"SELECT COUNT(*) AS count FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `method` = 'TOTP'\",\n array($userid)\n );", "\n if (empty($row['count']) && isset($_SESSION['totpSecret'])) {\n $cryptoGen = new CryptoGen();\n privStatement(\n \"INSERT INTO login_mfa_registrations \" .\n \"(`user_id`, `method`, `name`, `var1`, `var2`) VALUES \" .\n \"(?, 'TOTP', 'App Based 2FA', ?, '')\",\n array($userid, $cryptoGen->encryptStandard($_SESSION['totpSecret']))\n );\n unset($_SESSION['totpSecret']);\n } else {\n echo \" alert(\" . xlj('TOTP Method already exists and is enabled. Try again.') . \");\\n\";\n }", " echo \"window.location.href = 'mfa_registrations.php';\\n\";\n echo \"</script>\\n\";\n }\n ?>", " <input type='hidden' name='action' value='' />\n <input type='hidden' name='error' value='' />\n </form>\n </div>\n </div>\n </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FIDO U2F Support Module\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "require_once('../globals.php');\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "// https is required, and with a proxy the server might not see it.\n$scheme = \"https://\"; // isset($_SERVER['HTTPS']) ? \"https://\" : \"http://\";\n$appId = $scheme . $_SERVER['HTTP_HOST'];\n$u2f = new u2flib_server\\U2F($appId);", "$userid = $_SESSION['authUserID'];\n$action = $_REQUEST['action'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];\n?>\n<html>\n<head>\n<?php Header::setupHeader(); ?>\n<title><?php echo xlt('U2F Registration'); ?></title>\n<script src=\"<?php echo $GLOBALS['webroot'] ?>/library/js/u2f-api.js\"></script>\n<script>", "function doregister() {\n var f = document.forms[0];\n if (f.form_name.value.trim() == '') {\n alert(<?php echo xlj(\"Please enter a name for this key.\"); ?>);\n return;\n }\n var request = JSON.parse(f.form_request.value);\n u2f.register(\n <?php echo js_escape($appId); ?>,\n [request],\n [],\n function(data) {\n if(data.errorCode && data.errorCode != 0) {\n alert(<?php echo xlj(\"Registration failed with error\"); ?> + ' ' + data.errorCode);\n return;\n }\n f.form_registration.value = JSON.stringify(data);\n f.action.value = 'reg2';\n top.restoreSession();\n f.submit();\n },\n 60\n );\n}", "function docancel() {\n window.location.href = 'mfa_registrations.php';\n}", "</script>\n<?php\n $arrOeUiSettings = array(\n 'heading_title' => xl('Register Universal 2nd Factor Key') . \" - \" . xl('U2F'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => false,\n 'help_file_name' => \"\"\n );\n $oemr_ui = new OemrUI($arrOeUiSettings);\n ?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <form method='post' action='mfa_u2f.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />", " <?php", " ///////////////////////////////////////////////////////////////////////", " if ($action == 'reg1') {\n list ($request, $signs) = $u2f->getRegisterData();\n ?>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <fieldset>", " <legend><?php echo xlt('Register U2F Key for') . \" \" . $user_full_name; ?></legend>", " <div class='col-sm-12'>\n <p><?php echo xlt(\"Instructions\");?>:\n <ul>\n <li><?php echo xlt('This will register a new U2F USB key'); ?></li>\n <li><?php echo xlt('Type a name for your key, insert it into a USB port and click the Register button below'); ?></li>\n <li><?php echo xlt('Then press the flashing button on your key within 1 minute to complete registration'); ?></li>\n </ul>\n </div>", " <div class=\"form-group\">\n <label for=\"form_name\" class=\"col-sm-2 col-form-label\"><?php echo xlt('Please give this key a name'); ?></label>\n <div class=\"col-sm-4\">\n <input type='text' class='form-control' name='form_name' id='form_name'>\n <input type='hidden' name='form_request' value='<?php echo attr(json_encode($request)); ?>'>\n <input type='hidden' name='form_signs' value='<?php echo attr(json_encode($signs)); ?>'>\n <input type='hidden' name='form_registration' value=''>\n </div>\n </div>", " <div class='col-sm-12'>\n <ul>\n <li><?php echo xlt('A secure (HTTPS) web connection is required for U2F'); ?></li>\n <li><?php echo xlt('Chrome browser version 41 and above, Mozilla Firefox browser version 64 and above, Microsoft Edge browser version 19 and above, Safari browser version 13 and above, Opera browser version 40 and Opera browser version 42 and above support FIDO U2F API'); ?></li>\n <li><?php echo xlt('Internet Explorer browser version 6 to Internet Explorer browser version 11 does not support FIDO U2F API'); ?></li>", " <li><?php echo xlt('For U2F support on Linux click'); ?>: <a href='https://www.key-id.com/enable-fido-u2f-linux/' rel=\"noopener\" target='_blank'><?php echo text('Enable FIDO U2F Linux'); ?></a></li>\n <li><?php echo xlt('For Firefox click'); ?>: <a href='https://www.trishtech.com/2018/07/enable-fido-u2f-security-key-yubikey-in-mozilla-firefox/' rel=\"noopener\" target='_blank'><?php echo text('Enable FIDO U2F Key in Firefox'); ?></a></li>\n </ul>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value='<?php echo xla('Register'); ?>' onclick='doregister()'><?php echo xlt('Register'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n </div>\n </div>\n </div>\n </div>\n <?php\n } elseif ($action == 'reg2') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n try {\n $data = $u2f->doRegister(json_decode($_POST['form_request']), json_decode($_POST['form_registration']));\n } catch (u2flib_server\\Error $e) {\n die(xlt('Registration error') . ': ' . text($e->getMessage()));\n }\n echo \"<script>\\n\";\n $row = sqlQuery(\n \"SELECT COUNT(*) AS count FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `name` = ?\",\n array($userid, $_POST['form_name'])\n );\n if (empty($row['count'])) {\n sqlStatement(\n \"INSERT INTO login_mfa_registrations \" .\n \"(`user_id`, `method`, `name`, `var1`, `var2`) VALUES \" .\n \"(?, 'U2F', ?, ?, ?)\",\n array($userid, $_POST['form_name'], json_encode($data), '')\n );\n } else {\n echo \" alert(\" . xlj('This key name is already in use by you. Try again.') . \");\\n\";\n }\n echo \" window.location.href = 'mfa_registrations.php';\\n\";\n echo \"</script>\\n\";\n }", " ///////////////////////////////////////////////////////////////////////", " ?>", " <input type='hidden' name='action' value='' />\n </form>\n </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FIDO U2F Support Module\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Rod Roark <rod@sunsetsystems.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2018 Rod Roark <rod@sunsetsystems.com>\n * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE CNU General Public License 3\n */", "require_once('../globals.php');\nrequire_once(\"$srcdir/options.inc.php\");", "use OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\OeUI\\OemrUI;", "// https is required, and with a proxy the server might not see it.\n$scheme = \"https://\"; // isset($_SERVER['HTTPS']) ? \"https://\" : \"http://\";\n$appId = $scheme . $_SERVER['HTTP_HOST'];\n$u2f = new u2flib_server\\U2F($appId);", "$userid = $_SESSION['authUserID'];\n$action = $_REQUEST['action'];\n$user_name = getUserIDInfo($userid);\n$user_full_name = $user_name['fname'] . \" \" . $user_name['lname'];\n?>\n<html>\n<head>\n<?php Header::setupHeader(); ?>\n<title><?php echo xlt('U2F Registration'); ?></title>\n<script src=\"<?php echo $GLOBALS['webroot'] ?>/library/js/u2f-api.js\"></script>\n<script>", "function doregister() {\n var f = document.forms[0];\n if (f.form_name.value.trim() == '') {\n alert(<?php echo xlj(\"Please enter a name for this key.\"); ?>);\n return;\n }\n var request = JSON.parse(f.form_request.value);\n u2f.register(\n <?php echo js_escape($appId); ?>,\n [request],\n [],\n function(data) {\n if(data.errorCode && data.errorCode != 0) {\n alert(<?php echo xlj(\"Registration failed with error\"); ?> + ' ' + data.errorCode);\n return;\n }\n f.form_registration.value = JSON.stringify(data);\n f.action.value = 'reg2';\n top.restoreSession();\n f.submit();\n },\n 60\n );\n}", "function docancel() {\n window.location.href = 'mfa_registrations.php';\n}", "</script>\n<?php\n $arrOeUiSettings = array(\n 'heading_title' => xl('Register Universal 2nd Factor Key') . \" - \" . xl('U2F'),\n 'include_patient_name' => false,\n 'expandable' => false,\n 'expandable_files' => array(),//all file names need suffix _xpd\n 'action' => \"\",//conceal, reveal, search, reset, link or back\n 'action_title' => \"\",\n 'action_href' => \"\",//only for actions - reset, link or back\n 'show_help_icon' => false,\n 'help_file_name' => \"\"\n );\n $oemr_ui = new OemrUI($arrOeUiSettings);\n ?>\n</head>\n<body class=\"body_top\">\n <div id=\"container_div\" class=\"<?php echo $oemr_ui->oeContainer();?>\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <?php echo $oemr_ui->pageHeading() . \"\\r\\n\"; ?>\n </div>\n </div>\n <form method='post' action='mfa_u2f.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />", " <?php", " ///////////////////////////////////////////////////////////////////////", " if ($action == 'reg1') {\n list ($request, $signs) = $u2f->getRegisterData();\n ?>\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <fieldset>", " <legend><?php echo xlt('Register U2F Key for') . \" \" . text($user_full_name); ?></legend>", " <div class='col-sm-12'>\n <p><?php echo xlt(\"Instructions\");?>:\n <ul>\n <li><?php echo xlt('This will register a new U2F USB key'); ?></li>\n <li><?php echo xlt('Type a name for your key, insert it into a USB port and click the Register button below'); ?></li>\n <li><?php echo xlt('Then press the flashing button on your key within 1 minute to complete registration'); ?></li>\n </ul>\n </div>", " <div class=\"form-group\">\n <label for=\"form_name\" class=\"col-sm-2 col-form-label\"><?php echo xlt('Please give this key a name'); ?></label>\n <div class=\"col-sm-4\">\n <input type='text' class='form-control' name='form_name' id='form_name'>\n <input type='hidden' name='form_request' value='<?php echo attr(json_encode($request)); ?>'>\n <input type='hidden' name='form_signs' value='<?php echo attr(json_encode($signs)); ?>'>\n <input type='hidden' name='form_registration' value=''>\n </div>\n </div>", " <div class='col-sm-12'>\n <ul>\n <li><?php echo xlt('A secure (HTTPS) web connection is required for U2F'); ?></li>\n <li><?php echo xlt('Chrome browser version 41 and above, Mozilla Firefox browser version 64 and above, Microsoft Edge browser version 19 and above, Safari browser version 13 and above, Opera browser version 40 and Opera browser version 42 and above support FIDO U2F API'); ?></li>\n <li><?php echo xlt('Internet Explorer browser version 6 to Internet Explorer browser version 11 does not support FIDO U2F API'); ?></li>", " <li><?php echo xlt('For U2F support on Linux click'); ?>: <a href='https://www.key-id.com/enable-fido-u2f-linux/' rel=\"noopener\" target='_blank'><?php echo text('Enable FIDO U2F Linux'); ?></a></li>\n <li><?php echo xlt('For Firefox click'); ?>: <a href='https://www.trishtech.com/2018/07/enable-fido-u2f-security-key-yubikey-in-mozilla-firefox/' rel=\"noopener\" target='_blank'><?php echo text('Enable FIDO U2F Key in Firefox'); ?></a></li>\n </ul>\n </div>\n </fieldset>\n <div class=\"form-group clearfix\">\n <div class=\"col-sm-12 text-left position-override\">\n <button type=\"button\" class=\"btn btn-secondary btn-save\" value='<?php echo xla('Register'); ?>' onclick='doregister()'><?php echo xlt('Register'); ?></button>\n <button type=\"button\" class=\"btn btn-link btn-cancel\" value=\"<?php echo xla('Cancel'); ?>\" onclick=\"docancel()\" ><?php echo xlt('Cancel'); ?></button>\n </div>\n </div>\n </div>\n </div>\n <?php\n } elseif ($action == 'reg2') {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n try {\n $data = $u2f->doRegister(json_decode($_POST['form_request']), json_decode($_POST['form_registration']));\n } catch (u2flib_server\\Error $e) {\n die(xlt('Registration error') . ': ' . text($e->getMessage()));\n }\n echo \"<script>\\n\";\n $row = sqlQuery(\n \"SELECT COUNT(*) AS count FROM login_mfa_registrations WHERE \" .\n \"`user_id` = ? AND `name` = ?\",\n array($userid, $_POST['form_name'])\n );\n if (empty($row['count'])) {\n sqlStatement(\n \"INSERT INTO login_mfa_registrations \" .\n \"(`user_id`, `method`, `name`, `var1`, `var2`) VALUES \" .\n \"(?, 'U2F', ?, ?, ?)\",\n array($userid, $_POST['form_name'], json_encode($data), '')\n );\n } else {\n echo \" alert(\" . xlj('This key name is already in use by you. Try again.') . \");\\n\";\n }\n echo \" window.location.href = 'mfa_registrations.php';\\n\";\n echo \"</script>\\n\";\n }", " ///////////////////////////////////////////////////////////////////////", " ?>", " <input type='hidden' name='action' value='' />\n </form>\n </div><!--end of container div -->\n <?php $oemr_ui->oeBelowContainerDiv();?>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This script Assign acl 'Emergency login'.\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Roberto Vasquez <robertogagliotta@gmail.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @author Daniel Pflieger <daniel@mi-squared.com> <daniel@growlingflea.com>\n * @author Ken Chapple <ken@mi-squared.com>\n * @copyright Copyright (c) 2015 Roberto Vasquez <robertogagliotta@gmail.com>\n * @copyright Copyright (c) 2017-2019 Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2021 Daniel Pflieger <daniel@mi-squared.com> <daniel@growlingflea.com>\n * @copyright Copyright (c) 2021 Ken Chapple <ken@mi-squared.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "$sessionAllowWrite = true;\nrequire_once(\"../globals.php\");\nrequire_once(\"$srcdir/auth.inc\");", "use OpenEMR\\Common\\Acl\\AclExtended;\nuse OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Common\\Auth\\AuthUtils;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\Services\\UserService;\nuse OpenEMR\\Events\\User\\UserUpdatedEvent;\nuse OpenEMR\\Events\\User\\UserCreatedEvent;", "if (!empty($_POST)) {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n}", "if (!empty($_GET)) {\n if (!CsrfUtils::verifyCsrfToken($_GET[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n}", "if (!AclMain::aclCheckCore('admin', 'users')) {\n die(xlt('Access denied'));\n}", "if (!AclMain::aclCheckCore('admin', 'super')) {\n //block non-administrator user from create administrator\n foreach ($_POST['access_group'] as $aro_group) {\n if (AclExtended::isGroupIncludeSuperuser($aro_group)) {\n die(xlt('Saving denied'));\n };\n }\n if ($_POST['mode'] === 'update') {\n //block non-administrator user from update administrator\n $user_service = new UserService();\n $user = $user_service->getUser($_POST['id']);\n $aro_groups = AclExtended::aclGetGroupTitles($user['username']);\n foreach ($aro_groups as $aro_group) {\n if (AclExtended::isGroupIncludeSuperuser($aro_group)) {\n die(xlt('Saving denied'));\n };\n }\n }\n}", "$alertmsg = '';\n$bg_msg = '';\n$set_active_msg = 0;\n$show_message = 0;", "/* Sending a mail to the admin when the breakglass user is activated only if $GLOBALS['Emergency_Login_email'] is set to 1 */\nif (!empty($_POST['access_group']) && is_array($_POST['access_group'])) {\n $bg_count = count($_POST['access_group']);\n $mail_id = explode(\".\", $SMTP_HOST);\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['active'] == 'on') && ($_POST['pre_active'] == 0)) {\n if (($_POST['get_admin_id'] == 1) && ($_POST['admin_id'] != \"\")) {\n $res = sqlStatement(\"select username from users where id= ? \", array($_POST[\"id\"]));\n $row = sqlFetchArray($res);\n $uname = $row['username'];\n $mail = new MyMailer();\n $mail->From = $GLOBALS[\"practice_return_email_path\"];\n $mail->FromName = \"Administrator OpenEMR\";\n $text_body = \"Hello Security Admin,\\n\\n The Emergency Login user \" . $uname .\n \" was activated at \" . date('l jS \\of F Y h:i:s A') . \" \\n\\nThanks,\\nAdmin OpenEMR.\";\n $mail->Body = $text_body;\n $mail->Subject = \"Emergency Login User Activated\";\n $mail->AddAddress($_POST['admin_id']);\n $mail->Send();\n }\n }\n }\n}", "/* To refresh and save variables in mail frame */\nif (isset($_POST[\"privatemode\"]) && $_POST[\"privatemode\"] == \"user_admin\") {\n if ($_POST[\"mode\"] == \"update\") {\n $user_data = sqlFetchArray(sqlStatement(\"select * from users where id= ? \", array($_POST[\"id\"])));", " if (isset($_POST[\"username\"])) {\n sqlStatement(\"update users set username=? where id= ? \", array(trim($_POST[\"username\"]), $_POST[\"id\"]));\n sqlStatement(\"update `groups` set user=? where user= ?\", array(trim($_POST[\"username\"]), $user_data[\"username\"]));\n }", " if ($_POST[\"taxid\"]) {\n sqlStatement(\"update users set federaltaxid=? where id= ? \", array($_POST[\"taxid\"], $_POST[\"id\"]));\n }", " if ($_POST[\"state_license_number\"]) {\n sqlStatement(\"update users set state_license_number=? where id= ? \", array($_POST[\"state_license_number\"], $_POST[\"id\"]));\n }", " if ($_POST[\"drugid\"]) {\n sqlStatement(\"update users set federaldrugid=? where id= ? \", array($_POST[\"drugid\"], $_POST[\"id\"]));\n }", " if ($_POST[\"upin\"]) {\n sqlStatement(\"update users set upin=? where id= ? \", array($_POST[\"upin\"], $_POST[\"id\"]));\n }", " if ($_POST[\"npi\"]) {\n sqlStatement(\"update users set npi=? where id= ? \", array($_POST[\"npi\"], $_POST[\"id\"]));\n }", " if ($_POST[\"taxonomy\"]) {\n sqlStatement(\"update users set taxonomy = ? where id= ? \", array($_POST[\"taxonomy\"], $_POST[\"id\"]));\n }", " if ($_POST[\"lname\"]) {\n sqlStatement(\"update users set lname=? where id= ? \", array($_POST[\"lname\"], $_POST[\"id\"]));\n }", " if ($_POST[\"job\"]) {\n sqlStatement(\"update users set specialty=? where id= ? \", array($_POST[\"job\"], $_POST[\"id\"]));\n }", " if ($_POST[\"mname\"]) {\n sqlStatement(\"update users set mname=? where id= ? \", array($_POST[\"mname\"], $_POST[\"id\"]));\n }", " if ($_POST[\"facility_id\"]) {\n sqlStatement(\"update users set facility_id = ? where id = ? \", array($_POST[\"facility_id\"], $_POST[\"id\"]));\n //(CHEMED) Update facility name when changing the id\n sqlStatement(\"UPDATE users, facility SET users.facility = facility.name WHERE facility.id = ? AND users.id = ?\", array($_POST[\"facility_id\"], $_POST[\"id\"]));\n //END (CHEMED)\n }", " if ($GLOBALS['restrict_user_facility'] && $_POST[\"schedule_facility\"]) {\n $sqlBindArray = [];\n $scheduledFacilityString = \"\";\n foreach ($_POST[\"schedule_facility\"] as $scheduledFacility) {\n $scheduledFacilityString .= \"?,\";\n array_push($sqlBindArray, $scheduledFacility);\n }\n if (!empty($scheduledFacilityString)) {\n $scheduledFacilityString = substr($scheduledFacilityString, 0, -1);\n }\n array_unshift($sqlBindArray, $_POST[\"id\"]);\n sqlStatement(\"delete from users_facility\n where tablename='users'\n and table_id= ?\n and facility_id not in (\" . $scheduledFacilityString . \")\", $sqlBindArray);", " foreach ($_POST[\"schedule_facility\"] as $tqvar) {\n sqlStatement(\"replace into users_facility set\n facility_id = ?,\n tablename='users',\n table_id = ?\", array($tqvar, $_POST[\"id\"]));\n }\n }", " if ($_POST[\"fname\"]) {\n sqlStatement(\"update users set fname=? where id= ? \", array($_POST[\"fname\"], $_POST[\"id\"]));\n }", " if (isset($_POST['default_warehouse'])) {\n sqlStatement(\"UPDATE users SET default_warehouse = ? WHERE id = ?\", array($_POST['default_warehouse'], $_POST[\"id\"]));\n }", " if (isset($_POST['irnpool'])) {\n sqlStatement(\"UPDATE users SET irnpool = ? WHERE id = ?\", array($_POST['irnpool'], $_POST[\"id\"]));\n }", " if (!empty($_POST['clear_2fa'])) {\n sqlStatement(\"DELETE FROM login_mfa_registrations WHERE user_id = ?\", array($_POST['id']));\n }", " if ($_POST[\"adminPass\"] && $_POST[\"clearPass\"]) {\n $authUtilsUpdatePassword = new AuthUtils();\n $success = $authUtilsUpdatePassword->updatePassword($_SESSION['authUserID'], $_POST['id'], $_POST['adminPass'], $_POST['clearPass']);\n if (!$success) {\n error_log(errorLogEscape($authUtilsUpdatePassword->getErrorMessage()));\n $alertmsg .= $authUtilsUpdatePassword->getErrorMessage();\n }\n }", " $tqvar = (!empty($_POST[\"authorized\"])) ? 1 : 0;\n $actvar = (!empty($_POST[\"active\"])) ? 1 : 0;\n $calvar = (!empty($_POST[\"calendar\"])) ? 1 : 0;\n $portalvar = (!empty($_POST[\"portal_user\"])) ? 1 : 0;", " sqlStatement(\"UPDATE users SET authorized = ?, active = ?, \" .\n \"calendar = ?, portal_user = ?, see_auth = ? WHERE \" .\n \"id = ? \", array($tqvar, $actvar, $calvar, $portalvar, $_POST['see_auth'], $_POST[\"id\"]));\n //Display message when Emergency Login user was activated\n $bg_count = count($_POST['access_group']);\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['pre_active'] == 0) && ($actvar == 1)) {\n $show_message = 1;\n }\n }", " if (($_POST['access_group'])) {\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['user_type']) == \"\" && ($_POST['check_acl'] == 1) && ($_POST['active']) != \"\") {\n $set_active_msg = 1;\n }\n }\n }", " if ($_POST[\"comments\"]) {\n sqlStatement(\"update users set info = ? where id = ? \", array($_POST[\"comments\"], $_POST[\"id\"]));\n }", " $erxrole = isset($_POST['erxrole']) ? $_POST['erxrole'] : '';\n sqlStatement(\"update users set newcrop_user_role = ? where id = ? \", array($erxrole, $_POST[\"id\"]));", " if ($_POST[\"physician_type\"]) {\n sqlStatement(\"update users set physician_type = ? where id = ? \", array($_POST[\"physician_type\"], $_POST[\"id\"]));\n }", " if ($_POST[\"main_menu_role\"]) {\n $mainMenuRole = filter_input(INPUT_POST, 'main_menu_role');\n sqlStatement(\"update `users` set `main_menu_role` = ? where `id` = ? \", array($mainMenuRole, $_POST[\"id\"]));\n }", " if ($_POST[\"patient_menu_role\"]) {\n $patientMenuRole = filter_input(INPUT_POST, 'patient_menu_role');\n sqlStatement(\"update `users` set `patient_menu_role` = ? where `id` = ? \", array($patientMenuRole, $_POST[\"id\"]));\n }", " if ($_POST[\"erxprid\"]) {\n sqlStatement(\"update users set weno_prov_id = ? where id = ? \", array($_POST[\"erxprid\"], $_POST[\"id\"]));\n }", " if (isset($_POST[\"supervisor_id\"])) {\n sqlStatement(\"update users set supervisor_id = ? where id = ? \", array((int)$_POST[\"supervisor_id\"], $_POST[\"id\"]));\n }\n if (isset($_POST[\"google_signin_email\"])) {\n sqlStatement(\"update users set google_signin_email = ? where id = ? \", array($_POST[\"google_signin_email\"], $_POST[\"id\"]));\n }", " // Set the access control group of user\n $user_data = sqlFetchArray(sqlStatement(\"select username from users where id= ?\", array($_POST[\"id\"])));\n AclExtended::setUserAro(\n $_POST['access_group'],\n $user_data[\"username\"],\n (isset($_POST['fname']) ? $_POST['fname'] : ''),\n (isset($_POST['mname']) ? $_POST['mname'] : ''),\n (isset($_POST['lname']) ? $_POST['lname'] : '')\n );", " $userUpdatedEvent = new UserUpdatedEvent($user_data, $_POST);\n $GLOBALS[\"kernel\"]->getEventDispatcher()->dispatch(UserUpdatedEvent::EVENT_HANDLE, $userUpdatedEvent, 10);\n }\n}", "/* To refresh and save variables in mail frame - Arb*/\nif (isset($_POST[\"mode\"])) {\n if ($_POST[\"mode\"] == \"new_user\") {\n if (empty($_POST[\"authorized\"]) || $_POST[\"authorized\"] != \"1\") {\n $_POST[\"authorized\"] = 0;\n }", " $calvar = (!empty($_POST[\"calendar\"])) ? 1 : 0;\n $portalvar = (!empty($_POST[\"portal_user\"])) ? 1 : 0;\n", " $res = sqlStatement(\"select distinct username from users where username != ''\");", " $doit = true;", " while ($row = sqlFetchArray($res)) {\n if ($doit == true && $row['username'] == trim($_POST['rumple'])) {\n $doit = false;\n }", " }", " if ($doit == true) {\n $insertUserSQL =\n \"insert into users set \" .\n \"username = '\" . add_escape_custom(trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))) .\n \"', password = '\" . 'NoLongerUsed' .\n \"', fname = '\" . add_escape_custom(trim((isset($_POST['fname']) ? $_POST['fname'] : ''))) .\n \"', mname = '\" . add_escape_custom(trim((isset($_POST['mname']) ? $_POST['mname'] : ''))) .\n \"', lname = '\" . add_escape_custom(trim((isset($_POST['lname']) ? $_POST['lname'] : ''))) .\n \"', federaltaxid = '\" . add_escape_custom(trim((isset($_POST['federaltaxid']) ? $_POST['federaltaxid'] : ''))) .\n \"', state_license_number = '\" . add_escape_custom(trim((isset($_POST['state_license_number']) ? $_POST['state_license_number'] : ''))) .\n \"', newcrop_user_role = '\" . add_escape_custom(trim((isset($_POST['erxrole']) ? $_POST['erxrole'] : ''))) .\n \"', physician_type = '\" . add_escape_custom(trim((isset($_POST['physician_type']) ? $_POST['physician_type'] : ''))) .\n \"', main_menu_role = '\" . add_escape_custom(trim((isset($_POST['main_menu_role']) ? $_POST['main_menu_role'] : ''))) .\n \"', patient_menu_role = '\" . add_escape_custom(trim((isset($_POST['patient_menu_role']) ? $_POST['patient_menu_role'] : ''))) .\n \"', weno_prov_id = '\" . add_escape_custom(trim((isset($_POST['erxprid']) ? $_POST['erxprid'] : ''))) .\n \"', authorized = '\" . add_escape_custom(trim((isset($_POST['authorized']) ? $_POST['authorized'] : ''))) .\n \"', info = '\" . add_escape_custom(trim((isset($_POST['info']) ? $_POST['info'] : ''))) .\n \"', federaldrugid = '\" . add_escape_custom(trim((isset($_POST['federaldrugid']) ? $_POST['federaldrugid'] : ''))) .\n \"', upin = '\" . add_escape_custom(trim((isset($_POST['upin']) ? $_POST['upin'] : ''))) .\n \"', npi = '\" . add_escape_custom(trim((isset($_POST['npi']) ? $_POST['npi'] : ''))) .\n \"', taxonomy = '\" . add_escape_custom(trim((isset($_POST['taxonomy']) ? $_POST['taxonomy'] : ''))) .\n \"', facility_id = '\" . add_escape_custom(trim((isset($_POST['facility_id']) ? $_POST['facility_id'] : ''))) .\n \"', specialty = '\" . add_escape_custom(trim((isset($_POST['specialty']) ? $_POST['specialty'] : ''))) .\n \"', see_auth = '\" . add_escape_custom(trim((isset($_POST['see_auth']) ? $_POST['see_auth'] : ''))) .\n \"', default_warehouse = '\" . add_escape_custom(trim((isset($_POST['default_warehouse']) ? $_POST['default_warehouse'] : ''))) .\n \"', irnpool = '\" . add_escape_custom(trim((isset($_POST['irnpool']) ? $_POST['irnpool'] : ''))) .\n \"', calendar = '\" . add_escape_custom($calvar) .\n \"', portal_user = '\" . add_escape_custom($portalvar) .\n \"', supervisor_id = '\" . add_escape_custom((isset($_POST['supervisor_id']) ? (int)$_POST['supervisor_id'] : 0)) .\n \"'\";", " $authUtilsNewPassword = new AuthUtils();\n $success = $authUtilsNewPassword->updatePassword(\n $_SESSION['authUserID'],\n 0,\n $_POST['adminPass'],\n $_POST['stiltskin'],\n true,\n $insertUserSQL,\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n );\n if (!empty($authUtilsNewPassword->getErrorMessage())) {\n $alertmsg .= $authUtilsNewPassword->getErrorMessage();\n }\n if ($success) {\n //set the facility name from the selected facility_id\n sqlStatement(\n \"UPDATE users, facility SET users.facility = facility.name WHERE facility.id = ? AND users.username = ?\",\n array(\n trim((isset($_POST['facility_id']) ? $_POST['facility_id'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );", " sqlStatement(\n \"insert into `groups` set name = ?, user = ?\",\n array(\n trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );", " if (trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))) {\n // Set the access control group of user\n AclExtended::setUserAro(\n $_POST['access_group'],\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')),\n trim((isset($_POST['fname']) ? $_POST['fname'] : '')),\n trim((isset($_POST['mname']) ? $_POST['mname'] : '')),\n trim((isset($_POST['lname']) ? $_POST['lname'] : ''))\n );\n }\n }\n } else {\n $alertmsg .= xl('User') . ' ' . trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')) . ' ' . xl('already exists.');\n }", " if ($_POST['access_group']) {\n $bg_count = count($_POST['access_group']);\n for ($i = 0; $i < $bg_count; $i++) {\n if ($_POST['access_group'][$i] == \"Emergency Login\") {\n $set_active_msg = 1;\n }\n }\n }", " $userCreatedEvent = new UserCreatedEvent($_POST);\n $GLOBALS[\"kernel\"]->getEventDispatcher()->dispatch(UserCreatedEvent::EVENT_HANDLE, $userCreatedEvent, 10);\n } elseif ($_POST[\"mode\"] == \"new_group\") {\n $res = sqlStatement(\"select distinct name, user from `groups`\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result[$iter] = $row;\n }", " $doit = 1;\n foreach ($result as $iter) {\n if ($doit == 1 && $iter[\"name\"] == (trim((isset($_POST['groupname']) ? $_POST['groupname'] : ''))) && $iter[\"user\"] == (trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')))) {\n $doit--;\n }\n }", " if ($doit == 1) {\n sqlStatement(\n \"insert into `groups` set name = ?, user = ?\",\n array(\n trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );\n } else {\n $alertmsg .= \"User \" . trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')) .\n \" is already a member of group \" . trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')) . \". \";\n }\n }\n}", "if (isset($_GET[\"mode\"])) {\n /*******************************************************************\n // This is the code to delete a user. Note that the link which invokes\n // this is commented out. Somebody must have figured it was too dangerous.\n //\n if ($_GET[\"mode\"] == \"delete\") {\n $res = sqlStatement(\"select distinct username, id from users where id = '\" .\n $_GET[\"id\"] . \"'\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++)\n $result[$iter] = $row;", " // TBD: Before deleting the user, we should check all tables that\n // reference users to make sure this user is not referenced!", " foreach($result as $iter) {\n sqlStatement(\"delete from `groups` where user = '\" . $iter[\"username\"] . \"'\");\n }\n sqlStatement(\"delete from users where id = '\" . $_GET[\"id\"] . \"'\");\n }\n *******************************************************************/", " if ($_GET[\"mode\"] == \"delete_group\") {\n $res = sqlStatement(\"select distinct user from `groups` where id = ?\", array($_GET[\"id\"]));\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result[$iter] = $row;\n }", " foreach ($result as $iter) {\n $un = $iter[\"user\"];\n }", " $res = sqlStatement(\"select name, user from `groups` where user = ? \" .\n \"and id != ?\", array($un, $_GET[\"id\"]));", " // Remove the user only if they are also in some other group. I.e. every\n // user must be a member of at least one group.\n if (sqlFetchArray($res) != false) {\n sqlStatement(\"delete from `groups` where id = ?\", array($_GET[\"id\"]));\n } else {\n $alertmsg .= \"You must add this user to some other group before \" .\n \"removing them from this group. \";\n }\n }\n}\n// added for form submit's from usergroup_admin_add and user_admin.php\n// sjp 12/29/17\nif (isset($_REQUEST[\"mode\"])) {\n exit(text(trim($alertmsg)));\n}", "$form_inactive = empty($_POST['form_inactive']) ? false : true;", "?>\n<html>\n<head>\n<title><?php echo xlt('User / Groups');?></title>", "<?php Header::setupHeader(['common']); ?>", "<script>", "$(function () {", " tabbify();", " $(\".medium_modal\").on('click', function(e) {\n e.preventDefault();e.stopPropagation();\n dlgopen('', '', 'modal-mlg', 450, '', '', {\n type: 'iframe',\n url: $(this).attr('href')\n });\n });", "});", "function authorized_clicked() {\n var f = document.forms[0];\n f.calendar.disabled = !f.authorized.checked;\n f.calendar.checked = f.authorized.checked;\n}", "</script>", "</head>\n<body class=\"body_top\">", "<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-12\">\n <div class=\"page-title\">\n <h2><?php echo xlt('User / Groups');?></h2>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <div class=\"btn-group\">\n <a href=\"usergroup_admin_add.php\" class=\"medium_modal btn btn-secondary btn-add\"><?php echo xlt('Add User'); ?></a>\n <a href=\"facility_user.php\" class=\"btn btn-secondary btn-show\"><?php echo xlt('View Facility Specific User Information'); ?></a>\n </div>\n <form name='userlist' method='post' style=\"display: inline;\" class=\"form-inline\" class=\"float-right\" action='usergroup_admin.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n <div class=\"checkbox\">\n <label for=\"form_inactive\">\n <input type='checkbox' class=\"form-control\" id=\"form_inactive\" name='form_inactive' value='1' onclick='submit()' <?php echo ($form_inactive) ? 'checked ' : ''; ?>>\n <?php echo xlt('Include inactive users'); ?>\n </label>\n </div>\n </form>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <?php\n if ($set_active_msg == 1) {\n echo \"<div class='alert alert-danger'>\" . xlt('Emergency Login ACL is chosen. The user is still in active state, please de-activate the user and activate the same when required during emergency situations. Visit Administration->Users for activation or de-activation.') . \"</div><br />\";\n }", " if ($show_message == 1) {\n echo \"<div class='alert alert-danger'>\" . xlt('The following Emergency Login User is activated:') . \" \" . \"<b>\" . text($_GET['fname']) . \"</b>\" . \"</div><br />\";\n echo \"<div class='alert alert-danger'>\" . xlt('Emergency Login activation email will be circulated only if following settings in the interface/globals.php file are configured:') . \" \\$GLOBALS['Emergency_Login_email'], \\$GLOBALS['Emergency_Login_email_id']</div>\";\n }", " ?>\n <div class=\"table-responsive\">\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th><?php echo xlt('Username'); ?></th>\n <th><?php echo xlt('Real Name'); ?></th>\n <th><?php echo xlt('Additional Info'); ?></th>\n <th><?php echo xlt('Authorized'); ?></th>\n <th><?php echo xlt('MFA'); ?></th>\n <?php\n $checkPassExp = false;\n if (($GLOBALS['password_expiration_days'] != 0) && (check_integer($GLOBALS['password_expiration_days'])) && (check_integer($GLOBALS['password_grace_time']))) {\n $checkPassExp = true;\n echo '<th>' . xlt('Password Expiration') . '</th>';\n }\n ?>\n </tr>\n <tbody>\n <?php\n $query = \"SELECT * FROM users WHERE username != '' \";\n if (!$form_inactive) {\n $query .= \"AND active = '1' \";\n }", " $query .= \"ORDER BY username\";\n $res = sqlStatement($query);\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result4[$iter] = $row;\n }", " foreach ($result4 as $iter) {\n if ($iter[\"authorized\"]) {\n $iter[\"authorized\"] = xl('yes');\n } else {\n $iter[\"authorized\"] = xl('no');\n }", " $mfa = sqlQuery(\n \"SELECT `method` FROM `login_mfa_registrations` \" .\n \"WHERE `user_id` = ? AND (`method` = 'TOTP' OR `method` = 'U2F')\",\n [$iter['id']]\n );\n if (!empty($mfa['method'])) {\n $isMfa = xl('yes');\n } else {\n $isMfa = xl('no');\n }", " if ($checkPassExp && !empty($iter[\"active\"])) {\n $current_date = date(\"Y-m-d\");\n $userSecure = privQuery(\"SELECT `last_update_password` FROM `users_secure` WHERE `id` = ?\", [$iter['id']]);\n $pwd_expires = date(\"Y-m-d\", strtotime($userSecure['last_update_password'] . \"+\" . $GLOBALS['password_expiration_days'] . \" days\"));\n $grace_time = date(\"Y-m-d\", strtotime($pwd_expires . \"+\" . $GLOBALS['password_grace_time'] . \" days\"));\n }", " print \"<tr>\n <td><b><a href='user_admin.php?id=\" . attr_url($iter[\"id\"]) . \"&csrf_token_form=\" . attr_url(CsrfUtils::collectCsrfToken()) .\n \"' class='medium_modal' onclick='top.restoreSession()'>\" . text($iter[\"username\"]) . \"</a></b>\" . \"&nbsp;</td>\n <td>\" . text($iter[\"fname\"]) . ' ' . text($iter[\"lname\"]) . \"&nbsp;</td>\n <td>\" . text($iter[\"info\"]) . \"&nbsp;</td>\n <td align='left'><span>\" . text($iter[\"authorized\"]) . \"</td>\n <td align='left'><span>\" . text($isMfa) . \"</td>\";\n if ($checkPassExp) {\n echo '<td>';\n if (AuthUtils::useActiveDirectory($iter[\"username\"]) || empty($iter[\"active\"])) {\n // LDAP bypasses expired password mechanism\n echo '<div class=\"alert alert-success\" role=\"alert\">' . xlt('Not Applicable') . '</div>';\n } elseif (strtotime($current_date) > strtotime($grace_time)) {\n echo '<div class=\"alert alert-danger\" role=\"alert\">' . xlt('Expired') . '</div>';\n } elseif (strtotime($current_date) > strtotime($pwd_expires)) {\n echo '<div class=\"alert alert-warning\" role=\"alert\">' . xlt('Grace Period') . '</div>';\n } else {\n echo '<div class=\"alert alert-success\" role=\"alert\">' . text(oeFormatShortDate($pwd_expires)) . '</div>';\n }\n echo '</td>';\n }\n print \"</tr>\\n\";\n }\n ?>\n </tbody>\n </table>\n </div>\n <?php\n if (empty($GLOBALS['disable_non_default_groups'])) {\n $res = sqlStatement(\"select * from `groups` order by name\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result5[$iter] = $row;\n }", " foreach ($result5 as $iter) {\n $grouplist[$iter[\"name\"]] .= text($iter[\"user\"]) .\n \"(<a class='link_submit' href='usergroup_admin.php?mode=delete_group&id=\" .\n attr_url($iter[\"id\"]) . \"&csrf_token_form=\" . attr_url(CsrfUtils::collectCsrfToken()) . \"' onclick='top.restoreSession()'>\" . xlt('Remove') . \"</a>), \";\n }", " foreach ($grouplist as $groupname => $list) {\n print \"<span class='bold'>\" . text($groupname) . \"</span><br />\\n<span>\" .\n substr($list, 0, strlen($list) - 2) . \"</span><br />\\n\";\n }\n }\n ?>\n </div>\n </div>\n</div>\n<script>\n<?php\nif ($alertmsg = trim($alertmsg)) {\n echo \"alert(\" . js_escape($alertmsg) . \");\\n\";\n}\n?>\n</script>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * This script Assign acl 'Emergency login'.\n *\n * @package OpenEMR\n * @link http://www.open-emr.org\n * @author Roberto Vasquez <robertogagliotta@gmail.com>\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @author Daniel Pflieger <daniel@mi-squared.com> <daniel@growlingflea.com>\n * @author Ken Chapple <ken@mi-squared.com>\n * @copyright Copyright (c) 2015 Roberto Vasquez <robertogagliotta@gmail.com>\n * @copyright Copyright (c) 2017-2019 Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2021 Daniel Pflieger <daniel@mi-squared.com> <daniel@growlingflea.com>\n * @copyright Copyright (c) 2021 Ken Chapple <ken@mi-squared.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "$sessionAllowWrite = true;\nrequire_once(\"../globals.php\");\nrequire_once(\"$srcdir/auth.inc\");", "use OpenEMR\\Common\\Acl\\AclExtended;\nuse OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Common\\Auth\\AuthUtils;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Core\\Header;\nuse OpenEMR\\Services\\UserService;\nuse OpenEMR\\Events\\User\\UserUpdatedEvent;\nuse OpenEMR\\Events\\User\\UserCreatedEvent;", "if (!empty($_POST)) {\n if (!CsrfUtils::verifyCsrfToken($_POST[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n}", "if (!empty($_GET)) {\n if (!CsrfUtils::verifyCsrfToken($_GET[\"csrf_token_form\"])) {\n CsrfUtils::csrfNotVerified();\n }\n}", "if (!AclMain::aclCheckCore('admin', 'users')) {\n die(xlt('Access denied'));\n}", "if (!AclMain::aclCheckCore('admin', 'super')) {\n //block non-administrator user from create administrator\n foreach ($_POST['access_group'] as $aro_group) {\n if (AclExtended::isGroupIncludeSuperuser($aro_group)) {\n die(xlt('Saving denied'));\n };\n }\n if ($_POST['mode'] === 'update') {\n //block non-administrator user from update administrator\n $user_service = new UserService();\n $user = $user_service->getUser($_POST['id']);\n $aro_groups = AclExtended::aclGetGroupTitles($user['username']);\n foreach ($aro_groups as $aro_group) {\n if (AclExtended::isGroupIncludeSuperuser($aro_group)) {\n die(xlt('Saving denied'));\n };\n }\n }\n}", "$alertmsg = '';\n$bg_msg = '';\n$set_active_msg = 0;\n$show_message = 0;", "/* Sending a mail to the admin when the breakglass user is activated only if $GLOBALS['Emergency_Login_email'] is set to 1 */\nif (!empty($_POST['access_group']) && is_array($_POST['access_group'])) {\n $bg_count = count($_POST['access_group']);\n $mail_id = explode(\".\", $SMTP_HOST);\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['active'] == 'on') && ($_POST['pre_active'] == 0)) {\n if (($_POST['get_admin_id'] == 1) && ($_POST['admin_id'] != \"\")) {\n $res = sqlStatement(\"select username from users where id= ? \", array($_POST[\"id\"]));\n $row = sqlFetchArray($res);\n $uname = $row['username'];\n $mail = new MyMailer();\n $mail->From = $GLOBALS[\"practice_return_email_path\"];\n $mail->FromName = \"Administrator OpenEMR\";\n $text_body = \"Hello Security Admin,\\n\\n The Emergency Login user \" . $uname .\n \" was activated at \" . date('l jS \\of F Y h:i:s A') . \" \\n\\nThanks,\\nAdmin OpenEMR.\";\n $mail->Body = $text_body;\n $mail->Subject = \"Emergency Login User Activated\";\n $mail->AddAddress($_POST['admin_id']);\n $mail->Send();\n }\n }\n }\n}", "/* To refresh and save variables in mail frame */\nif (isset($_POST[\"privatemode\"]) && $_POST[\"privatemode\"] == \"user_admin\") {\n if ($_POST[\"mode\"] == \"update\") {\n $user_data = sqlFetchArray(sqlStatement(\"select * from users where id= ? \", array($_POST[\"id\"])));", " if (isset($_POST[\"username\"])) {\n sqlStatement(\"update users set username=? where id= ? \", array(trim($_POST[\"username\"]), $_POST[\"id\"]));\n sqlStatement(\"update `groups` set user=? where user= ?\", array(trim($_POST[\"username\"]), $user_data[\"username\"]));\n }", " if ($_POST[\"taxid\"]) {\n sqlStatement(\"update users set federaltaxid=? where id= ? \", array($_POST[\"taxid\"], $_POST[\"id\"]));\n }", " if ($_POST[\"state_license_number\"]) {\n sqlStatement(\"update users set state_license_number=? where id= ? \", array($_POST[\"state_license_number\"], $_POST[\"id\"]));\n }", " if ($_POST[\"drugid\"]) {\n sqlStatement(\"update users set federaldrugid=? where id= ? \", array($_POST[\"drugid\"], $_POST[\"id\"]));\n }", " if ($_POST[\"upin\"]) {\n sqlStatement(\"update users set upin=? where id= ? \", array($_POST[\"upin\"], $_POST[\"id\"]));\n }", " if ($_POST[\"npi\"]) {\n sqlStatement(\"update users set npi=? where id= ? \", array($_POST[\"npi\"], $_POST[\"id\"]));\n }", " if ($_POST[\"taxonomy\"]) {\n sqlStatement(\"update users set taxonomy = ? where id= ? \", array($_POST[\"taxonomy\"], $_POST[\"id\"]));\n }", " if ($_POST[\"lname\"]) {\n sqlStatement(\"update users set lname=? where id= ? \", array($_POST[\"lname\"], $_POST[\"id\"]));\n }", " if ($_POST[\"job\"]) {\n sqlStatement(\"update users set specialty=? where id= ? \", array($_POST[\"job\"], $_POST[\"id\"]));\n }", " if ($_POST[\"mname\"]) {\n sqlStatement(\"update users set mname=? where id= ? \", array($_POST[\"mname\"], $_POST[\"id\"]));\n }", " if ($_POST[\"facility_id\"]) {\n sqlStatement(\"update users set facility_id = ? where id = ? \", array($_POST[\"facility_id\"], $_POST[\"id\"]));\n //(CHEMED) Update facility name when changing the id\n sqlStatement(\"UPDATE users, facility SET users.facility = facility.name WHERE facility.id = ? AND users.id = ?\", array($_POST[\"facility_id\"], $_POST[\"id\"]));\n //END (CHEMED)\n }", " if ($GLOBALS['restrict_user_facility'] && $_POST[\"schedule_facility\"]) {\n $sqlBindArray = [];\n $scheduledFacilityString = \"\";\n foreach ($_POST[\"schedule_facility\"] as $scheduledFacility) {\n $scheduledFacilityString .= \"?,\";\n array_push($sqlBindArray, $scheduledFacility);\n }\n if (!empty($scheduledFacilityString)) {\n $scheduledFacilityString = substr($scheduledFacilityString, 0, -1);\n }\n array_unshift($sqlBindArray, $_POST[\"id\"]);\n sqlStatement(\"delete from users_facility\n where tablename='users'\n and table_id= ?\n and facility_id not in (\" . $scheduledFacilityString . \")\", $sqlBindArray);", " foreach ($_POST[\"schedule_facility\"] as $tqvar) {\n sqlStatement(\"replace into users_facility set\n facility_id = ?,\n tablename='users',\n table_id = ?\", array($tqvar, $_POST[\"id\"]));\n }\n }", " if ($_POST[\"fname\"]) {\n sqlStatement(\"update users set fname=? where id= ? \", array($_POST[\"fname\"], $_POST[\"id\"]));\n }", " if (isset($_POST['default_warehouse'])) {\n sqlStatement(\"UPDATE users SET default_warehouse = ? WHERE id = ?\", array($_POST['default_warehouse'], $_POST[\"id\"]));\n }", " if (isset($_POST['irnpool'])) {\n sqlStatement(\"UPDATE users SET irnpool = ? WHERE id = ?\", array($_POST['irnpool'], $_POST[\"id\"]));\n }", " if (!empty($_POST['clear_2fa'])) {\n sqlStatement(\"DELETE FROM login_mfa_registrations WHERE user_id = ?\", array($_POST['id']));\n }", " if ($_POST[\"adminPass\"] && $_POST[\"clearPass\"]) {\n $authUtilsUpdatePassword = new AuthUtils();\n $success = $authUtilsUpdatePassword->updatePassword($_SESSION['authUserID'], $_POST['id'], $_POST['adminPass'], $_POST['clearPass']);\n if (!$success) {\n error_log(errorLogEscape($authUtilsUpdatePassword->getErrorMessage()));\n $alertmsg .= $authUtilsUpdatePassword->getErrorMessage();\n }\n }", " $tqvar = (!empty($_POST[\"authorized\"])) ? 1 : 0;\n $actvar = (!empty($_POST[\"active\"])) ? 1 : 0;\n $calvar = (!empty($_POST[\"calendar\"])) ? 1 : 0;\n $portalvar = (!empty($_POST[\"portal_user\"])) ? 1 : 0;", " sqlStatement(\"UPDATE users SET authorized = ?, active = ?, \" .\n \"calendar = ?, portal_user = ?, see_auth = ? WHERE \" .\n \"id = ? \", array($tqvar, $actvar, $calvar, $portalvar, $_POST['see_auth'], $_POST[\"id\"]));\n //Display message when Emergency Login user was activated\n $bg_count = count($_POST['access_group']);\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['pre_active'] == 0) && ($actvar == 1)) {\n $show_message = 1;\n }\n }", " if (($_POST['access_group'])) {\n for ($i = 0; $i < $bg_count; $i++) {\n if (($_POST['access_group'][$i] == \"Emergency Login\") && ($_POST['user_type']) == \"\" && ($_POST['check_acl'] == 1) && ($_POST['active']) != \"\") {\n $set_active_msg = 1;\n }\n }\n }", " if ($_POST[\"comments\"]) {\n sqlStatement(\"update users set info = ? where id = ? \", array($_POST[\"comments\"], $_POST[\"id\"]));\n }", " $erxrole = isset($_POST['erxrole']) ? $_POST['erxrole'] : '';\n sqlStatement(\"update users set newcrop_user_role = ? where id = ? \", array($erxrole, $_POST[\"id\"]));", " if ($_POST[\"physician_type\"]) {\n sqlStatement(\"update users set physician_type = ? where id = ? \", array($_POST[\"physician_type\"], $_POST[\"id\"]));\n }", " if ($_POST[\"main_menu_role\"]) {\n $mainMenuRole = filter_input(INPUT_POST, 'main_menu_role');\n sqlStatement(\"update `users` set `main_menu_role` = ? where `id` = ? \", array($mainMenuRole, $_POST[\"id\"]));\n }", " if ($_POST[\"patient_menu_role\"]) {\n $patientMenuRole = filter_input(INPUT_POST, 'patient_menu_role');\n sqlStatement(\"update `users` set `patient_menu_role` = ? where `id` = ? \", array($patientMenuRole, $_POST[\"id\"]));\n }", " if ($_POST[\"erxprid\"]) {\n sqlStatement(\"update users set weno_prov_id = ? where id = ? \", array($_POST[\"erxprid\"], $_POST[\"id\"]));\n }", " if (isset($_POST[\"supervisor_id\"])) {\n sqlStatement(\"update users set supervisor_id = ? where id = ? \", array((int)$_POST[\"supervisor_id\"], $_POST[\"id\"]));\n }\n if (isset($_POST[\"google_signin_email\"])) {\n sqlStatement(\"update users set google_signin_email = ? where id = ? \", array($_POST[\"google_signin_email\"], $_POST[\"id\"]));\n }", " // Set the access control group of user\n $user_data = sqlFetchArray(sqlStatement(\"select username from users where id= ?\", array($_POST[\"id\"])));\n AclExtended::setUserAro(\n $_POST['access_group'],\n $user_data[\"username\"],\n (isset($_POST['fname']) ? $_POST['fname'] : ''),\n (isset($_POST['mname']) ? $_POST['mname'] : ''),\n (isset($_POST['lname']) ? $_POST['lname'] : '')\n );", " $userUpdatedEvent = new UserUpdatedEvent($user_data, $_POST);\n $GLOBALS[\"kernel\"]->getEventDispatcher()->dispatch(UserUpdatedEvent::EVENT_HANDLE, $userUpdatedEvent, 10);\n }\n}", "/* To refresh and save variables in mail frame - Arb*/\nif (isset($_POST[\"mode\"])) {\n if ($_POST[\"mode\"] == \"new_user\") {\n if (empty($_POST[\"authorized\"]) || $_POST[\"authorized\"] != \"1\") {\n $_POST[\"authorized\"] = 0;\n }", " $calvar = (!empty($_POST[\"calendar\"])) ? 1 : 0;\n $portalvar = (!empty($_POST[\"portal_user\"])) ? 1 : 0;\n", " $res = sqlQuery(\"select username from users where username = ?\", [trim($_POST['rumple'])]);", " $doit = true;", " if (!empty($res['username'])) {\n $doit = false;", " }", " if ($doit == true) {\n $insertUserSQL =\n \"insert into users set \" .\n \"username = '\" . add_escape_custom(trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))) .\n \"', password = '\" . 'NoLongerUsed' .\n \"', fname = '\" . add_escape_custom(trim((isset($_POST['fname']) ? $_POST['fname'] : ''))) .\n \"', mname = '\" . add_escape_custom(trim((isset($_POST['mname']) ? $_POST['mname'] : ''))) .\n \"', lname = '\" . add_escape_custom(trim((isset($_POST['lname']) ? $_POST['lname'] : ''))) .\n \"', federaltaxid = '\" . add_escape_custom(trim((isset($_POST['federaltaxid']) ? $_POST['federaltaxid'] : ''))) .\n \"', state_license_number = '\" . add_escape_custom(trim((isset($_POST['state_license_number']) ? $_POST['state_license_number'] : ''))) .\n \"', newcrop_user_role = '\" . add_escape_custom(trim((isset($_POST['erxrole']) ? $_POST['erxrole'] : ''))) .\n \"', physician_type = '\" . add_escape_custom(trim((isset($_POST['physician_type']) ? $_POST['physician_type'] : ''))) .\n \"', main_menu_role = '\" . add_escape_custom(trim((isset($_POST['main_menu_role']) ? $_POST['main_menu_role'] : ''))) .\n \"', patient_menu_role = '\" . add_escape_custom(trim((isset($_POST['patient_menu_role']) ? $_POST['patient_menu_role'] : ''))) .\n \"', weno_prov_id = '\" . add_escape_custom(trim((isset($_POST['erxprid']) ? $_POST['erxprid'] : ''))) .\n \"', authorized = '\" . add_escape_custom(trim((isset($_POST['authorized']) ? $_POST['authorized'] : ''))) .\n \"', info = '\" . add_escape_custom(trim((isset($_POST['info']) ? $_POST['info'] : ''))) .\n \"', federaldrugid = '\" . add_escape_custom(trim((isset($_POST['federaldrugid']) ? $_POST['federaldrugid'] : ''))) .\n \"', upin = '\" . add_escape_custom(trim((isset($_POST['upin']) ? $_POST['upin'] : ''))) .\n \"', npi = '\" . add_escape_custom(trim((isset($_POST['npi']) ? $_POST['npi'] : ''))) .\n \"', taxonomy = '\" . add_escape_custom(trim((isset($_POST['taxonomy']) ? $_POST['taxonomy'] : ''))) .\n \"', facility_id = '\" . add_escape_custom(trim((isset($_POST['facility_id']) ? $_POST['facility_id'] : ''))) .\n \"', specialty = '\" . add_escape_custom(trim((isset($_POST['specialty']) ? $_POST['specialty'] : ''))) .\n \"', see_auth = '\" . add_escape_custom(trim((isset($_POST['see_auth']) ? $_POST['see_auth'] : ''))) .\n \"', default_warehouse = '\" . add_escape_custom(trim((isset($_POST['default_warehouse']) ? $_POST['default_warehouse'] : ''))) .\n \"', irnpool = '\" . add_escape_custom(trim((isset($_POST['irnpool']) ? $_POST['irnpool'] : ''))) .\n \"', calendar = '\" . add_escape_custom($calvar) .\n \"', portal_user = '\" . add_escape_custom($portalvar) .\n \"', supervisor_id = '\" . add_escape_custom((isset($_POST['supervisor_id']) ? (int)$_POST['supervisor_id'] : 0)) .\n \"'\";", " $authUtilsNewPassword = new AuthUtils();\n $success = $authUtilsNewPassword->updatePassword(\n $_SESSION['authUserID'],\n 0,\n $_POST['adminPass'],\n $_POST['stiltskin'],\n true,\n $insertUserSQL,\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n );\n if (!empty($authUtilsNewPassword->getErrorMessage())) {\n $alertmsg .= $authUtilsNewPassword->getErrorMessage();\n }\n if ($success) {\n //set the facility name from the selected facility_id\n sqlStatement(\n \"UPDATE users, facility SET users.facility = facility.name WHERE facility.id = ? AND users.username = ?\",\n array(\n trim((isset($_POST['facility_id']) ? $_POST['facility_id'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );", " sqlStatement(\n \"insert into `groups` set name = ?, user = ?\",\n array(\n trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );", " if (trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))) {\n // Set the access control group of user\n AclExtended::setUserAro(\n $_POST['access_group'],\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')),\n trim((isset($_POST['fname']) ? $_POST['fname'] : '')),\n trim((isset($_POST['mname']) ? $_POST['mname'] : '')),\n trim((isset($_POST['lname']) ? $_POST['lname'] : ''))\n );\n }\n }\n } else {\n $alertmsg .= xl('User') . ' ' . trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')) . ' ' . xl('already exists.');\n }", " if ($_POST['access_group']) {\n $bg_count = count($_POST['access_group']);\n for ($i = 0; $i < $bg_count; $i++) {\n if ($_POST['access_group'][$i] == \"Emergency Login\") {\n $set_active_msg = 1;\n }\n }\n }", " $userCreatedEvent = new UserCreatedEvent($_POST);\n $GLOBALS[\"kernel\"]->getEventDispatcher()->dispatch(UserCreatedEvent::EVENT_HANDLE, $userCreatedEvent, 10);\n } elseif ($_POST[\"mode\"] == \"new_group\") {\n $res = sqlStatement(\"select distinct name, user from `groups`\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result[$iter] = $row;\n }", " $doit = 1;\n foreach ($result as $iter) {\n if ($doit == 1 && $iter[\"name\"] == (trim((isset($_POST['groupname']) ? $_POST['groupname'] : ''))) && $iter[\"user\"] == (trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')))) {\n $doit--;\n }\n }", " if ($doit == 1) {\n sqlStatement(\n \"insert into `groups` set name = ?, user = ?\",\n array(\n trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')),\n trim((isset($_POST['rumple']) ? $_POST['rumple'] : ''))\n )\n );\n } else {\n $alertmsg .= \"User \" . trim((isset($_POST['rumple']) ? $_POST['rumple'] : '')) .\n \" is already a member of group \" . trim((isset($_POST['groupname']) ? $_POST['groupname'] : '')) . \". \";\n }\n }\n}", "if (isset($_GET[\"mode\"])) {\n /*******************************************************************\n // This is the code to delete a user. Note that the link which invokes\n // this is commented out. Somebody must have figured it was too dangerous.\n //\n if ($_GET[\"mode\"] == \"delete\") {\n $res = sqlStatement(\"select distinct username, id from users where id = '\" .\n $_GET[\"id\"] . \"'\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++)\n $result[$iter] = $row;", " // TBD: Before deleting the user, we should check all tables that\n // reference users to make sure this user is not referenced!", " foreach($result as $iter) {\n sqlStatement(\"delete from `groups` where user = '\" . $iter[\"username\"] . \"'\");\n }\n sqlStatement(\"delete from users where id = '\" . $_GET[\"id\"] . \"'\");\n }\n *******************************************************************/", " if ($_GET[\"mode\"] == \"delete_group\") {\n $res = sqlStatement(\"select distinct user from `groups` where id = ?\", array($_GET[\"id\"]));\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result[$iter] = $row;\n }", " foreach ($result as $iter) {\n $un = $iter[\"user\"];\n }", " $res = sqlStatement(\"select name, user from `groups` where user = ? \" .\n \"and id != ?\", array($un, $_GET[\"id\"]));", " // Remove the user only if they are also in some other group. I.e. every\n // user must be a member of at least one group.\n if (sqlFetchArray($res) != false) {\n sqlStatement(\"delete from `groups` where id = ?\", array($_GET[\"id\"]));\n } else {\n $alertmsg .= \"You must add this user to some other group before \" .\n \"removing them from this group. \";\n }\n }\n}\n// added for form submit's from usergroup_admin_add and user_admin.php\n// sjp 12/29/17\nif (isset($_REQUEST[\"mode\"])) {\n exit(text(trim($alertmsg)));\n}", "$form_inactive = empty($_POST['form_inactive']) ? false : true;", "?>\n<html>\n<head>\n<title><?php echo xlt('User / Groups');?></title>", "<?php Header::setupHeader(['common']); ?>", "<script>", "$(function () {", " tabbify();", " $(\".medium_modal\").on('click', function(e) {\n e.preventDefault();e.stopPropagation();\n dlgopen('', '', 'modal-mlg', 450, '', '', {\n type: 'iframe',\n url: $(this).attr('href')\n });\n });", "});", "function authorized_clicked() {\n var f = document.forms[0];\n f.calendar.disabled = !f.authorized.checked;\n f.calendar.checked = f.authorized.checked;\n}", "</script>", "</head>\n<body class=\"body_top\">", "<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-12\">\n <div class=\"page-title\">\n <h2><?php echo xlt('User / Groups');?></h2>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <div class=\"btn-group\">\n <a href=\"usergroup_admin_add.php\" class=\"medium_modal btn btn-secondary btn-add\"><?php echo xlt('Add User'); ?></a>\n <a href=\"facility_user.php\" class=\"btn btn-secondary btn-show\"><?php echo xlt('View Facility Specific User Information'); ?></a>\n </div>\n <form name='userlist' method='post' style=\"display: inline;\" class=\"form-inline\" class=\"float-right\" action='usergroup_admin.php' onsubmit='return top.restoreSession()'>\n <input type=\"hidden\" name=\"csrf_token_form\" value=\"<?php echo attr(CsrfUtils::collectCsrfToken()); ?>\" />\n <div class=\"checkbox\">\n <label for=\"form_inactive\">\n <input type='checkbox' class=\"form-control\" id=\"form_inactive\" name='form_inactive' value='1' onclick='submit()' <?php echo ($form_inactive) ? 'checked ' : ''; ?>>\n <?php echo xlt('Include inactive users'); ?>\n </label>\n </div>\n </form>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-12\">\n <?php\n if ($set_active_msg == 1) {\n echo \"<div class='alert alert-danger'>\" . xlt('Emergency Login ACL is chosen. The user is still in active state, please de-activate the user and activate the same when required during emergency situations. Visit Administration->Users for activation or de-activation.') . \"</div><br />\";\n }", " if ($show_message == 1) {\n echo \"<div class='alert alert-danger'>\" . xlt('The following Emergency Login User is activated:') . \" \" . \"<b>\" . text($_GET['fname']) . \"</b>\" . \"</div><br />\";\n echo \"<div class='alert alert-danger'>\" . xlt('Emergency Login activation email will be circulated only if following settings in the interface/globals.php file are configured:') . \" \\$GLOBALS['Emergency_Login_email'], \\$GLOBALS['Emergency_Login_email_id']</div>\";\n }", " ?>\n <div class=\"table-responsive\">\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th><?php echo xlt('Username'); ?></th>\n <th><?php echo xlt('Real Name'); ?></th>\n <th><?php echo xlt('Additional Info'); ?></th>\n <th><?php echo xlt('Authorized'); ?></th>\n <th><?php echo xlt('MFA'); ?></th>\n <?php\n $checkPassExp = false;\n if (($GLOBALS['password_expiration_days'] != 0) && (check_integer($GLOBALS['password_expiration_days'])) && (check_integer($GLOBALS['password_grace_time']))) {\n $checkPassExp = true;\n echo '<th>' . xlt('Password Expiration') . '</th>';\n }\n ?>\n </tr>\n <tbody>\n <?php\n $query = \"SELECT * FROM users WHERE username != '' \";\n if (!$form_inactive) {\n $query .= \"AND active = '1' \";\n }", " $query .= \"ORDER BY username\";\n $res = sqlStatement($query);\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result4[$iter] = $row;\n }", " foreach ($result4 as $iter) {\n if ($iter[\"authorized\"]) {\n $iter[\"authorized\"] = xl('yes');\n } else {\n $iter[\"authorized\"] = xl('no');\n }", " $mfa = sqlQuery(\n \"SELECT `method` FROM `login_mfa_registrations` \" .\n \"WHERE `user_id` = ? AND (`method` = 'TOTP' OR `method` = 'U2F')\",\n [$iter['id']]\n );\n if (!empty($mfa['method'])) {\n $isMfa = xl('yes');\n } else {\n $isMfa = xl('no');\n }", " if ($checkPassExp && !empty($iter[\"active\"])) {\n $current_date = date(\"Y-m-d\");\n $userSecure = privQuery(\"SELECT `last_update_password` FROM `users_secure` WHERE `id` = ?\", [$iter['id']]);\n $pwd_expires = date(\"Y-m-d\", strtotime($userSecure['last_update_password'] . \"+\" . $GLOBALS['password_expiration_days'] . \" days\"));\n $grace_time = date(\"Y-m-d\", strtotime($pwd_expires . \"+\" . $GLOBALS['password_grace_time'] . \" days\"));\n }", " print \"<tr>\n <td><b><a href='user_admin.php?id=\" . attr_url($iter[\"id\"]) . \"&csrf_token_form=\" . attr_url(CsrfUtils::collectCsrfToken()) .\n \"' class='medium_modal' onclick='top.restoreSession()'>\" . text($iter[\"username\"]) . \"</a></b>\" . \"&nbsp;</td>\n <td>\" . text($iter[\"fname\"]) . ' ' . text($iter[\"lname\"]) . \"&nbsp;</td>\n <td>\" . text($iter[\"info\"]) . \"&nbsp;</td>\n <td align='left'><span>\" . text($iter[\"authorized\"]) . \"</td>\n <td align='left'><span>\" . text($isMfa) . \"</td>\";\n if ($checkPassExp) {\n echo '<td>';\n if (AuthUtils::useActiveDirectory($iter[\"username\"]) || empty($iter[\"active\"])) {\n // LDAP bypasses expired password mechanism\n echo '<div class=\"alert alert-success\" role=\"alert\">' . xlt('Not Applicable') . '</div>';\n } elseif (strtotime($current_date) > strtotime($grace_time)) {\n echo '<div class=\"alert alert-danger\" role=\"alert\">' . xlt('Expired') . '</div>';\n } elseif (strtotime($current_date) > strtotime($pwd_expires)) {\n echo '<div class=\"alert alert-warning\" role=\"alert\">' . xlt('Grace Period') . '</div>';\n } else {\n echo '<div class=\"alert alert-success\" role=\"alert\">' . text(oeFormatShortDate($pwd_expires)) . '</div>';\n }\n echo '</td>';\n }\n print \"</tr>\\n\";\n }\n ?>\n </tbody>\n </table>\n </div>\n <?php\n if (empty($GLOBALS['disable_non_default_groups'])) {\n $res = sqlStatement(\"select * from `groups` order by name\");\n for ($iter = 0; $row = sqlFetchArray($res); $iter++) {\n $result5[$iter] = $row;\n }", " foreach ($result5 as $iter) {\n $grouplist[$iter[\"name\"]] .= text($iter[\"user\"]) .\n \"(<a class='link_submit' href='usergroup_admin.php?mode=delete_group&id=\" .\n attr_url($iter[\"id\"]) . \"&csrf_token_form=\" . attr_url(CsrfUtils::collectCsrfToken()) . \"' onclick='top.restoreSession()'>\" . xlt('Remove') . \"</a>), \";\n }", " foreach ($grouplist as $groupname => $list) {\n print \"<span class='bold'>\" . text($groupname) . \"</span><br />\\n<span>\" .\n substr($list, 0, strlen($list) - 2) . \"</span><br />\\n\";\n }\n }\n ?>\n </div>\n </div>\n</div>\n<script>\n<?php\nif ($alertmsg = trim($alertmsg)) {\n echo \"alert(\" . js_escape($alertmsg) . \");\\n\";\n}\n?>\n</script>\n</body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [56, 333, 169, 174, 105, 286], "buggy_code_start_loc": [55, 332, 139, 112, 104, 280], "filenames": ["interface/orders/patient_match_dialog.php", "interface/patient_file/report/patient_report.php", "interface/usergroup/mfa_registrations.php", "interface/usergroup/mfa_totp.php", "interface/usergroup/mfa_u2f.php", "interface/usergroup/usergroup_admin.php"], "fixing_code_end_loc": [56, 333, 169, 174, 105, 284], "fixing_code_start_loc": [55, 332, 139, 112, 104, 280], "message": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "22010AB0-B63C-4F53-8C59-A2288B9B8874", "versionEndExcluding": null, "versionEndIncluding": "6.0.0", "versionStartExcluding": null, "versionStartIncluding": "2.7.3", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In OpenEMR, versions 2.7.3-rc1 to 6.0.0 are vulnerable to Stored Cross-Site-Scripting (XSS) due to user input not being validated properly in the `Allergies` section. An attacker could lure an admin to enter a malicious payload and by that initiate the exploit."}, {"lang": "es", "value": "En OpenEMR, las versiones 2.7.3-rc1 a 6.0.0, son vulnerables a un ataque de tipo Cross-Site-Scripting (XSS) Almacenado debido a que la entrada del usuario no es validada apropiadamente en la secci\u00f3n \"Allergies\".&#xa0;Un atacante podr\u00eda convencer a un administrador para que ingrese una carga \u00fatil maliciosa y as\u00ed iniciar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-25921", "lastModified": "2021-03-24T18:24:39.170", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-03-22T20:15:17.943", "references": [{"source": "vulnerabilitylab@mend.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, {"source": "vulnerabilitylab@mend.io", "tags": ["Third Party Advisory"], "url": "https://www.whitesourcesoftware.com/vulnerability-database/CVE-2021-25921"}], "sourceIdentifier": "vulnerabilitylab@mend.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/0fadc3e592d84bc9dfe9e0403f8bd6e3c7d8427f"}, "type": "CWE-79"}
112
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/perl", "package Catalyst::Plugin::Session;", "use Moose;\nwith 'MooseX::Emulate::Class::Accessor::Fast';\nuse MRO::Compat;\nuse Catalyst::Exception ();\nuse Digest ();\nuse overload ();\nuse Object::Signature ();", "", "use Carp;\nuse List::Util qw/ max /;", "use namespace::clean -except => 'meta';", "our $VERSION = '0.40';\n$VERSION = eval $VERSION;", "my @session_data_accessors; # used in delete_session", "__PACKAGE__->mk_accessors(\n \"_session_delete_reason\",\n @session_data_accessors = qw/\n _sessionid\n _session\n _session_expires\n _extended_session_expires\n _session_data_sig\n _flash\n _flash_keep_keys\n _flash_key_hashes\n _tried_loading_session_id\n _tried_loading_session_data\n _tried_loading_session_expires\n _tried_loading_flash_data\n _needs_early_session_finalization\n /\n);", "sub _session_plugin_config {\n my $c = shift;\n # FIXME - Start warning once all the state/store modules have also been updated.\n #$c->log->warn(\"Deprecated 'session' config key used, please use the key 'Plugin::Session' instead\")\n # if exists $c->config->{session}\n #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};\n $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};\n}", "sub setup {\n my $c = shift;", " $c->maybe::next::method(@_);", " $c->check_session_plugin_requirements;\n $c->setup_session;", " return $c;\n}", "sub check_session_plugin_requirements {\n my $c = shift;", " unless ( $c->isa(\"Catalyst::Plugin::Session::State\")\n && $c->isa(\"Catalyst::Plugin::Session::Store\") )\n {\n my $err =\n ( \"The Session plugin requires both Session::State \"\n . \"and Session::Store plugins to be used as well.\" );", " $c->log->fatal($err);\n Catalyst::Exception->throw($err);\n }\n}", "sub setup_session {\n my $c = shift;", " my $cfg = $c->_session_plugin_config;", " %$cfg = (\n expires => 7200,\n verify_address => 0,\n verify_user_agent => 0,\n expiry_threshold => 0,\n %$cfg,\n );", " $c->maybe::next::method();\n}", "sub prepare_action {\n my $c = shift;", " $c->maybe::next::method(@_);", " if ( $c->_session_plugin_config->{flash_to_stash}\n and $c->sessionid\n and my $flash_data = $c->flash )\n {\n @{ $c->stash }{ keys %$flash_data } = values %$flash_data;\n }\n}", "sub finalize_headers {\n my $c = shift;", " # fix cookie before we send headers\n $c->_save_session_expires;", " # Force extension of session_expires before finalizing headers, so a pos\n # up to date. First call to session_expires will extend the expiry, subs\n # just return the previously extended value.\n $c->session_expires;\n $c->finalize_session if $c->_needs_early_session_finalization;", " return $c->maybe::next::method(@_);\n}", "sub finalize_body {\n my $c = shift;", " # We have to finalize our session *before* $c->engine->finalize_xxx is called,\n # because we do not want to send the HTTP response before the session is stored/committed to\n # the session database (or whatever Session::Store you use).\n $c->finalize_session unless $c->_needs_early_session_finalization;\n $c->_clear_session_instance_data;", " return $c->maybe::next::method(@_);\n}", "sub finalize_session {\n my $c = shift;", " $c->maybe::next::method(@_);", " $c->_save_session_id;\n $c->_save_session;\n $c->_save_flash;", "}", "sub _session_updated {\n my $c = shift;", " if ( my $session_data = $c->_session ) {", " no warnings 'uninitialized';\n if ( Object::Signature::signature($session_data) ne\n $c->_session_data_sig )\n {\n return $session_data;\n } else {\n return;\n }", " } else {", " return;", " }\n}", "sub _save_session_id {\n my $c = shift;", " # we already called set when allocating\n # no need to tell the state plugins anything new\n}", "sub _save_session_expires {\n my $c = shift;", " if ( defined($c->_session_expires) ) {", " if (my $sid = $c->sessionid) {", " my $current = $c->_get_stored_session_expires;\n my $extended = $c->session_expires;\n if ($extended > $current) {\n $c->store_session_data( \"expires:$sid\" => $extended );\n }", " }\n }\n}", "sub _save_session {\n my $c = shift;", " if ( my $session_data = $c->_session_updated ) {", " $session_data->{__updated} = time();\n my $sid = $c->sessionid;\n $c->store_session_data( \"session:$sid\" => $session_data );\n }\n}", "sub _save_flash {\n my $c = shift;", " if ( my $flash_data = $c->_flash ) {", " my $hashes = $c->_flash_key_hashes || {};\n my $keep = $c->_flash_keep_keys || {};\n foreach my $key ( keys %$hashes ) {\n if ( !exists $keep->{$key} and Object::Signature::signature( \\$flash_data->{$key} ) eq $hashes->{$key} ) {\n delete $flash_data->{$key};\n }\n }", " my $sid = $c->sessionid;", " my $session_data = $c->_session;\n if (%$flash_data) {\n $session_data->{__flash} = $flash_data;\n }\n else {\n delete $session_data->{__flash};\n }\n $c->_session($session_data);\n $c->_save_session;\n }\n}", "sub _load_session_expires {\n my $c = shift;\n return $c->_session_expires if $c->_tried_loading_session_expires;\n $c->_tried_loading_session_expires(1);", " if ( my $sid = $c->sessionid ) {\n my $expires = $c->_get_stored_session_expires;", " if ( $expires >= time() ) {\n $c->_session_expires( $expires );\n return $expires;\n } else {\n $c->delete_session( \"session expired\" );\n return 0;\n }\n }", " return;\n}", "sub _load_session {\n my $c = shift;\n return $c->_session if $c->_tried_loading_session_data;\n $c->_tried_loading_session_data(1);", " if ( my $sid = $c->sessionid ) {\n if ( $c->_load_session_expires ) { # > 0", " my $session_data = $c->get_session_data(\"session:$sid\") || return;\n $c->_session($session_data);", " no warnings 'uninitialized'; # ne __address\n if ( $c->_session_plugin_config->{verify_address}\n && exists $session_data->{__address}\n && $session_data->{__address} ne $c->request->address )\n {\n $c->log->warn(\n \"Deleting session $sid due to address mismatch (\"\n . $session_data->{__address} . \" != \"\n . $c->request->address . \")\"\n );\n $c->delete_session(\"address mismatch\");\n return;\n }\n if ( $c->_session_plugin_config->{verify_user_agent}\n && $session_data->{__user_agent} ne $c->request->user_agent )\n {\n $c->log->warn(\n \"Deleting session $sid due to user agent mismatch (\"\n . $session_data->{__user_agent} . \" != \"\n . $c->request->user_agent . \")\"\n );\n $c->delete_session(\"user agent mismatch\");\n return;\n }", " $c->log->debug(qq/Restored session \"$sid\"/) if $c->debug;\n $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;\n $c->_expire_session_keys;", " return $session_data;\n }\n }", " return;\n}", "sub _load_flash {\n my $c = shift;\n return $c->_flash if $c->_tried_loading_flash_data;\n $c->_tried_loading_flash_data(1);", " if ( my $sid = $c->sessionid ) {", " my $session_data = $c->session;\n $c->_flash($session_data->{__flash});", " if ( my $flash_data = $c->_flash )\n {\n $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \\$flash_data->{$_} ) } keys %$flash_data });", " return $flash_data;\n }\n }", " return;\n}", "sub _expire_session_keys {\n my ( $c, $data ) = @_;", " my $now = time;", " my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};\n foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {\n delete $c->_session->{$key};\n delete $expire_times->{$key};\n }\n}", "sub _clear_session_instance_data {\n my $c = shift;\n $c->$_(undef) for @session_data_accessors;\n $c->maybe::next::method(@_); # allow other plugins to hook in on this\n}", "sub change_session_id {\n my $c = shift;", " my $sessiondata = $c->session;\n my $oldsid = $c->sessionid;\n my $newsid = $c->create_session_id;", " if ($oldsid) {\n $c->log->debug(qq/change_sessid: deleting session data from \"$oldsid\"/) if $c->debug;\n $c->delete_session_data(\"${_}:${oldsid}\") for qw/session expires flash/;\n }", " $c->log->debug(qq/change_sessid: storing session data to \"$newsid\"/) if $c->debug;\n $c->store_session_data( \"session:$newsid\" => $sessiondata );", " return $newsid;\n}", "sub delete_session {\n my ( $c, $msg ) = @_;", " $c->log->debug(\"Deleting session\" . ( defined($msg) ? \"($msg)\" : '(no reason given)') ) if $c->debug;", " # delete the session data\n if ( my $sid = $c->sessionid ) {\n $c->delete_session_data(\"${_}:${sid}\") for qw/session expires flash/;\n $c->delete_session_id($sid);\n }", " # reset the values in the context object\n # see the BEGIN block\n $c->_clear_session_instance_data;", " $c->_session_delete_reason($msg);\n}", "sub session_delete_reason {\n my $c = shift;", " $c->session_is_valid; # check that it was loaded", " $c->_session_delete_reason(@_);\n}", "sub session_expires {\n my $c = shift;", " if ( defined( my $expires = $c->_extended_session_expires ) ) {\n return $expires;\n } elsif ( defined( $expires = $c->_load_session_expires ) ) {\n return $c->extend_session_expires( $expires );\n } else {\n return 0;\n }\n}", "sub extend_session_expires {\n my ( $c, $expires ) = @_;", " my $threshold = $c->_session_plugin_config->{expiry_threshold} || 0;", " if ( my $sid = $c->sessionid ) {\n my $expires = $c->_get_stored_session_expires;\n my $cutoff = $expires - $threshold;", " if (!$threshold || $cutoff <= time || $c->_session_updated) {", " $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires() );\n $c->extend_session_id( $sid, $updated );", " return $updated;", " } else {", " return $expires;", " }", " } else {", " return;", " }", "}", "sub change_session_expires {\n my ( $c, $expires ) = @_;", " $expires ||= 0;\n my $sid = $c->sessionid;\n my $time_exp = time() + $expires;\n $c->store_session_data( \"expires:$sid\" => $time_exp );\n}", "sub _get_stored_session_expires {\n my ($c) = @_;", " if ( my $sid = $c->sessionid ) {\n return $c->get_session_data(\"expires:$sid\") || 0;\n } else {\n return 0;\n }\n}", "sub initial_session_expires {\n my $c = shift;\n return ( time() + $c->_session_plugin_config->{expires} );\n}", "sub calculate_initial_session_expires {\n my ($c) = @_;\n return max( $c->initial_session_expires, $c->_get_stored_session_expires );\n}", "sub calculate_extended_session_expires {\n my ( $c, $prev ) = @_;\n return ( time() + $prev );\n}", "sub reset_session_expires {\n my ( $c, $sid ) = @_;", " my $exp = $c->calculate_initial_session_expires;\n $c->_session_expires( $exp );\n #\n # since we're setting _session_expires directly, make load_session_expires\n # actually use that value.\n #\n $c->_tried_loading_session_expires(1);\n $c->_extended_session_expires( $exp );\n $exp;\n}", "sub sessionid {\n my $c = shift;", " return $c->_sessionid || $c->_load_sessionid;\n}", "sub _load_sessionid {\n my $c = shift;\n return if $c->_tried_loading_session_id;\n $c->_tried_loading_session_id(1);", " if ( defined( my $sid = $c->get_session_id ) ) {\n if ( $c->validate_session_id($sid) ) {\n # temporarily set the inner key, so that validation will work\n $c->_sessionid($sid);\n return $sid;\n } else {", "", " my $err = \"Tried to set invalid session ID '$sid'\";\n $c->log->error($err);\n Catalyst::Exception->throw($err);\n }\n }", " return;\n}", "sub session_is_valid {\n my $c = shift;", " # force a check for expiry, but also __address, etc\n if ( $c->_load_session ) {\n return 1;\n } else {\n return;\n }\n}", "sub validate_session_id {\n my ( $c, $sid ) = @_;", " $sid and $sid =~ /^[a-f\\d]+$/i;\n}", "sub session {\n my $c = shift;", " my $session = $c->_session || $c->_load_session || do {\n $c->create_session_id_if_needed;\n $c->initialize_session_data;\n };", " if (@_) {\n my $new_values = @_ > 1 ? { @_ } : $_[0];\n croak('session takes a hash or hashref') unless ref $new_values;", " for my $key (keys %$new_values) {\n $session->{$key} = $new_values->{$key};\n }\n }", " $session;\n}", "sub keep_flash {\n my ( $c, @keys ) = @_;\n my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});\n (@{$href}{@keys}) = ((undef) x @keys);\n}", "sub _flash_data {\n my $c = shift;\n $c->_flash || $c->_load_flash || do {\n $c->create_session_id_if_needed;\n $c->_flash( {} );\n };\n}", "sub _set_flash {\n my $c = shift;\n if (@_) {\n my $items = @_ > 1 ? {@_} : $_[0];\n croak('flash takes a hash or hashref') unless ref $items;\n @{ $c->_flash }{ keys %$items } = values %$items;\n }\n}", "sub flash {\n my $c = shift;\n $c->_flash_data;\n $c->_set_flash(@_);\n return $c->_flash;\n}", "sub clear_flash {\n my $c = shift;", " #$c->delete_session_data(\"flash:\" . $c->sessionid); # should this be in here? or delayed till finalization?\n $c->_flash_key_hashes({});\n $c->_flash_keep_keys({});\n $c->_flash({});\n}", "sub session_expire_key {\n my ( $c, %keys ) = @_;", " my $now = time;\n @{ $c->session->{__expire_keys} }{ keys %keys } =\n map { $now + $_ } values %keys;\n}", "sub initialize_session_data {\n my $c = shift;", " my $now = time;", " return $c->_session(\n {\n __created => $now,\n __updated => $now,", " (\n $c->_session_plugin_config->{verify_address}\n ? ( __address => $c->request->address||'' )\n : ()\n ),\n (\n $c->_session_plugin_config->{verify_user_agent}\n ? ( __user_agent => $c->request->user_agent||'' )\n : ()\n ),\n }\n );\n}", "sub generate_session_id {\n my $c = shift;", " my $digest = $c->_find_digest();\n $digest->add( $c->session_hash_seed() );\n return $digest->hexdigest;\n}", "sub create_session_id_if_needed {\n my $c = shift;\n $c->create_session_id unless $c->sessionid;\n}", "sub create_session_id {\n my $c = shift;", " my $sid = $c->generate_session_id;", " $c->log->debug(qq/Created session \"$sid\"/) if $c->debug;", " $c->_sessionid($sid);\n $c->reset_session_expires;\n $c->set_session_id($sid);", " return $sid;\n}", "my $counter;", "sub session_hash_seed {\n my $c = shift;", " return join( \"\", ++$counter, time, rand, $$, {}, overload::StrVal($c), );\n}", "my $usable;", "sub _find_digest () {\n unless ($usable) {\n foreach my $alg (qw/SHA-1 SHA-256 MD5/) {\n if ( eval { Digest->new($alg) } ) {\n $usable = $alg;\n last;\n }\n }\n Catalyst::Exception->throw(\n \"Could not find a suitable Digest module. Please install \"\n . \"Digest::SHA1, Digest::SHA, or Digest::MD5\" )\n unless $usable;\n }", " return Digest->new($usable);\n}", "sub dump_these {\n my $c = shift;", " (\n $c->maybe::next::method(),", " $c->_sessionid\n ? ( [ \"Session ID\" => $c->sessionid ], [ Session => $c->session ], )\n : ()\n );\n}", "\nsub get_session_id { shift->maybe::next::method(@_) }\nsub set_session_id { shift->maybe::next::method(@_) }\nsub delete_session_id { shift->maybe::next::method(@_) }\nsub extend_session_id { shift->maybe::next::method(@_) }", "__PACKAGE__;", "__END__", "=pod", "=head1 NAME", "Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.", "=head1 SYNOPSIS", " # To get sessions to \"just work\", all you need to do is use these plugins:", " use Catalyst qw/\n Session\n Session::Store::FastMmap\n Session::State::Cookie\n /;", " # you can replace Store::FastMmap with Store::File - both have sensible\n # default configurations (see their docs for details)", " # more complicated backends are available for other scenarios (DBI storage,\n # etc)", "\n # after you've loaded the plugins you can save session data\n # For example, if you are writing a shopping cart, it could be implemented\n # like this:", " sub add_item : Local {\n my ( $self, $c ) = @_;", " my $item_id = $c->req->param(\"item\");", " # $c->session is a hash ref, a bit like $c->stash\n # the difference is that it' preserved across requests", " push @{ $c->session->{items} }, $item_id;", " $c->forward(\"MyView\");\n }", " sub display_items : Local {\n my ( $self, $c ) = @_;", " # values in $c->session are restored\n $c->stash->{items_to_display} =\n [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];", " $c->forward(\"MyView\");\n }", "=head1 DESCRIPTION", "The Session plugin is the base of two related parts of functionality required\nfor session management in web applications.", "The first part, the State, is getting the browser to repeat back a session key,\nso that the web application can identify the client and logically string\nseveral requests together into a session.", "The second part, the Store, deals with the actual storage of information about\nthe client. This data is stored so that the it may be revived for every request\nmade by the same client.", "This plugin links the two pieces together.", "=head1 RECOMENDED BACKENDS", "=over 4", "=item Session::State::Cookie", "The only really sane way to do state is using cookies.", "=item Session::Store::File", "A portable backend, based on Cache::File.", "=item Session::Store::FastMmap", "A fast and flexible backend, based on Cache::FastMmap.", "=back", "=head1 METHODS", "=over 4", "=item sessionid", "An accessor for the session ID value.", "=item session", "Returns a hash reference that might contain unserialized values from previous\nrequests in the same session, and whose modified value will be saved for future\nrequests.", "This method will automatically create a new session and session ID if none\nexists.", "You can also set session keys by passing a list of key/value pairs or a\nhashref.", " $c->session->{foo} = \"bar\"; # This works.\n $c->session(one => 1, two => 2); # And this.\n $c->session({ answer => 42 }); # And this.", "=item session_expires", "This method returns the time when the current session will expire, or 0 if\nthere is no current session. If there is a session and it already expired, it\nwill delete the session and return 0 as well.", "=item flash", "This is like Ruby on Rails' flash data structure. Think of it as a stash that\nlasts for longer than one request, letting you redirect instead of forward.", "The flash data will be cleaned up only on requests on which actually use\n$c->flash (thus allowing multiple redirections), and the policy is to delete\nall the keys which haven't changed since the flash data was loaded at the end\nof every request.", "Note that use of the flash is an easy way to get data across requests, but\nit's also strongly disrecommended, due it it being inherently plagued with\nrace conditions. This means that it's unlikely to work well if your\nusers have multiple tabs open at once, or if your site does a lot of AJAX\nrequests.", "L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,\nas this doesn't suffer from these issues.", " sub moose : Local {\n my ( $self, $c ) = @_;", " $c->flash->{beans} = 10;\n $c->response->redirect( $c->uri_for(\"foo\") );\n }", " sub foo : Local {\n my ( $self, $c ) = @_;", " my $value = $c->flash->{beans};", " # ...", " $c->response->redirect( $c->uri_for(\"bar\") );\n }", " sub bar : Local {\n my ( $self, $c ) = @_;", " if ( exists $c->flash->{beans} ) { # false", " }\n }", "=item clear_flash", "Zap all the keys in the flash regardless of their current state.", "=item keep_flash @keys", "If you want to keep a flash key for the next request too, even if it hasn't\nchanged, call C<keep_flash> and pass in the keys as arguments.", "=item delete_session REASON", "This method is used to invalidate a session. It takes an optional parameter\nwhich will be saved in C<session_delete_reason> if provided.", "NOTE: This method will B<also> delete your flash data.", "=item session_delete_reason", "This accessor contains a string with the reason a session was deleted. Possible\nvalues include:", "=over 4", "=item *", "C<address mismatch>", "=item *", "C<session expired>", "=back", "=item session_expire_key $key, $ttl", "Mark a key to expire at a certain time (only useful when shorter than the\nexpiry time for the whole session).", "For example:", " __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # \"forever\"\n (NB If this number is too large, Y2K38 breakage could result.)", " # later", " $c->session_expire_key( __user => 3600 );", "Will make the session data survive, but the user will still be logged out after\nan hour.", "Note that these values are not auto extended.", "=item change_session_id", "By calling this method you can force a session id change while keeping all\nsession data. This method might come handy when you are paranoid about some\nadvanced variations of session fixation attack.", "If you want to prevent this session fixation scenario:", " 0) let us have WebApp with anonymous and authenticated parts\n 1) a hacker goes to vulnerable WebApp and gets a real sessionid,\n just by browsing anonymous part of WebApp\n 2) the hacker inserts (somehow) this values into a cookie in victim's browser\n 3) after the victim logs into WebApp the hacker can enter his/her session", "you should call change_session_id in your login controller like this:", " if ($c->authenticate( { username => $user, password => $pass } )) {\n # login OK\n $c->change_session_id;\n ...\n } else {\n # login FAILED\n ...\n }", "=item change_session_expires $expires", "You can change the session expiration time for this session;", " $c->change_session_expires( 4000 );", "Note that this only works to set the session longer than the config setting.", "=back", "=head1 INTERNAL METHODS", "=over 4", "=item setup", "This method is extended to also make calls to\nC<check_session_plugin_requirements> and C<setup_session>.", "=item check_session_plugin_requirements", "This method ensures that a State and a Store plugin are also in use by the\napplication.", "=item setup_session", "This method populates C<< $c->config('Plugin::Session') >> with the default values\nlisted in L</CONFIGURATION>.", "=item prepare_action", "This method is extended.", "Its only effect is if the (off by default) C<flash_to_stash> configuration\nparameter is on - then it will copy the contents of the flash to the stash at\nprepare time.", "=item finalize_headers", "This method is extended and will extend the expiry time before sending\nthe response.", "=item finalize_body", "This method is extended and will call finalize_session before the other\nfinalize_body methods run. Here we persist the session data if a session exists.", "=item initialize_session_data", "This method will initialize the internal structure of the session, and is\ncalled by the C<session> method if appropriate.", "=item create_session_id", "Creates a new session ID using C<generate_session_id> if there is no session ID\nyet.", "=item validate_session_id SID", "Make sure a session ID is of the right format.", "This currently ensures that the session ID string is any amount of case\ninsensitive hexadecimal characters.", "=item generate_session_id", "This method will return a string that can be used as a session ID. It is\nsupposed to be a reasonably random string with enough bits to prevent\ncollision. It basically takes C<session_hash_seed> and hashes it using SHA-1,\nMD5 or SHA-256, depending on the availability of these modules.", "=item session_hash_seed", "This method is actually rather internal to generate_session_id, but should be\noverridable in case you want to provide more random data.", "Currently it returns a concatenated string which contains:", "=over 4", "=item * A counter", "=item * The current time", "=item * One value from C<rand>.", "=item * The stringified value of a newly allocated hash reference", "=item * The stringified value of the Catalyst context object", "=back", "in the hopes that those combined values are entropic enough for most uses. If\nthis is not the case you can replace C<session_hash_seed> with e.g.", " sub session_hash_seed {\n open my $fh, \"<\", \"/dev/random\";\n read $fh, my $bytes, 20;\n close $fh;\n return $bytes;\n }", "Or even more directly, replace C<generate_session_id>:", " sub generate_session_id {\n open my $fh, \"<\", \"/dev/random\";\n read $fh, my $bytes, 20;\n close $fh;\n return unpack(\"H*\", $bytes);\n }", "Also have a look at L<Crypt::Random> and the various openssl bindings - these\nmodules provide APIs for cryptographically secure random data.", "=item finalize_session", "Clean up the session during C<finalize>.", "This clears the various accessors after saving to the store.", "=item dump_these", "See L<Catalyst/dump_these> - ammends the session data structure to the list of\ndumped objects if session ID is defined.", "\n=item calculate_extended_session_expires", "=item calculate_initial_session_expires", "=item create_session_id_if_needed", "=item delete_session_id", "=item extend_session_expires", "Note: this is *not* used to give an individual user a longer session. See\n'change_session_expires'.", "=item extend_session_id", "=item get_session_id", "=item reset_session_expires", "=item session_is_valid", "=item set_session_id", "=item initial_session_expires", "=back", "=head1 USING SESSIONS DURING PREPARE", "The earliest point in time at which you may use the session data is after\nL<Catalyst::Plugin::Session>'s C<prepare_action> has finished.", "State plugins must set $c->session ID before C<prepare_action>, and during\nC<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from\nthe store.", " sub prepare_action {\n my $c = shift;", " # don't touch $c->session yet!", " $c->NEXT::prepare_action( @_ );", " $c->session; # this is OK\n $c->sessionid; # this is also OK\n }", "=head1 CONFIGURATION", " $c->config('Plugin::Session' => {\n expires => 1234,\n });", "All configuation parameters are provided in a hash reference under the\nC<Plugin::Session> key in the configuration hash.", "=over 4", "=item expires", "The time-to-live of each session, expressed in seconds. Defaults to 7200 (two\nhours).", "=item expiry_threshold", "Only update the session expiry time if it would otherwise expire\nwithin this many seconds from now.", "The purpose of this is to keep the session store from being updated\nwhen nothing else in the session is updated.", "Defaults to 0 (in which case, the expiration will always be updated).", "=item verify_address", "When true, C<< $c->request->address >> will be checked at prepare time. If it is\nnot the same as the address that initiated the session, the session is deleted.", "Defaults to false.", "=item verify_user_agent", "When true, C<< $c->request->user_agent >> will be checked at prepare time. If it\nis not the same as the user agent that initiated the session, the session is\ndeleted.", "Defaults to false.", "=item flash_to_stash", "This option makes it easier to have actions behave the same whether they were\nforwarded to or redirected to. On prepare time it copies the contents of\nC<flash> (if any) to the stash.", "=back", "=head1 SPECIAL KEYS", "The hash reference returned by C<< $c->session >> contains several keys which\nare automatically set:", "=over 4", "=item __expires", "This key no longer exists. Use C<session_expires> instead.", "=item __updated", "The last time a session was saved to the store.", "=item __created", "The time when the session was first created.", "=item __address", "The value of C<< $c->request->address >> at the time the session was created.\nThis value is only populated if C<verify_address> is true in the configuration.", "=item __user_agent", "The value of C<< $c->request->user_agent >> at the time the session was created.\nThis value is only populated if C<verify_user_agent> is true in the configuration.", "=back", "=head1 CAVEATS", "=head2 Round the Robin Proxies", "C<verify_address> could make your site inaccessible to users who are behind\nload balanced proxies. Some ISPs may give a different IP to each request by the\nsame client due to this type of proxying. If addresses are verified these\nusers' sessions cannot persist.", "To let these users access your site you can either disable address verification\nas a whole, or provide a checkbox in the login dialog that tells the server\nthat it's OK for the address of the client to change. When the server sees that\nthis box is checked it should delete the C<__address> special key from the\nsession hash when the hash is first created.", "=head2 Race Conditions", "In this day and age where cleaning detergents and Dutch football (not the\nAmerican kind) teams roam the plains in great numbers, requests may happen\nsimultaneously. This means that there is some risk of session data being\noverwritten, like this:", "=over 4", "=item 1.", "request a starts, request b starts, with the same session ID", "=item 2.", "session data is loaded in request a", "=item 3.", "session data is loaded in request b", "=item 4.", "session data is changed in request a", "=item 5.", "request a finishes, session data is updated and written to store", "=item 6.", "request b finishes, session data is updated and written to store, overwriting\nchanges by request a", "=back", "For applications where any given user's session is only making one request\nat a time this plugin should be safe enough.", "=head1 AUTHORS", "Andy Grundman", "Christian Hansen", "Yuval Kogman, C<nothingmuch@woobling.org>", "Sebastian Riedel", "Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)", "Sergio Salvi", "kmx C<kmx@volny.cz>", "Florian Ragwitz (rafl) C<rafl@debian.org>", "Kent Fredric (kentnl)", "And countless other contributers from #catalyst. Thanks guys!", "=head1 Contributors", "Devin Austin (dhoss) <dhoss@cpan.org>", "Robert Rothenberg <rrwo@cpan.org> (on behalf of Foxtons Ltd.)", "=head1 COPYRIGHT & LICENSE", " Copyright (c) 2005 the aforementioned authors. All rights\n reserved. This program is free software; you can redistribute\n it and/or modify it under the same terms as Perl itself.", "=cut" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [482], "buggy_code_start_loc": [11], "filenames": ["lib/Catalyst/Plugin/Session.pm"], "fixing_code_end_loc": [485], "fixing_code_start_loc": [12], "message": "A vulnerability has been found in Catalyst-Plugin-Session up to 0.40 and classified as problematic. This vulnerability affects the function _load_sessionid of the file lib/Catalyst/Plugin/Session.pm of the component Session ID Handler. The manipulation of the argument sid leads to cross site scripting. The attack can be initiated remotely. Upgrading to version 0.41 is able to address this issue. The name of the patch is 88d1b599e1163761c9bd53bec53ba078f13e09d4. It is recommended to upgrade the affected component. VDB-216958 is the identifier assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:catalyst-plugin-session_project:catalyst-plugin-session:*:*:*:*:*:*:*:*", "matchCriteriaId": "B2E8D730-08F5-4D5C-8BD8-6E5520647EF1", "versionEndExcluding": "0.41", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in Catalyst-Plugin-Session up to 0.40 and classified as problematic. This vulnerability affects the function _load_sessionid of the file lib/Catalyst/Plugin/Session.pm of the component Session ID Handler. The manipulation of the argument sid leads to cross site scripting. The attack can be initiated remotely. Upgrading to version 0.41 is able to address this issue. The name of the patch is 88d1b599e1163761c9bd53bec53ba078f13e09d4. It is recommended to upgrade the affected component. VDB-216958 is the identifier assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2018-25052", "lastModified": "2023-01-06T19:11:19.490", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-28T12:15:08.607", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/commit/88d1b599e1163761c9bd53bec53ba078f13e09d4"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/releases/tag/0.41"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.216958"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216958"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/commit/88d1b599e1163761c9bd53bec53ba078f13e09d4"}, "type": "CWE-79"}
113
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/perl", "package Catalyst::Plugin::Session;", "use Moose;\nwith 'MooseX::Emulate::Class::Accessor::Fast';\nuse MRO::Compat;\nuse Catalyst::Exception ();\nuse Digest ();\nuse overload ();\nuse Object::Signature ();", "use HTML::Entities ();", "use Carp;\nuse List::Util qw/ max /;", "use namespace::clean -except => 'meta';", "our $VERSION = '0.40';\n$VERSION = eval $VERSION;", "my @session_data_accessors; # used in delete_session", "__PACKAGE__->mk_accessors(\n \"_session_delete_reason\",\n @session_data_accessors = qw/\n _sessionid\n _session\n _session_expires\n _extended_session_expires\n _session_data_sig\n _flash\n _flash_keep_keys\n _flash_key_hashes\n _tried_loading_session_id\n _tried_loading_session_data\n _tried_loading_session_expires\n _tried_loading_flash_data\n _needs_early_session_finalization\n /\n);", "sub _session_plugin_config {\n my $c = shift;\n # FIXME - Start warning once all the state/store modules have also been updated.\n #$c->log->warn(\"Deprecated 'session' config key used, please use the key 'Plugin::Session' instead\")\n # if exists $c->config->{session}\n #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};\n $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};\n}", "sub setup {\n my $c = shift;", " $c->maybe::next::method(@_);", " $c->check_session_plugin_requirements;\n $c->setup_session;", " return $c;\n}", "sub check_session_plugin_requirements {\n my $c = shift;", " unless ( $c->isa(\"Catalyst::Plugin::Session::State\")\n && $c->isa(\"Catalyst::Plugin::Session::Store\") )\n {\n my $err =\n ( \"The Session plugin requires both Session::State \"\n . \"and Session::Store plugins to be used as well.\" );", " $c->log->fatal($err);\n Catalyst::Exception->throw($err);\n }\n}", "sub setup_session {\n my $c = shift;", " my $cfg = $c->_session_plugin_config;", " %$cfg = (\n expires => 7200,\n verify_address => 0,\n verify_user_agent => 0,\n expiry_threshold => 0,\n %$cfg,\n );", " $c->maybe::next::method();\n}", "sub prepare_action {\n my $c = shift;", " $c->maybe::next::method(@_);", " if ( $c->_session_plugin_config->{flash_to_stash}\n and $c->sessionid\n and my $flash_data = $c->flash )\n {\n @{ $c->stash }{ keys %$flash_data } = values %$flash_data;\n }\n}", "sub finalize_headers {\n my $c = shift;", " # fix cookie before we send headers\n $c->_save_session_expires;", " # Force extension of session_expires before finalizing headers, so a pos\n # up to date. First call to session_expires will extend the expiry, subs\n # just return the previously extended value.\n $c->session_expires;\n $c->finalize_session if $c->_needs_early_session_finalization;", " return $c->maybe::next::method(@_);\n}", "sub finalize_body {\n my $c = shift;", " # We have to finalize our session *before* $c->engine->finalize_xxx is called,\n # because we do not want to send the HTTP response before the session is stored/committed to\n # the session database (or whatever Session::Store you use).\n $c->finalize_session unless $c->_needs_early_session_finalization;\n $c->_clear_session_instance_data;", " return $c->maybe::next::method(@_);\n}", "sub finalize_session {\n my $c = shift;", " $c->maybe::next::method(@_);", " $c->_save_session_id;\n $c->_save_session;\n $c->_save_flash;", "}", "sub _session_updated {\n my $c = shift;", " if ( my $session_data = $c->_session ) {", " no warnings 'uninitialized';\n if ( Object::Signature::signature($session_data) ne\n $c->_session_data_sig )\n {\n return $session_data;\n } else {\n return;\n }", " } else {", " return;", " }\n}", "sub _save_session_id {\n my $c = shift;", " # we already called set when allocating\n # no need to tell the state plugins anything new\n}", "sub _save_session_expires {\n my $c = shift;", " if ( defined($c->_session_expires) ) {", " if (my $sid = $c->sessionid) {", " my $current = $c->_get_stored_session_expires;\n my $extended = $c->session_expires;\n if ($extended > $current) {\n $c->store_session_data( \"expires:$sid\" => $extended );\n }", " }\n }\n}", "sub _save_session {\n my $c = shift;", " if ( my $session_data = $c->_session_updated ) {", " $session_data->{__updated} = time();\n my $sid = $c->sessionid;\n $c->store_session_data( \"session:$sid\" => $session_data );\n }\n}", "sub _save_flash {\n my $c = shift;", " if ( my $flash_data = $c->_flash ) {", " my $hashes = $c->_flash_key_hashes || {};\n my $keep = $c->_flash_keep_keys || {};\n foreach my $key ( keys %$hashes ) {\n if ( !exists $keep->{$key} and Object::Signature::signature( \\$flash_data->{$key} ) eq $hashes->{$key} ) {\n delete $flash_data->{$key};\n }\n }", " my $sid = $c->sessionid;", " my $session_data = $c->_session;\n if (%$flash_data) {\n $session_data->{__flash} = $flash_data;\n }\n else {\n delete $session_data->{__flash};\n }\n $c->_session($session_data);\n $c->_save_session;\n }\n}", "sub _load_session_expires {\n my $c = shift;\n return $c->_session_expires if $c->_tried_loading_session_expires;\n $c->_tried_loading_session_expires(1);", " if ( my $sid = $c->sessionid ) {\n my $expires = $c->_get_stored_session_expires;", " if ( $expires >= time() ) {\n $c->_session_expires( $expires );\n return $expires;\n } else {\n $c->delete_session( \"session expired\" );\n return 0;\n }\n }", " return;\n}", "sub _load_session {\n my $c = shift;\n return $c->_session if $c->_tried_loading_session_data;\n $c->_tried_loading_session_data(1);", " if ( my $sid = $c->sessionid ) {\n if ( $c->_load_session_expires ) { # > 0", " my $session_data = $c->get_session_data(\"session:$sid\") || return;\n $c->_session($session_data);", " no warnings 'uninitialized'; # ne __address\n if ( $c->_session_plugin_config->{verify_address}\n && exists $session_data->{__address}\n && $session_data->{__address} ne $c->request->address )\n {\n $c->log->warn(\n \"Deleting session $sid due to address mismatch (\"\n . $session_data->{__address} . \" != \"\n . $c->request->address . \")\"\n );\n $c->delete_session(\"address mismatch\");\n return;\n }\n if ( $c->_session_plugin_config->{verify_user_agent}\n && $session_data->{__user_agent} ne $c->request->user_agent )\n {\n $c->log->warn(\n \"Deleting session $sid due to user agent mismatch (\"\n . $session_data->{__user_agent} . \" != \"\n . $c->request->user_agent . \")\"\n );\n $c->delete_session(\"user agent mismatch\");\n return;\n }", " $c->log->debug(qq/Restored session \"$sid\"/) if $c->debug;\n $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;\n $c->_expire_session_keys;", " return $session_data;\n }\n }", " return;\n}", "sub _load_flash {\n my $c = shift;\n return $c->_flash if $c->_tried_loading_flash_data;\n $c->_tried_loading_flash_data(1);", " if ( my $sid = $c->sessionid ) {", " my $session_data = $c->session;\n $c->_flash($session_data->{__flash});", " if ( my $flash_data = $c->_flash )\n {\n $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \\$flash_data->{$_} ) } keys %$flash_data });", " return $flash_data;\n }\n }", " return;\n}", "sub _expire_session_keys {\n my ( $c, $data ) = @_;", " my $now = time;", " my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};\n foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {\n delete $c->_session->{$key};\n delete $expire_times->{$key};\n }\n}", "sub _clear_session_instance_data {\n my $c = shift;\n $c->$_(undef) for @session_data_accessors;\n $c->maybe::next::method(@_); # allow other plugins to hook in on this\n}", "sub change_session_id {\n my $c = shift;", " my $sessiondata = $c->session;\n my $oldsid = $c->sessionid;\n my $newsid = $c->create_session_id;", " if ($oldsid) {\n $c->log->debug(qq/change_sessid: deleting session data from \"$oldsid\"/) if $c->debug;\n $c->delete_session_data(\"${_}:${oldsid}\") for qw/session expires flash/;\n }", " $c->log->debug(qq/change_sessid: storing session data to \"$newsid\"/) if $c->debug;\n $c->store_session_data( \"session:$newsid\" => $sessiondata );", " return $newsid;\n}", "sub delete_session {\n my ( $c, $msg ) = @_;", " $c->log->debug(\"Deleting session\" . ( defined($msg) ? \"($msg)\" : '(no reason given)') ) if $c->debug;", " # delete the session data\n if ( my $sid = $c->sessionid ) {\n $c->delete_session_data(\"${_}:${sid}\") for qw/session expires flash/;\n $c->delete_session_id($sid);\n }", " # reset the values in the context object\n # see the BEGIN block\n $c->_clear_session_instance_data;", " $c->_session_delete_reason($msg);\n}", "sub session_delete_reason {\n my $c = shift;", " $c->session_is_valid; # check that it was loaded", " $c->_session_delete_reason(@_);\n}", "sub session_expires {\n my $c = shift;", " if ( defined( my $expires = $c->_extended_session_expires ) ) {\n return $expires;\n } elsif ( defined( $expires = $c->_load_session_expires ) ) {\n return $c->extend_session_expires( $expires );\n } else {\n return 0;\n }\n}", "sub extend_session_expires {\n my ( $c, $expires ) = @_;", " my $threshold = $c->_session_plugin_config->{expiry_threshold} || 0;", " if ( my $sid = $c->sessionid ) {\n my $expires = $c->_get_stored_session_expires;\n my $cutoff = $expires - $threshold;", " if (!$threshold || $cutoff <= time || $c->_session_updated) {", " $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires() );\n $c->extend_session_id( $sid, $updated );", " return $updated;", " } else {", " return $expires;", " }", " } else {", " return;", " }", "}", "sub change_session_expires {\n my ( $c, $expires ) = @_;", " $expires ||= 0;\n my $sid = $c->sessionid;\n my $time_exp = time() + $expires;\n $c->store_session_data( \"expires:$sid\" => $time_exp );\n}", "sub _get_stored_session_expires {\n my ($c) = @_;", " if ( my $sid = $c->sessionid ) {\n return $c->get_session_data(\"expires:$sid\") || 0;\n } else {\n return 0;\n }\n}", "sub initial_session_expires {\n my $c = shift;\n return ( time() + $c->_session_plugin_config->{expires} );\n}", "sub calculate_initial_session_expires {\n my ($c) = @_;\n return max( $c->initial_session_expires, $c->_get_stored_session_expires );\n}", "sub calculate_extended_session_expires {\n my ( $c, $prev ) = @_;\n return ( time() + $prev );\n}", "sub reset_session_expires {\n my ( $c, $sid ) = @_;", " my $exp = $c->calculate_initial_session_expires;\n $c->_session_expires( $exp );\n #\n # since we're setting _session_expires directly, make load_session_expires\n # actually use that value.\n #\n $c->_tried_loading_session_expires(1);\n $c->_extended_session_expires( $exp );\n $exp;\n}", "sub sessionid {\n my $c = shift;", " return $c->_sessionid || $c->_load_sessionid;\n}", "sub _load_sessionid {\n my $c = shift;\n return if $c->_tried_loading_session_id;\n $c->_tried_loading_session_id(1);", " if ( defined( my $sid = $c->get_session_id ) ) {\n if ( $c->validate_session_id($sid) ) {\n # temporarily set the inner key, so that validation will work\n $c->_sessionid($sid);\n return $sid;\n } else {", " $sid = HTML::Entities::encode_entities($sid);", " my $err = \"Tried to set invalid session ID '$sid'\";\n $c->log->error($err);\n Catalyst::Exception->throw($err);\n }\n }", " return;\n}", "sub session_is_valid {\n my $c = shift;", " # force a check for expiry, but also __address, etc\n if ( $c->_load_session ) {\n return 1;\n } else {\n return;\n }\n}", "sub validate_session_id {\n my ( $c, $sid ) = @_;", " $sid and $sid =~ /^[a-f\\d]+$/i;\n}", "sub session {\n my $c = shift;", " my $session = $c->_session || $c->_load_session || do {\n $c->create_session_id_if_needed;\n $c->initialize_session_data;\n };", " if (@_) {\n my $new_values = @_ > 1 ? { @_ } : $_[0];\n croak('session takes a hash or hashref') unless ref $new_values;", " for my $key (keys %$new_values) {\n $session->{$key} = $new_values->{$key};\n }\n }", " $session;\n}", "sub keep_flash {\n my ( $c, @keys ) = @_;\n my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});\n (@{$href}{@keys}) = ((undef) x @keys);\n}", "sub _flash_data {\n my $c = shift;\n $c->_flash || $c->_load_flash || do {\n $c->create_session_id_if_needed;\n $c->_flash( {} );\n };\n}", "sub _set_flash {\n my $c = shift;\n if (@_) {\n my $items = @_ > 1 ? {@_} : $_[0];\n croak('flash takes a hash or hashref') unless ref $items;\n @{ $c->_flash }{ keys %$items } = values %$items;\n }\n}", "sub flash {\n my $c = shift;\n $c->_flash_data;\n $c->_set_flash(@_);\n return $c->_flash;\n}", "sub clear_flash {\n my $c = shift;", " #$c->delete_session_data(\"flash:\" . $c->sessionid); # should this be in here? or delayed till finalization?\n $c->_flash_key_hashes({});\n $c->_flash_keep_keys({});\n $c->_flash({});\n}", "sub session_expire_key {\n my ( $c, %keys ) = @_;", " my $now = time;\n @{ $c->session->{__expire_keys} }{ keys %keys } =\n map { $now + $_ } values %keys;\n}", "sub initialize_session_data {\n my $c = shift;", " my $now = time;", " return $c->_session(\n {\n __created => $now,\n __updated => $now,", " (\n $c->_session_plugin_config->{verify_address}\n ? ( __address => $c->request->address||'' )\n : ()\n ),\n (\n $c->_session_plugin_config->{verify_user_agent}\n ? ( __user_agent => $c->request->user_agent||'' )\n : ()\n ),\n }\n );\n}", "sub generate_session_id {\n my $c = shift;", " my $digest = $c->_find_digest();\n $digest->add( $c->session_hash_seed() );\n return $digest->hexdigest;\n}", "sub create_session_id_if_needed {\n my $c = shift;\n $c->create_session_id unless $c->sessionid;\n}", "sub create_session_id {\n my $c = shift;", " my $sid = $c->generate_session_id;", " $c->log->debug(qq/Created session \"$sid\"/) if $c->debug;", " $c->_sessionid($sid);\n $c->reset_session_expires;\n $c->set_session_id($sid);", " return $sid;\n}", "my $counter;", "sub session_hash_seed {\n my $c = shift;", " return join( \"\", ++$counter, time, rand, $$, {}, overload::StrVal($c), );\n}", "my $usable;", "sub _find_digest () {\n unless ($usable) {\n foreach my $alg (qw/SHA-1 SHA-256 MD5/) {\n if ( eval { Digest->new($alg) } ) {\n $usable = $alg;\n last;\n }\n }\n Catalyst::Exception->throw(\n \"Could not find a suitable Digest module. Please install \"\n . \"Digest::SHA1, Digest::SHA, or Digest::MD5\" )\n unless $usable;\n }", " return Digest->new($usable);\n}", "sub dump_these {\n my $c = shift;", " (\n $c->maybe::next::method(),", " $c->_sessionid\n ? ( [ \"Session ID\" => $c->sessionid ], [ Session => $c->session ], )\n : ()\n );\n}", "\nsub get_session_id { shift->maybe::next::method(@_) }\nsub set_session_id { shift->maybe::next::method(@_) }\nsub delete_session_id { shift->maybe::next::method(@_) }\nsub extend_session_id { shift->maybe::next::method(@_) }", "__PACKAGE__;", "__END__", "=pod", "=head1 NAME", "Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.", "=head1 SYNOPSIS", " # To get sessions to \"just work\", all you need to do is use these plugins:", " use Catalyst qw/\n Session\n Session::Store::FastMmap\n Session::State::Cookie\n /;", " # you can replace Store::FastMmap with Store::File - both have sensible\n # default configurations (see their docs for details)", " # more complicated backends are available for other scenarios (DBI storage,\n # etc)", "\n # after you've loaded the plugins you can save session data\n # For example, if you are writing a shopping cart, it could be implemented\n # like this:", " sub add_item : Local {\n my ( $self, $c ) = @_;", " my $item_id = $c->req->param(\"item\");", " # $c->session is a hash ref, a bit like $c->stash\n # the difference is that it' preserved across requests", " push @{ $c->session->{items} }, $item_id;", " $c->forward(\"MyView\");\n }", " sub display_items : Local {\n my ( $self, $c ) = @_;", " # values in $c->session are restored\n $c->stash->{items_to_display} =\n [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];", " $c->forward(\"MyView\");\n }", "=head1 DESCRIPTION", "The Session plugin is the base of two related parts of functionality required\nfor session management in web applications.", "The first part, the State, is getting the browser to repeat back a session key,\nso that the web application can identify the client and logically string\nseveral requests together into a session.", "The second part, the Store, deals with the actual storage of information about\nthe client. This data is stored so that the it may be revived for every request\nmade by the same client.", "This plugin links the two pieces together.", "=head1 RECOMENDED BACKENDS", "=over 4", "=item Session::State::Cookie", "The only really sane way to do state is using cookies.", "=item Session::Store::File", "A portable backend, based on Cache::File.", "=item Session::Store::FastMmap", "A fast and flexible backend, based on Cache::FastMmap.", "=back", "=head1 METHODS", "=over 4", "=item sessionid", "An accessor for the session ID value.", "=item session", "Returns a hash reference that might contain unserialized values from previous\nrequests in the same session, and whose modified value will be saved for future\nrequests.", "This method will automatically create a new session and session ID if none\nexists.", "You can also set session keys by passing a list of key/value pairs or a\nhashref.", " $c->session->{foo} = \"bar\"; # This works.\n $c->session(one => 1, two => 2); # And this.\n $c->session({ answer => 42 }); # And this.", "=item session_expires", "This method returns the time when the current session will expire, or 0 if\nthere is no current session. If there is a session and it already expired, it\nwill delete the session and return 0 as well.", "=item flash", "This is like Ruby on Rails' flash data structure. Think of it as a stash that\nlasts for longer than one request, letting you redirect instead of forward.", "The flash data will be cleaned up only on requests on which actually use\n$c->flash (thus allowing multiple redirections), and the policy is to delete\nall the keys which haven't changed since the flash data was loaded at the end\nof every request.", "Note that use of the flash is an easy way to get data across requests, but\nit's also strongly disrecommended, due it it being inherently plagued with\nrace conditions. This means that it's unlikely to work well if your\nusers have multiple tabs open at once, or if your site does a lot of AJAX\nrequests.", "L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,\nas this doesn't suffer from these issues.", " sub moose : Local {\n my ( $self, $c ) = @_;", " $c->flash->{beans} = 10;\n $c->response->redirect( $c->uri_for(\"foo\") );\n }", " sub foo : Local {\n my ( $self, $c ) = @_;", " my $value = $c->flash->{beans};", " # ...", " $c->response->redirect( $c->uri_for(\"bar\") );\n }", " sub bar : Local {\n my ( $self, $c ) = @_;", " if ( exists $c->flash->{beans} ) { # false", " }\n }", "=item clear_flash", "Zap all the keys in the flash regardless of their current state.", "=item keep_flash @keys", "If you want to keep a flash key for the next request too, even if it hasn't\nchanged, call C<keep_flash> and pass in the keys as arguments.", "=item delete_session REASON", "This method is used to invalidate a session. It takes an optional parameter\nwhich will be saved in C<session_delete_reason> if provided.", "NOTE: This method will B<also> delete your flash data.", "=item session_delete_reason", "This accessor contains a string with the reason a session was deleted. Possible\nvalues include:", "=over 4", "=item *", "C<address mismatch>", "=item *", "C<session expired>", "=back", "=item session_expire_key $key, $ttl", "Mark a key to expire at a certain time (only useful when shorter than the\nexpiry time for the whole session).", "For example:", " __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # \"forever\"\n (NB If this number is too large, Y2K38 breakage could result.)", " # later", " $c->session_expire_key( __user => 3600 );", "Will make the session data survive, but the user will still be logged out after\nan hour.", "Note that these values are not auto extended.", "=item change_session_id", "By calling this method you can force a session id change while keeping all\nsession data. This method might come handy when you are paranoid about some\nadvanced variations of session fixation attack.", "If you want to prevent this session fixation scenario:", " 0) let us have WebApp with anonymous and authenticated parts\n 1) a hacker goes to vulnerable WebApp and gets a real sessionid,\n just by browsing anonymous part of WebApp\n 2) the hacker inserts (somehow) this values into a cookie in victim's browser\n 3) after the victim logs into WebApp the hacker can enter his/her session", "you should call change_session_id in your login controller like this:", " if ($c->authenticate( { username => $user, password => $pass } )) {\n # login OK\n $c->change_session_id;\n ...\n } else {\n # login FAILED\n ...\n }", "=item change_session_expires $expires", "You can change the session expiration time for this session;", " $c->change_session_expires( 4000 );", "Note that this only works to set the session longer than the config setting.", "=back", "=head1 INTERNAL METHODS", "=over 4", "=item setup", "This method is extended to also make calls to\nC<check_session_plugin_requirements> and C<setup_session>.", "=item check_session_plugin_requirements", "This method ensures that a State and a Store plugin are also in use by the\napplication.", "=item setup_session", "This method populates C<< $c->config('Plugin::Session') >> with the default values\nlisted in L</CONFIGURATION>.", "=item prepare_action", "This method is extended.", "Its only effect is if the (off by default) C<flash_to_stash> configuration\nparameter is on - then it will copy the contents of the flash to the stash at\nprepare time.", "=item finalize_headers", "This method is extended and will extend the expiry time before sending\nthe response.", "=item finalize_body", "This method is extended and will call finalize_session before the other\nfinalize_body methods run. Here we persist the session data if a session exists.", "=item initialize_session_data", "This method will initialize the internal structure of the session, and is\ncalled by the C<session> method if appropriate.", "=item create_session_id", "Creates a new session ID using C<generate_session_id> if there is no session ID\nyet.", "=item validate_session_id SID", "Make sure a session ID is of the right format.", "This currently ensures that the session ID string is any amount of case\ninsensitive hexadecimal characters.", "=item generate_session_id", "This method will return a string that can be used as a session ID. It is\nsupposed to be a reasonably random string with enough bits to prevent\ncollision. It basically takes C<session_hash_seed> and hashes it using SHA-1,\nMD5 or SHA-256, depending on the availability of these modules.", "=item session_hash_seed", "This method is actually rather internal to generate_session_id, but should be\noverridable in case you want to provide more random data.", "Currently it returns a concatenated string which contains:", "=over 4", "=item * A counter", "=item * The current time", "=item * One value from C<rand>.", "=item * The stringified value of a newly allocated hash reference", "=item * The stringified value of the Catalyst context object", "=back", "in the hopes that those combined values are entropic enough for most uses. If\nthis is not the case you can replace C<session_hash_seed> with e.g.", " sub session_hash_seed {\n open my $fh, \"<\", \"/dev/random\";\n read $fh, my $bytes, 20;\n close $fh;\n return $bytes;\n }", "Or even more directly, replace C<generate_session_id>:", " sub generate_session_id {\n open my $fh, \"<\", \"/dev/random\";\n read $fh, my $bytes, 20;\n close $fh;\n return unpack(\"H*\", $bytes);\n }", "Also have a look at L<Crypt::Random> and the various openssl bindings - these\nmodules provide APIs for cryptographically secure random data.", "=item finalize_session", "Clean up the session during C<finalize>.", "This clears the various accessors after saving to the store.", "=item dump_these", "See L<Catalyst/dump_these> - ammends the session data structure to the list of\ndumped objects if session ID is defined.", "\n=item calculate_extended_session_expires", "=item calculate_initial_session_expires", "=item create_session_id_if_needed", "=item delete_session_id", "=item extend_session_expires", "Note: this is *not* used to give an individual user a longer session. See\n'change_session_expires'.", "=item extend_session_id", "=item get_session_id", "=item reset_session_expires", "=item session_is_valid", "=item set_session_id", "=item initial_session_expires", "=back", "=head1 USING SESSIONS DURING PREPARE", "The earliest point in time at which you may use the session data is after\nL<Catalyst::Plugin::Session>'s C<prepare_action> has finished.", "State plugins must set $c->session ID before C<prepare_action>, and during\nC<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from\nthe store.", " sub prepare_action {\n my $c = shift;", " # don't touch $c->session yet!", " $c->NEXT::prepare_action( @_ );", " $c->session; # this is OK\n $c->sessionid; # this is also OK\n }", "=head1 CONFIGURATION", " $c->config('Plugin::Session' => {\n expires => 1234,\n });", "All configuation parameters are provided in a hash reference under the\nC<Plugin::Session> key in the configuration hash.", "=over 4", "=item expires", "The time-to-live of each session, expressed in seconds. Defaults to 7200 (two\nhours).", "=item expiry_threshold", "Only update the session expiry time if it would otherwise expire\nwithin this many seconds from now.", "The purpose of this is to keep the session store from being updated\nwhen nothing else in the session is updated.", "Defaults to 0 (in which case, the expiration will always be updated).", "=item verify_address", "When true, C<< $c->request->address >> will be checked at prepare time. If it is\nnot the same as the address that initiated the session, the session is deleted.", "Defaults to false.", "=item verify_user_agent", "When true, C<< $c->request->user_agent >> will be checked at prepare time. If it\nis not the same as the user agent that initiated the session, the session is\ndeleted.", "Defaults to false.", "=item flash_to_stash", "This option makes it easier to have actions behave the same whether they were\nforwarded to or redirected to. On prepare time it copies the contents of\nC<flash> (if any) to the stash.", "=back", "=head1 SPECIAL KEYS", "The hash reference returned by C<< $c->session >> contains several keys which\nare automatically set:", "=over 4", "=item __expires", "This key no longer exists. Use C<session_expires> instead.", "=item __updated", "The last time a session was saved to the store.", "=item __created", "The time when the session was first created.", "=item __address", "The value of C<< $c->request->address >> at the time the session was created.\nThis value is only populated if C<verify_address> is true in the configuration.", "=item __user_agent", "The value of C<< $c->request->user_agent >> at the time the session was created.\nThis value is only populated if C<verify_user_agent> is true in the configuration.", "=back", "=head1 CAVEATS", "=head2 Round the Robin Proxies", "C<verify_address> could make your site inaccessible to users who are behind\nload balanced proxies. Some ISPs may give a different IP to each request by the\nsame client due to this type of proxying. If addresses are verified these\nusers' sessions cannot persist.", "To let these users access your site you can either disable address verification\nas a whole, or provide a checkbox in the login dialog that tells the server\nthat it's OK for the address of the client to change. When the server sees that\nthis box is checked it should delete the C<__address> special key from the\nsession hash when the hash is first created.", "=head2 Race Conditions", "In this day and age where cleaning detergents and Dutch football (not the\nAmerican kind) teams roam the plains in great numbers, requests may happen\nsimultaneously. This means that there is some risk of session data being\noverwritten, like this:", "=over 4", "=item 1.", "request a starts, request b starts, with the same session ID", "=item 2.", "session data is loaded in request a", "=item 3.", "session data is loaded in request b", "=item 4.", "session data is changed in request a", "=item 5.", "request a finishes, session data is updated and written to store", "=item 6.", "request b finishes, session data is updated and written to store, overwriting\nchanges by request a", "=back", "For applications where any given user's session is only making one request\nat a time this plugin should be safe enough.", "=head1 AUTHORS", "Andy Grundman", "Christian Hansen", "Yuval Kogman, C<nothingmuch@woobling.org>", "Sebastian Riedel", "Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)", "Sergio Salvi", "kmx C<kmx@volny.cz>", "Florian Ragwitz (rafl) C<rafl@debian.org>", "Kent Fredric (kentnl)", "And countless other contributers from #catalyst. Thanks guys!", "=head1 Contributors", "Devin Austin (dhoss) <dhoss@cpan.org>", "Robert Rothenberg <rrwo@cpan.org> (on behalf of Foxtons Ltd.)", "=head1 COPYRIGHT & LICENSE", " Copyright (c) 2005 the aforementioned authors. All rights\n reserved. This program is free software; you can redistribute\n it and/or modify it under the same terms as Perl itself.", "=cut" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [482], "buggy_code_start_loc": [11], "filenames": ["lib/Catalyst/Plugin/Session.pm"], "fixing_code_end_loc": [485], "fixing_code_start_loc": [12], "message": "A vulnerability has been found in Catalyst-Plugin-Session up to 0.40 and classified as problematic. This vulnerability affects the function _load_sessionid of the file lib/Catalyst/Plugin/Session.pm of the component Session ID Handler. The manipulation of the argument sid leads to cross site scripting. The attack can be initiated remotely. Upgrading to version 0.41 is able to address this issue. The name of the patch is 88d1b599e1163761c9bd53bec53ba078f13e09d4. It is recommended to upgrade the affected component. VDB-216958 is the identifier assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:catalyst-plugin-session_project:catalyst-plugin-session:*:*:*:*:*:*:*:*", "matchCriteriaId": "B2E8D730-08F5-4D5C-8BD8-6E5520647EF1", "versionEndExcluding": "0.41", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in Catalyst-Plugin-Session up to 0.40 and classified as problematic. This vulnerability affects the function _load_sessionid of the file lib/Catalyst/Plugin/Session.pm of the component Session ID Handler. The manipulation of the argument sid leads to cross site scripting. The attack can be initiated remotely. Upgrading to version 0.41 is able to address this issue. The name of the patch is 88d1b599e1163761c9bd53bec53ba078f13e09d4. It is recommended to upgrade the affected component. VDB-216958 is the identifier assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2018-25052", "lastModified": "2023-01-06T19:11:19.490", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-28T12:15:08.607", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/commit/88d1b599e1163761c9bd53bec53ba078f13e09d4"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/releases/tag/0.41"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?ctiid.216958"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216958"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/perl-catalyst/Catalyst-Plugin-Session/commit/88d1b599e1163761c9bd53bec53ba078f13e09d4"}, "type": "CWE-79"}
113
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007 Oracle. All rights reserved.\n *\n * This software is available to you under a choice of one of two\n * licenses. You may choose to be licensed under the terms of the GNU\n * General Public License (GPL) Version 2, available from the file\n * COPYING in the main directory of this source tree, or the\n * OpenIB.org BSD license below:\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * - Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * disclaimer.\n *\n * - Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n */\n#include <linux/pagemap.h>\n#include <linux/slab.h>\n#include <linux/rbtree.h>\n#include <linux/dma-mapping.h> /* for DMA_*_DEVICE */", "#include \"rds.h\"", "/*\n * XXX\n * - build with sparse\n * - should we detect duplicate keys on a socket? hmm.\n * - an rdma is an mlock, apply rlimit?\n */", "/*\n * get the number of pages by looking at the page indices that the start and\n * end addresses fall in.\n *\n * Returns 0 if the vec is invalid. It is invalid if the number of bytes\n * causes the address to wrap or overflows an unsigned int. This comes\n * from being stored in the 'length' member of 'struct scatterlist'.\n */\nstatic unsigned int rds_pages_in_vec(struct rds_iovec *vec)\n{\n\tif ((vec->addr + vec->bytes <= vec->addr) ||\n\t (vec->bytes > (u64)UINT_MAX))\n\t\treturn 0;", "\treturn ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) -\n\t\t(vec->addr >> PAGE_SHIFT);\n}", "static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key,\n\t\t\t\t struct rds_mr *insert)\n{\n\tstruct rb_node **p = &root->rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct rds_mr *mr;", "\twhile (*p) {\n\t\tparent = *p;\n\t\tmr = rb_entry(parent, struct rds_mr, r_rb_node);", "\t\tif (key < mr->r_key)\n\t\t\tp = &(*p)->rb_left;\n\t\telse if (key > mr->r_key)\n\t\t\tp = &(*p)->rb_right;\n\t\telse\n\t\t\treturn mr;\n\t}", "\tif (insert) {\n\t\trb_link_node(&insert->r_rb_node, parent, p);\n\t\trb_insert_color(&insert->r_rb_node, root);\n\t\trefcount_inc(&insert->r_refcount);\n\t}\n\treturn NULL;\n}", "/*\n * Destroy the transport-specific part of a MR.\n */\nstatic void rds_destroy_mr(struct rds_mr *mr)\n{\n\tstruct rds_sock *rs = mr->r_sock;\n\tvoid *trans_private = NULL;\n\tunsigned long flags;", "\trdsdebug(\"RDS: destroy mr key is %x refcnt %u\\n\",\n\t\t\tmr->r_key, refcount_read(&mr->r_refcount));", "\tif (test_and_set_bit(RDS_MR_DEAD, &mr->r_state))\n\t\treturn;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tif (!RB_EMPTY_NODE(&mr->r_rb_node))\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\ttrans_private = mr->r_trans_private;\n\tmr->r_trans_private = NULL;\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (trans_private)\n\t\tmr->r_trans->free_mr(trans_private, mr->r_invalidate);\n}", "void __rds_put_mr_final(struct rds_mr *mr)\n{\n\trds_destroy_mr(mr);\n\tkfree(mr);\n}", "/*\n * By the time this is called we can't have any more ioctls called on\n * the socket so we don't need to worry about racing with others.\n */\nvoid rds_rdma_drop_keys(struct rds_sock *rs)\n{\n\tstruct rds_mr *mr;\n\tstruct rb_node *node;\n\tunsigned long flags;", "\t/* Release any MRs associated with this socket */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\twhile ((node = rb_first(&rs->rs_rdma_keys))) {\n\t\tmr = rb_entry(node, struct rds_mr, r_rb_node);\n\t\tif (mr->r_trans == rs->rs_transport)\n\t\t\tmr->r_invalidate = 0;\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (rs->rs_transport && rs->rs_transport->flush_mrs)\n\t\trs->rs_transport->flush_mrs();\n}", "/*\n * Helper function to pin user pages.\n */\nstatic int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages,\n\t\t\tstruct page **pages, int write)\n{\n\tint ret;", "\tret = get_user_pages_fast(user_addr, nr_pages, write, pages);", "\tif (ret >= 0 && ret < nr_pages) {\n\t\twhile (ret--)\n\t\t\tput_page(pages[ret]);\n\t\tret = -EFAULT;\n\t}", "\treturn ret;\n}", "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;", "\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}", "\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}", "\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);", "\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;", "\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;", "\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;", "\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);", "\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);", "\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);", "\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);", "\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}", "\tmr->r_trans_private = trans_private;", "\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);", "\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing <R_Key, offset> and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;", "\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tBUG_ON(found && found != mr);", "\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}", "\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_args args;", "\tif (optlen != sizeof(struct rds_get_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_args)))\n\t\treturn -EFAULT;", "\treturn __rds_rdma_map(rs, &args, NULL, NULL);\n}", "int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_for_dest_args args;\n\tstruct rds_get_mr_args new_args;", "\tif (optlen != sizeof(struct rds_get_mr_for_dest_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_for_dest_args)))\n\t\treturn -EFAULT;", "\t/*\n\t * Initially, just behave like get_mr().\n\t * TODO: Implement get_mr as wrapper around this\n\t *\t and deprecate it.\n\t */\n\tnew_args.vec = args.vec;\n\tnew_args.cookie_addr = args.cookie_addr;\n\tnew_args.flags = args.flags;", "\treturn __rds_rdma_map(rs, &new_args, NULL, NULL);\n}", "/*\n * Free the MR indicated by the given R_Key\n */\nint rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_free_mr_args args;\n\tstruct rds_mr *mr;\n\tunsigned long flags;", "\tif (optlen != sizeof(struct rds_free_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_free_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_free_mr_args)))\n\t\treturn -EFAULT;", "\t/* Special case - a null cookie means flush all unused MRs */\n\tif (args.cookie == 0) {\n\t\tif (!rs->rs_transport || !rs->rs_transport->flush_mrs)\n\t\t\treturn -EINVAL;\n\t\trs->rs_transport->flush_mrs();\n\t\treturn 0;\n\t}", "\t/* Look up the MR given its R_key and remove it from the rbtree\n\t * so nobody else finds it.\n\t * This should also prevent races with rds_rdma_unuse.\n\t */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL);\n\tif (mr) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tif (args.flags & RDS_RDMA_INVALIDATE)\n\t\t\tmr->r_invalidate = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (!mr)\n\t\treturn -EINVAL;", "\t/*\n\t * call rds_destroy_mr() ourselves so that we're sure it's done by the time\n\t * we return. If we let rds_mr_put() do it it might not happen until\n\t * someone else drops their ref.\n\t */\n\trds_destroy_mr(mr);\n\trds_mr_put(mr);\n\treturn 0;\n}", "/*\n * This is called when we receive an extension header that\n * tells us this MR was used. It allows us to implement\n * use_once semantics\n */\nvoid rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force)\n{\n\tstruct rds_mr *mr;\n\tunsigned long flags;\n\tint zot_me = 0;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr) {\n\t\tpr_debug(\"rds: trying to unuse MR with unknown r_key %u!\\n\",\n\t\t\t r_key);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\treturn;\n\t}", "\tif (mr->r_use_once || force) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tzot_me = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\t/* May have to issue a dma_sync on this memory region.\n\t * Note we could avoid this if the operation was a RDMA READ,\n\t * but at this point we can't tell. */\n\tif (mr->r_trans->sync_mr)\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE);", "\t/* If the MR was marked as invalidate, this will\n\t * trigger an async flush. */\n\tif (zot_me) {\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t}\n}", "void rds_rdma_free_op(struct rm_rdma_op *ro)\n{\n\tunsigned int i;", "\tfor (i = 0; i < ro->op_nents; i++) {\n\t\tstruct page *page = sg_page(&ro->op_sg[i]);", "\t\t/* Mark page dirty if it was possibly modified, which\n\t\t * is the case for a RDMA_READ which copies from remote\n\t\t * to local memory */\n\t\tif (!ro->op_write) {\n\t\t\tWARN_ON(!page->mapping && irqs_disabled());\n\t\t\tset_page_dirty(page);\n\t\t}\n\t\tput_page(page);\n\t}", "\tkfree(ro->op_notifier);\n\tro->op_notifier = NULL;\n\tro->op_active = 0;\n}", "void rds_atomic_free_op(struct rm_atomic_op *ao)\n{\n\tstruct page *page = sg_page(ao->op_sg);", "\t/* Mark page dirty if it was possibly modified, which\n\t * is the case for a RDMA_READ which copies from remote\n\t * to local memory */\n\tset_page_dirty(page);\n\tput_page(page);", "\tkfree(ao->op_notifier);\n\tao->op_notifier = NULL;\n\tao->op_active = 0;\n}", "\n/*\n * Count the number of pages needed to describe an incoming iovec array.\n */\nstatic int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs)\n{\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < nr_iovecs; i++) {\n\t\tnr_pages = rds_pages_in_vec(&iov[i]);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages;\n}", "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;\n", "", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;", "\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages * sizeof(struct scatterlist);\n}", "/*\n * The application asks for a RDMA transfer.\n * Extract all arguments and set up the rdma_op\n */\nint rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tstruct rds_rdma_args *args;\n\tstruct rm_rdma_op *op = &rm->rdma;\n\tint nr_pages;\n\tunsigned int nr_bytes;\n\tstruct page **pages = NULL;\n\tstruct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack;\n\tint iov_size;\n\tunsigned int i, j;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args))\n\t || rm->rdma.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out_ret;\n\t}", "\tif (args->nr_local > UIO_MAXIOV) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out_ret;\n\t}", "\t/* Check whether to allocate the iovec area */\n\tiov_size = args->nr_local * sizeof(struct rds_iovec);\n\tif (args->nr_local > UIO_FASTIOV) {\n\t\tiovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL);\n\t\tif (!iovs) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out_ret;\n\t\t}\n\t}", "\tif (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_rdma_pages(iovs, args->nr_local);\n\tif (nr_pages < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\top->op_write = !!(args->flags & RDS_RDMA_READWRITE);\n\top->op_fence = !!(args->flags & RDS_RDMA_FENCE);\n\top->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\top->op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\top->op_active = 1;\n\top->op_recverr = rs->rs_recverr;\n\tWARN_ON(!nr_pages);\n\top->op_sg = rds_message_alloc_sgs(rm, nr_pages);\n\tif (!op->op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tif (op->op_notify || op->op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\top->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL);\n\t\tif (!op->op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\top->op_notifier->n_user_token = args->user_token;\n\t\top->op_notifier->n_status = RDS_RDMA_SUCCESS;", "\t\t/* Enable rmda notification on data operation for composite\n\t\t * rds messages and make sure notification is enabled only\n\t\t * for the data operation which follows it so that application\n\t\t * gets notified only after full message gets delivered.\n\t\t */\n\t\tif (rm->data.op_sg) {\n\t\t\trm->rdma.op_notify = 0;\n\t\t\trm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\t\t}\n\t}", "\t/* The cookie contains the R_Key of the remote memory region, and\n\t * optionally an offset into it. This is how we implement RDMA into\n\t * unaligned memory.\n\t * When setting up the RDMA, we need to add that offset to the\n\t * destination address (which is really an offset into the MR)\n\t * FIXME: We may want to move this into ib_rdma.c\n\t */\n\top->op_rkey = rds_rdma_cookie_key(args->cookie);\n\top->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie);", "\tnr_bytes = 0;", "\trdsdebug(\"RDS: rdma prepare nr_local %llu rva %llx rkey %x\\n\",\n\t (unsigned long long)args->nr_local,\n\t (unsigned long long)args->remote_vec.addr,\n\t op->op_rkey);", "\tfor (i = 0; i < args->nr_local; i++) {\n\t\tstruct rds_iovec *iov = &iovs[i];\n\t\t/* don't need to check, rds_rdma_pages() verified nr will be +nonzero */\n\t\tunsigned int nr = rds_pages_in_vec(iov);", "\t\trs->rs_user_addr = iov->addr;\n\t\trs->rs_user_bytes = iov->bytes;", "\t\t/* If it's a WRITE operation, we want to pin the pages for reading.\n\t\t * If it's a READ operation, we need to pin the pages for writing.\n\t\t */\n\t\tret = rds_pin_pages(iov->addr, nr, pages, !op->op_write);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t\telse\n\t\t\tret = 0;", "\t\trdsdebug(\"RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\\n\",\n\t\t\t nr_bytes, nr, iov->bytes, iov->addr);", "\t\tnr_bytes += iov->bytes;", "\t\tfor (j = 0; j < nr; j++) {\n\t\t\tunsigned int offset = iov->addr & ~PAGE_MASK;\n\t\t\tstruct scatterlist *sg;", "\t\t\tsg = &op->op_sg[op->op_nents + j];\n\t\t\tsg_set_page(sg, pages[j],\n\t\t\t\t\tmin_t(unsigned int, iov->bytes, PAGE_SIZE - offset),\n\t\t\t\t\toffset);", "\t\t\trdsdebug(\"RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\\n\",\n\t\t\t sg->offset, sg->length, iov->addr, iov->bytes);", "\t\t\tiov->addr += sg->length;\n\t\t\tiov->bytes -= sg->length;\n\t\t}", "\t\top->op_nents += nr;\n\t}", "\tif (nr_bytes > args->remote_vec.bytes) {\n\t\trdsdebug(\"RDS nr_bytes %u remote_bytes %u do not match\\n\",\n\t\t\t\tnr_bytes,\n\t\t\t\t(unsigned int) args->remote_vec.bytes);\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\top->op_bytes = nr_bytes;", "out:\n\tif (iovs != iovstack)\n\t\tsock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size);\n\tkfree(pages);\nout_ret:\n\tif (ret)\n\t\trds_rdma_free_op(op);\n\telse\n\t\trds_stats_inc(s_send_rdma);", "\treturn ret;\n}", "/*\n * The application wants us to pass an RDMA destination (aka MR)\n * to the remote\n */\nint rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tunsigned long flags;\n\tstruct rds_mr *mr;\n\tu32 r_key;\n\tint err = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\tmemcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie));", "\t/* We are reusing a previously mapped MR here. Most likely, the\n\t * application has written to the buffer, so we need to explicitly\n\t * flush those writes to RAM. Otherwise the HCA may not see them\n\t * when doing a DMA from that buffer.\n\t */\n\tr_key = rds_rdma_cookie_key(rm->m_rdma_cookie);", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr)\n\t\terr = -EINVAL;\t/* invalid r_key */\n\telse\n\t\trefcount_inc(&mr->r_refcount);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (mr) {\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE);\n\t\trm->rdma.op_rdma_mr = mr;\n\t}\n\treturn err;\n}", "/*\n * The application passes us an address range it wants to enable RDMA\n * to/from. We map the area, and save the <R_Key,offset> pair\n * in rm->m_rdma_cookie. This causes it to be sent along to the peer\n * in an extension header.\n */\nint rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\treturn __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr);\n}", "/*\n * Fill in rds_message for an atomic request.\n */\nint rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}", "\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}", "\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}", "\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;", "\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));", "\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}", "\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}", "\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);", "\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\tkfree(rm->atomic.op_notifier);", "\treturn ret;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [527], "buggy_code_start_loc": [527], "filenames": ["net/rds/rdma.c"], "fixing_code_end_loc": [531], "fixing_code_start_loc": [528], "message": "In the Linux kernel through 3.2, the rds_message_alloc_sgs() function does not validate a value that is used during DMA page allocation, leading to a heap-based out-of-bounds write (related to the rds_rdma_extra_size function in net/rds/rdma.c).", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "87B791D3-1C62-44B7-B4E4-E70E6F183462", "versionEndExcluding": "3.2.99", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "D999C96C-7B24-4418-9FEE-AF2D2539E28E", "versionEndExcluding": "3.16.54", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.3", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "56D29D8F-12F1-42E4-92EC-4DEC7214BA16", "versionEndExcluding": "3.18.92", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.17", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "F71F6650-13B4-486F-80AC-20D871806D44", "versionEndExcluding": "4.1.50", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.19", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "899C6EC3-5202-4A9A-9304-901FA4DECAFF", "versionEndExcluding": "4.4.112", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.2", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "0B51DE9C-D416-43D5-81C9-83F8958ADB2E", "versionEndExcluding": "4.9.77", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.5", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "CC51E40C-0FA7-41BD-ABDD-BA28D2B35761", "versionEndExcluding": "4.14.44", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.10", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Linux kernel through 3.2, the rds_message_alloc_sgs() function does not validate a value that is used during DMA page allocation, leading to a heap-based out-of-bounds write (related to the rds_rdma_extra_size function in net/rds/rdma.c)."}, {"lang": "es", "value": "En el kernel de Linux hasta la versi\u00f3n 3.2, la funci\u00f3n rds_message_alloc_sgs() no valida un valor empleado durante la asignaci\u00f3n de p\u00e1gina DMA, lo que conduce a una escritura fuera de l\u00edmites basada en memoria din\u00e1mica (heap), relacionado con la funci\u00f3n rds_rdma_extra_size en net/rds/rdma.c"}], "evaluatorComment": null, "id": "CVE-2018-5332", "lastModified": "2023-02-24T18:43:39.280", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2018-01-11T07:29:00.217", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c095508770aebf1b9218e77026e48345d719b17c"}, {"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/102507"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2018:0470"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?id=60daca9efbb3e4109ebc1f7069543e5573fc124e"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/torvalds/linux/commit/c095508770aebf1b9218e77026e48345d719b17c"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/05/msg00000.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-3/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3620-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3620-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3632-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2018/dsa-4187"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/c095508770aebf1b9218e77026e48345d719b17c"}, "type": "CWE-787"}
114
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007 Oracle. All rights reserved.\n *\n * This software is available to you under a choice of one of two\n * licenses. You may choose to be licensed under the terms of the GNU\n * General Public License (GPL) Version 2, available from the file\n * COPYING in the main directory of this source tree, or the\n * OpenIB.org BSD license below:\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * - Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * disclaimer.\n *\n * - Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n */\n#include <linux/pagemap.h>\n#include <linux/slab.h>\n#include <linux/rbtree.h>\n#include <linux/dma-mapping.h> /* for DMA_*_DEVICE */", "#include \"rds.h\"", "/*\n * XXX\n * - build with sparse\n * - should we detect duplicate keys on a socket? hmm.\n * - an rdma is an mlock, apply rlimit?\n */", "/*\n * get the number of pages by looking at the page indices that the start and\n * end addresses fall in.\n *\n * Returns 0 if the vec is invalid. It is invalid if the number of bytes\n * causes the address to wrap or overflows an unsigned int. This comes\n * from being stored in the 'length' member of 'struct scatterlist'.\n */\nstatic unsigned int rds_pages_in_vec(struct rds_iovec *vec)\n{\n\tif ((vec->addr + vec->bytes <= vec->addr) ||\n\t (vec->bytes > (u64)UINT_MAX))\n\t\treturn 0;", "\treturn ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) -\n\t\t(vec->addr >> PAGE_SHIFT);\n}", "static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key,\n\t\t\t\t struct rds_mr *insert)\n{\n\tstruct rb_node **p = &root->rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct rds_mr *mr;", "\twhile (*p) {\n\t\tparent = *p;\n\t\tmr = rb_entry(parent, struct rds_mr, r_rb_node);", "\t\tif (key < mr->r_key)\n\t\t\tp = &(*p)->rb_left;\n\t\telse if (key > mr->r_key)\n\t\t\tp = &(*p)->rb_right;\n\t\telse\n\t\t\treturn mr;\n\t}", "\tif (insert) {\n\t\trb_link_node(&insert->r_rb_node, parent, p);\n\t\trb_insert_color(&insert->r_rb_node, root);\n\t\trefcount_inc(&insert->r_refcount);\n\t}\n\treturn NULL;\n}", "/*\n * Destroy the transport-specific part of a MR.\n */\nstatic void rds_destroy_mr(struct rds_mr *mr)\n{\n\tstruct rds_sock *rs = mr->r_sock;\n\tvoid *trans_private = NULL;\n\tunsigned long flags;", "\trdsdebug(\"RDS: destroy mr key is %x refcnt %u\\n\",\n\t\t\tmr->r_key, refcount_read(&mr->r_refcount));", "\tif (test_and_set_bit(RDS_MR_DEAD, &mr->r_state))\n\t\treturn;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tif (!RB_EMPTY_NODE(&mr->r_rb_node))\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\ttrans_private = mr->r_trans_private;\n\tmr->r_trans_private = NULL;\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (trans_private)\n\t\tmr->r_trans->free_mr(trans_private, mr->r_invalidate);\n}", "void __rds_put_mr_final(struct rds_mr *mr)\n{\n\trds_destroy_mr(mr);\n\tkfree(mr);\n}", "/*\n * By the time this is called we can't have any more ioctls called on\n * the socket so we don't need to worry about racing with others.\n */\nvoid rds_rdma_drop_keys(struct rds_sock *rs)\n{\n\tstruct rds_mr *mr;\n\tstruct rb_node *node;\n\tunsigned long flags;", "\t/* Release any MRs associated with this socket */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\twhile ((node = rb_first(&rs->rs_rdma_keys))) {\n\t\tmr = rb_entry(node, struct rds_mr, r_rb_node);\n\t\tif (mr->r_trans == rs->rs_transport)\n\t\t\tmr->r_invalidate = 0;\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (rs->rs_transport && rs->rs_transport->flush_mrs)\n\t\trs->rs_transport->flush_mrs();\n}", "/*\n * Helper function to pin user pages.\n */\nstatic int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages,\n\t\t\tstruct page **pages, int write)\n{\n\tint ret;", "\tret = get_user_pages_fast(user_addr, nr_pages, write, pages);", "\tif (ret >= 0 && ret < nr_pages) {\n\t\twhile (ret--)\n\t\t\tput_page(pages[ret]);\n\t\tret = -EFAULT;\n\t}", "\treturn ret;\n}", "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;", "\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}", "\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}", "\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);", "\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;", "\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;", "\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;", "\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);", "\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);", "\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);", "\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);", "\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}", "\tmr->r_trans_private = trans_private;", "\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);", "\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing <R_Key, offset> and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;", "\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tBUG_ON(found && found != mr);", "\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}", "\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_args args;", "\tif (optlen != sizeof(struct rds_get_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_args)))\n\t\treturn -EFAULT;", "\treturn __rds_rdma_map(rs, &args, NULL, NULL);\n}", "int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_for_dest_args args;\n\tstruct rds_get_mr_args new_args;", "\tif (optlen != sizeof(struct rds_get_mr_for_dest_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_for_dest_args)))\n\t\treturn -EFAULT;", "\t/*\n\t * Initially, just behave like get_mr().\n\t * TODO: Implement get_mr as wrapper around this\n\t *\t and deprecate it.\n\t */\n\tnew_args.vec = args.vec;\n\tnew_args.cookie_addr = args.cookie_addr;\n\tnew_args.flags = args.flags;", "\treturn __rds_rdma_map(rs, &new_args, NULL, NULL);\n}", "/*\n * Free the MR indicated by the given R_Key\n */\nint rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_free_mr_args args;\n\tstruct rds_mr *mr;\n\tunsigned long flags;", "\tif (optlen != sizeof(struct rds_free_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_free_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_free_mr_args)))\n\t\treturn -EFAULT;", "\t/* Special case - a null cookie means flush all unused MRs */\n\tif (args.cookie == 0) {\n\t\tif (!rs->rs_transport || !rs->rs_transport->flush_mrs)\n\t\t\treturn -EINVAL;\n\t\trs->rs_transport->flush_mrs();\n\t\treturn 0;\n\t}", "\t/* Look up the MR given its R_key and remove it from the rbtree\n\t * so nobody else finds it.\n\t * This should also prevent races with rds_rdma_unuse.\n\t */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL);\n\tif (mr) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tif (args.flags & RDS_RDMA_INVALIDATE)\n\t\t\tmr->r_invalidate = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (!mr)\n\t\treturn -EINVAL;", "\t/*\n\t * call rds_destroy_mr() ourselves so that we're sure it's done by the time\n\t * we return. If we let rds_mr_put() do it it might not happen until\n\t * someone else drops their ref.\n\t */\n\trds_destroy_mr(mr);\n\trds_mr_put(mr);\n\treturn 0;\n}", "/*\n * This is called when we receive an extension header that\n * tells us this MR was used. It allows us to implement\n * use_once semantics\n */\nvoid rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force)\n{\n\tstruct rds_mr *mr;\n\tunsigned long flags;\n\tint zot_me = 0;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr) {\n\t\tpr_debug(\"rds: trying to unuse MR with unknown r_key %u!\\n\",\n\t\t\t r_key);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\treturn;\n\t}", "\tif (mr->r_use_once || force) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tzot_me = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\t/* May have to issue a dma_sync on this memory region.\n\t * Note we could avoid this if the operation was a RDMA READ,\n\t * but at this point we can't tell. */\n\tif (mr->r_trans->sync_mr)\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE);", "\t/* If the MR was marked as invalidate, this will\n\t * trigger an async flush. */\n\tif (zot_me) {\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t}\n}", "void rds_rdma_free_op(struct rm_rdma_op *ro)\n{\n\tunsigned int i;", "\tfor (i = 0; i < ro->op_nents; i++) {\n\t\tstruct page *page = sg_page(&ro->op_sg[i]);", "\t\t/* Mark page dirty if it was possibly modified, which\n\t\t * is the case for a RDMA_READ which copies from remote\n\t\t * to local memory */\n\t\tif (!ro->op_write) {\n\t\t\tWARN_ON(!page->mapping && irqs_disabled());\n\t\t\tset_page_dirty(page);\n\t\t}\n\t\tput_page(page);\n\t}", "\tkfree(ro->op_notifier);\n\tro->op_notifier = NULL;\n\tro->op_active = 0;\n}", "void rds_atomic_free_op(struct rm_atomic_op *ao)\n{\n\tstruct page *page = sg_page(ao->op_sg);", "\t/* Mark page dirty if it was possibly modified, which\n\t * is the case for a RDMA_READ which copies from remote\n\t * to local memory */\n\tset_page_dirty(page);\n\tput_page(page);", "\tkfree(ao->op_notifier);\n\tao->op_notifier = NULL;\n\tao->op_active = 0;\n}", "\n/*\n * Count the number of pages needed to describe an incoming iovec array.\n */\nstatic int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs)\n{\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < nr_iovecs; i++) {\n\t\tnr_pages = rds_pages_in_vec(&iov[i]);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages;\n}", "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;\n", "\tif (args->nr_local == 0)\n\t\treturn -EINVAL;\n", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;", "\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages * sizeof(struct scatterlist);\n}", "/*\n * The application asks for a RDMA transfer.\n * Extract all arguments and set up the rdma_op\n */\nint rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tstruct rds_rdma_args *args;\n\tstruct rm_rdma_op *op = &rm->rdma;\n\tint nr_pages;\n\tunsigned int nr_bytes;\n\tstruct page **pages = NULL;\n\tstruct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack;\n\tint iov_size;\n\tunsigned int i, j;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args))\n\t || rm->rdma.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out_ret;\n\t}", "\tif (args->nr_local > UIO_MAXIOV) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out_ret;\n\t}", "\t/* Check whether to allocate the iovec area */\n\tiov_size = args->nr_local * sizeof(struct rds_iovec);\n\tif (args->nr_local > UIO_FASTIOV) {\n\t\tiovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL);\n\t\tif (!iovs) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out_ret;\n\t\t}\n\t}", "\tif (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_rdma_pages(iovs, args->nr_local);\n\tif (nr_pages < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\top->op_write = !!(args->flags & RDS_RDMA_READWRITE);\n\top->op_fence = !!(args->flags & RDS_RDMA_FENCE);\n\top->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\top->op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\top->op_active = 1;\n\top->op_recverr = rs->rs_recverr;\n\tWARN_ON(!nr_pages);\n\top->op_sg = rds_message_alloc_sgs(rm, nr_pages);\n\tif (!op->op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tif (op->op_notify || op->op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\top->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL);\n\t\tif (!op->op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\top->op_notifier->n_user_token = args->user_token;\n\t\top->op_notifier->n_status = RDS_RDMA_SUCCESS;", "\t\t/* Enable rmda notification on data operation for composite\n\t\t * rds messages and make sure notification is enabled only\n\t\t * for the data operation which follows it so that application\n\t\t * gets notified only after full message gets delivered.\n\t\t */\n\t\tif (rm->data.op_sg) {\n\t\t\trm->rdma.op_notify = 0;\n\t\t\trm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\t\t}\n\t}", "\t/* The cookie contains the R_Key of the remote memory region, and\n\t * optionally an offset into it. This is how we implement RDMA into\n\t * unaligned memory.\n\t * When setting up the RDMA, we need to add that offset to the\n\t * destination address (which is really an offset into the MR)\n\t * FIXME: We may want to move this into ib_rdma.c\n\t */\n\top->op_rkey = rds_rdma_cookie_key(args->cookie);\n\top->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie);", "\tnr_bytes = 0;", "\trdsdebug(\"RDS: rdma prepare nr_local %llu rva %llx rkey %x\\n\",\n\t (unsigned long long)args->nr_local,\n\t (unsigned long long)args->remote_vec.addr,\n\t op->op_rkey);", "\tfor (i = 0; i < args->nr_local; i++) {\n\t\tstruct rds_iovec *iov = &iovs[i];\n\t\t/* don't need to check, rds_rdma_pages() verified nr will be +nonzero */\n\t\tunsigned int nr = rds_pages_in_vec(iov);", "\t\trs->rs_user_addr = iov->addr;\n\t\trs->rs_user_bytes = iov->bytes;", "\t\t/* If it's a WRITE operation, we want to pin the pages for reading.\n\t\t * If it's a READ operation, we need to pin the pages for writing.\n\t\t */\n\t\tret = rds_pin_pages(iov->addr, nr, pages, !op->op_write);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t\telse\n\t\t\tret = 0;", "\t\trdsdebug(\"RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\\n\",\n\t\t\t nr_bytes, nr, iov->bytes, iov->addr);", "\t\tnr_bytes += iov->bytes;", "\t\tfor (j = 0; j < nr; j++) {\n\t\t\tunsigned int offset = iov->addr & ~PAGE_MASK;\n\t\t\tstruct scatterlist *sg;", "\t\t\tsg = &op->op_sg[op->op_nents + j];\n\t\t\tsg_set_page(sg, pages[j],\n\t\t\t\t\tmin_t(unsigned int, iov->bytes, PAGE_SIZE - offset),\n\t\t\t\t\toffset);", "\t\t\trdsdebug(\"RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\\n\",\n\t\t\t sg->offset, sg->length, iov->addr, iov->bytes);", "\t\t\tiov->addr += sg->length;\n\t\t\tiov->bytes -= sg->length;\n\t\t}", "\t\top->op_nents += nr;\n\t}", "\tif (nr_bytes > args->remote_vec.bytes) {\n\t\trdsdebug(\"RDS nr_bytes %u remote_bytes %u do not match\\n\",\n\t\t\t\tnr_bytes,\n\t\t\t\t(unsigned int) args->remote_vec.bytes);\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\top->op_bytes = nr_bytes;", "out:\n\tif (iovs != iovstack)\n\t\tsock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size);\n\tkfree(pages);\nout_ret:\n\tif (ret)\n\t\trds_rdma_free_op(op);\n\telse\n\t\trds_stats_inc(s_send_rdma);", "\treturn ret;\n}", "/*\n * The application wants us to pass an RDMA destination (aka MR)\n * to the remote\n */\nint rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tunsigned long flags;\n\tstruct rds_mr *mr;\n\tu32 r_key;\n\tint err = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\tmemcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie));", "\t/* We are reusing a previously mapped MR here. Most likely, the\n\t * application has written to the buffer, so we need to explicitly\n\t * flush those writes to RAM. Otherwise the HCA may not see them\n\t * when doing a DMA from that buffer.\n\t */\n\tr_key = rds_rdma_cookie_key(rm->m_rdma_cookie);", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr)\n\t\terr = -EINVAL;\t/* invalid r_key */\n\telse\n\t\trefcount_inc(&mr->r_refcount);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (mr) {\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE);\n\t\trm->rdma.op_rdma_mr = mr;\n\t}\n\treturn err;\n}", "/*\n * The application passes us an address range it wants to enable RDMA\n * to/from. We map the area, and save the <R_Key,offset> pair\n * in rm->m_rdma_cookie. This causes it to be sent along to the peer\n * in an extension header.\n */\nint rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\treturn __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr);\n}", "/*\n * Fill in rds_message for an atomic request.\n */\nint rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}", "\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}", "\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}", "\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;", "\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));", "\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}", "\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}", "\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);", "\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\tkfree(rm->atomic.op_notifier);", "\treturn ret;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [527], "buggy_code_start_loc": [527], "filenames": ["net/rds/rdma.c"], "fixing_code_end_loc": [531], "fixing_code_start_loc": [528], "message": "In the Linux kernel through 3.2, the rds_message_alloc_sgs() function does not validate a value that is used during DMA page allocation, leading to a heap-based out-of-bounds write (related to the rds_rdma_extra_size function in net/rds/rdma.c).", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "87B791D3-1C62-44B7-B4E4-E70E6F183462", "versionEndExcluding": "3.2.99", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "D999C96C-7B24-4418-9FEE-AF2D2539E28E", "versionEndExcluding": "3.16.54", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.3", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "56D29D8F-12F1-42E4-92EC-4DEC7214BA16", "versionEndExcluding": "3.18.92", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.17", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "F71F6650-13B4-486F-80AC-20D871806D44", "versionEndExcluding": "4.1.50", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "3.19", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "899C6EC3-5202-4A9A-9304-901FA4DECAFF", "versionEndExcluding": "4.4.112", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.2", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "0B51DE9C-D416-43D5-81C9-83F8958ADB2E", "versionEndExcluding": "4.9.77", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.5", "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "CC51E40C-0FA7-41BD-ABDD-BA28D2B35761", "versionEndExcluding": "4.14.44", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "4.10", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the Linux kernel through 3.2, the rds_message_alloc_sgs() function does not validate a value that is used during DMA page allocation, leading to a heap-based out-of-bounds write (related to the rds_rdma_extra_size function in net/rds/rdma.c)."}, {"lang": "es", "value": "En el kernel de Linux hasta la versi\u00f3n 3.2, la funci\u00f3n rds_message_alloc_sgs() no valida un valor empleado durante la asignaci\u00f3n de p\u00e1gina DMA, lo que conduce a una escritura fuera de l\u00edmites basada en memoria din\u00e1mica (heap), relacionado con la funci\u00f3n rds_rdma_extra_size en net/rds/rdma.c"}], "evaluatorComment": null, "id": "CVE-2018-5332", "lastModified": "2023-02-24T18:43:39.280", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2018-01-11T07:29:00.217", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c095508770aebf1b9218e77026e48345d719b17c"}, {"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/102507"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2018:0470"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/commit/?id=60daca9efbb3e4109ebc1f7069543e5573fc124e"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/torvalds/linux/commit/c095508770aebf1b9218e77026e48345d719b17c"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/05/msg00000.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3617-3/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3620-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3620-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3632-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2018/dsa-4187"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/c095508770aebf1b9218e77026e48345d719b17c"}, "type": "CWE-787"}
114
Determine whether the {function_name} code is vulnerable or not.
[ "<html>\n\t<head>\n\t\t<?php include('parts/head.html.part'); ?>\n\t</head>\n\t<body class=\"vflex\">\n\t\t<div class=\"header hflex\">\n\t\t\t<?php include('parts/header.html.part'); ?>\n\t\t</div>\n\t\t<div class=\"center hflex\">\n\t\t\t<div class=\"page\">", "\t\t\t\t<?php include('pages/' . array_merge(array('p'=>'home'), $_GET)['p'] . '.html.part'); ?>", "\t\t\t</div>\n\t\t\t<div class=\"sidebar\">\n\t\t\t\t<?php include('parts/sidebar.html.part'); ?>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"footer hflex\">\n\t\t\t<?php include('parts/footer.html.part'); ?>\n\t\t</div>\n\t</body>\n</html>" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [12], "buggy_code_start_loc": [11], "filenames": ["index.php"], "fixing_code_end_loc": [23], "fixing_code_start_loc": [11], "message": "A vulnerability, which was classified as critical, was found in soshtolsus wing-tight. This affects an unknown part of the file index.php. The manipulation of the argument p leads to file inclusion. It is possible to initiate the attack remotely. Upgrading to version 1.0.0 is able to address this issue. The name of the patch is 567bc33e6ed82b0d0179c9add707ac2b257aeaf2. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-217515.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wing-tight_project:wing-tight:*:*:*:*:*:*:*:*", "matchCriteriaId": "84A09019-DFE8-4237-A362-E2522307454F", "versionEndExcluding": "1.0.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as critical, was found in soshtolsus wing-tight. This affects an unknown part of the file index.php. The manipulation of the argument p leads to file inclusion. It is possible to initiate the attack remotely. Upgrading to version 1.0.0 is able to address this issue. The name of the patch is 567bc33e6ed82b0d0179c9add707ac2b257aeaf2. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-217515."}], "evaluatorComment": null, "id": "CVE-2014-125044", "lastModified": "2023-01-12T02:47:06.567", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-05T20:15:18.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/soshtolsus/wing-tight/commit/567bc33e6ed82b0d0179c9add707ac2b257aeaf2"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/soshtolsus/wing-tight/releases/tag/1.0.0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217515"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217515"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/soshtolsus/wing-tight/commit/567bc33e6ed82b0d0179c9add707ac2b257aeaf2"}, "type": "CWE-610"}
115
Determine whether the {function_name} code is vulnerable or not.
[ "<html>\n\t<head>\n\t\t<?php include('parts/head.html.part'); ?>\n\t</head>\n\t<body class=\"vflex\">\n\t\t<div class=\"header hflex\">\n\t\t\t<?php include('parts/header.html.part'); ?>\n\t\t</div>\n\t\t<div class=\"center hflex\">\n\t\t\t<div class=\"page\">", "\t\t\t\t<?php\n\t\t\t\t\t$page_spec = array_merge(array('p'=>'home'), $_GET)['p'];\n\t\t\t\t\t\n\t\t\t\t\tif (strpos($page_spec, '/') === false)\n\t\t\t\t\t{\n\t\t\t\t\t\tinclude(\"{$_SERVER['DOCUMENT_ROOT']}/pages/$page_spec.html.part\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\techo 'no one here but us chickens';\n\t\t\t\t\t}\n\t\t\t\t?>", "\t\t\t</div>\n\t\t\t<div class=\"sidebar\">\n\t\t\t\t<?php include('parts/sidebar.html.part'); ?>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"footer hflex\">\n\t\t\t<?php include('parts/footer.html.part'); ?>\n\t\t</div>\n\t</body>\n</html>" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [12], "buggy_code_start_loc": [11], "filenames": ["index.php"], "fixing_code_end_loc": [23], "fixing_code_start_loc": [11], "message": "A vulnerability, which was classified as critical, was found in soshtolsus wing-tight. This affects an unknown part of the file index.php. The manipulation of the argument p leads to file inclusion. It is possible to initiate the attack remotely. Upgrading to version 1.0.0 is able to address this issue. The name of the patch is 567bc33e6ed82b0d0179c9add707ac2b257aeaf2. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-217515.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wing-tight_project:wing-tight:*:*:*:*:*:*:*:*", "matchCriteriaId": "84A09019-DFE8-4237-A362-E2522307454F", "versionEndExcluding": "1.0.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability, which was classified as critical, was found in soshtolsus wing-tight. This affects an unknown part of the file index.php. The manipulation of the argument p leads to file inclusion. It is possible to initiate the attack remotely. Upgrading to version 1.0.0 is able to address this issue. The name of the patch is 567bc33e6ed82b0d0179c9add707ac2b257aeaf2. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-217515."}], "evaluatorComment": null, "id": "CVE-2014-125044", "lastModified": "2023-01-12T02:47:06.567", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-05T20:15:18.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/soshtolsus/wing-tight/commit/567bc33e6ed82b0d0179c9add707ac2b257aeaf2"}, {"source": "cna@vuldb.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/soshtolsus/wing-tight/releases/tag/1.0.0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217515"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.217515"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-610"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-73"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/soshtolsus/wing-tight/commit/567bc33e6ed82b0d0179c9add707ac2b257aeaf2"}, "type": "CWE-610"}
115
Determine whether the {function_name} code is vulnerable or not.
[ "<?xml version=\"1.1\" encoding=\"UTF-8\"?>", "<!--\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software 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 GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n-->", "<xwikidoc version=\"1.1\">\n <web>IconThemesCode</web>\n <name>IconPickerMacro</name>\n <language/>\n <defaultLanguage/>\n <translation>0</translation>\n <creator>xwiki:XWiki.Admin</creator>\n <parent>IconThemes.WebHome</parent>\n <author>xwiki:XWiki.Admin</author>\n <contentAuthor>xwiki:XWiki.Admin</contentAuthor>\n <version>1.1</version>\n <title>Icon Picker Macro</title>\n <comment/>\n <minorEdit>false</minorEdit>\n <syntaxId>xwiki/2.1</syntaxId>\n <hidden>true</hidden>\n <content>= Usage =\n{{code}}\n{{iconPicker id=\"\" class=\"\" prefix=\"\" /}}\n{{/code}}", "**Where:**\n|=id (optional)|DOM id of the input field where the picker will apply\n|=class (optional)|CSS class of inputs where the picker will apply\n|=prefix (optional)|Prefix to add before the name of the icon in the input field (default: \"{{{image:icon:}}}\")\n== Live example ==\n{{code}}\n{{html}}\n &lt;p&gt;Field 1: &lt;input type=\"text\" id=\"myPicker\" /&gt;&lt;/p&gt;\n &lt;p&gt;Field 2: &lt;input type=\"text\" class=\"fieldWithPicker\" /&gt;&lt;/p&gt;\n{{/html}}", "{{iconPicker id=\"myPicker\" class=\"fieldWithPicker\" prefix=\"icon:\" /}}\n{{/code}}\n== Play with it ==\n{{html}}\n &lt;p&gt;Field 1: &lt;input type=\"text\" id=\"myPicker\" /&gt;&lt;/p&gt;\n &lt;p&gt;Field 2: &lt;input type=\"text\" class=\"fieldWithPicker\" /&gt;&lt;/p&gt;\n{{/html}}", "{{iconPicker id=\"myPicker\" class=\"fieldWithPicker\" prefix=\"icon:\" /}}</content>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>0</number>\n <className>XWiki.WikiMacroClass</className>\n <guid>a5daaf5a-bdf5-4a63-b0de-db25061f5874</guid>\n <class>\n <name>XWiki.WikiMacroClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <code>\n <disabled>0</disabled>\n <name>code</name>\n <number>9</number>\n <prettyName>Macro code</prettyName>\n <rows>20</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </code>\n <contentDescription>\n <disabled>0</disabled>\n <name>contentDescription</name>\n <number>8</number>\n <prettyName>Content description (Not applicable for \"No content\" type)</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </contentDescription>\n <contentType>\n <cache>0</cache>\n <disabled>0</disabled>\n <displayType>select</displayType>\n <multiSelect>0</multiSelect>\n <name>contentType</name>\n <number>7</number>\n <prettyName>Macro content type</prettyName>\n <relationalStorage>0</relationalStorage>\n <separator>|</separator>\n <separators>|</separators>\n <size>1</size>\n <unmodifiable>0</unmodifiable>\n <values>Optional|Mandatory|No content</values>\n <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>\n </contentType>\n <defaultCategory>\n <disabled>0</disabled>\n <name>defaultCategory</name>\n <number>4</number>\n <prettyName>Default category</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultCategory>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>3</number>\n <prettyName>Macro description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <id>\n <disabled>0</disabled>\n <name>id</name>\n <number>1</number>\n <prettyName>Macro id</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </id>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>2</number>\n <prettyName>Macro name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n <supportsInlineMode>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>supportsInlineMode</name>\n <number>5</number>\n <prettyName>Supports inline mode</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </supportsInlineMode>\n <visibility>\n <cache>0</cache>\n <disabled>0</disabled>\n <displayType>select</displayType>\n <multiSelect>0</multiSelect>\n <name>visibility</name>\n <number>6</number>\n <prettyName>Macro visibility</prettyName>\n <relationalStorage>0</relationalStorage>\n <separator>|</separator>\n <separators>|</separators>\n <size>1</size>\n <unmodifiable>0</unmodifiable>\n <values>Current User|Current Wiki|Global</values>\n <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>\n </visibility>\n </class>\n <property>\n <code>{{velocity output=\"false\"}}\n $xwiki.ssx.use('IconThemesCode.IconPicker')\n ## The icons themes may need some SSX, so we ask for a rendering of an icon of each icon theme, to be able to display\n ## all icon themes in the picker\n ## ToDo: since it is a bit hacky, a better system would be to dynamically load the needed SSX on demand\n #foreach($iconSetName in $services.icon.iconSetNames)\n $services.icon.render('wiki', $iconSetName)\n #end\n{{/velocity}}", "{{velocity}}\n{{html clean=\"false\"}}\n&lt;script&gt;\n require.config({\n paths: {\n 'xwiki-icon-picker': '$xwiki.getURL($services.model.createDocumentReference('', 'IconThemesCode', 'IconPicker'), 'jsx', \"minify=$!{escapetool.url($request.minify)}\")'\n }\n });\n require(['jquery', 'xwiki-icon-picker'], function($) {\n var options = {};\n #if($xcontext.macro.params.parameterNames.contains('prefix'))\n options['prefix'] = '$escapetool.javascript($xcontext.macro.params.prefix)';\n #end\n #if(\"$!xcontext.macro.params.id\" != '')", " $('#${xcontext.macro.params.id}').xwikiIconPicker(options);", " #end\n #if(\"$!xcontext.macro.params.get('class')\" != '')", " $('.${xcontext.macro.params.get('class')}').xwikiIconPicker(options);", " #end\n });\n&lt;/script&gt;\n{{/html}}\n{{/velocity}}</code>\n </property>\n <property>\n <contentDescription/>\n </property>\n <property>\n <contentType>No content</contentType>\n </property>\n <property>\n <defaultCategory>Development</defaultCategory>\n </property>\n <property>\n <description>Select an icon within the XWiki icon set.</description>\n </property>\n <property>\n <id>iconPicker</id>\n </property>\n <property>\n <name>Icon Picker</name>\n </property>\n <property>\n <supportsInlineMode>1</supportsInlineMode>\n </property>\n <property>\n <visibility>Current Wiki</visibility>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>0</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>bff4d631-8c3a-47fd-b54a-a542874bb81e</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>DOM id of the input field where the picker will apply</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>id</name>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>1</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>f9169e0d-a47c-4598-b0d7-4211940d1886</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>CSS class of inputs where the picker will apply</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>class</name>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>2</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>3a99d1ba-b108-45c6-a828-e76902f25783</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>Prefix to add before the name of the icon in the input field (default: \"image:icon:\")</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>prefix</name>\n </property>\n </object>\n</xwikidoc>" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [207], "buggy_code_start_loc": [203], "filenames": ["xwiki-platform-core/xwiki-platform-icon/xwiki-platform-icon-ui/src/main/resources/IconThemesCode/IconPickerMacro.xml"], "fixing_code_end_loc": [207], "fixing_code_start_loc": [203], "message": "xwiki-platform-icon-ui is vulnerable to Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'). Any user with view rights on commonly accessible documents including the icon picker macro can execute arbitrary Groovy, Python or Velocity code in XWiki due to improper neutralization of the macro parameters of the icon picker macro. The problem has been patched in XWiki 13.10.7, 14.5 and 14.4.2. Workarounds: The [patch](https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01) can be manually applied by editing `IconThemesCode.IconPickerMacro` in the object editor. The whole document can also be replaced by the current version by importing the document from the XAR archive of a fixed version as the only changes to the document have been security fixes and small formatting changes.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2983665-C5BF-4D43-983A-585BA30399E7", "versionEndExcluding": "13.10.7", "versionEndIncluding": null, "versionStartExcluding": "6.4", "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "B5DF0A47-B3DD-4A49-BA56-35374D029F02", "versionEndExcluding": "14.4.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:6.4:milestone2:*:*:*:*:*:*", "matchCriteriaId": "2ED3CF77-5A0B-4A1C-9F83-B5851D415D3E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:6.4:milestone3:*:*:*:*:*:*", "matchCriteriaId": "34004E8E-213E-4D7F-A6BF-953A5A5C3CA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:14.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "C9646DA8-7C5A-458E-975C-A67099D43047", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:14.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "CDAB9E27-2E41-44EA-BBCB-8015B22272B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "xwiki-platform-icon-ui is vulnerable to Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'). Any user with view rights on commonly accessible documents including the icon picker macro can execute arbitrary Groovy, Python or Velocity code in XWiki due to improper neutralization of the macro parameters of the icon picker macro. The problem has been patched in XWiki 13.10.7, 14.5 and 14.4.2. Workarounds: The [patch](https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01) can be manually applied by editing `IconThemesCode.IconPickerMacro` in the object editor. The whole document can also be replaced by the current version by importing the document from the XAR archive of a fixed version as the only changes to the document have been security fixes and small formatting changes."}], "evaluatorComment": null, "id": "CVE-2022-41931", "lastModified": "2022-11-30T17:00:37.137", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.9, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.1, "impactScore": 6.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-23T20:15:10.023", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-5j7g-cf6r-g2h7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-19805"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-95"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01"}, "type": "CWE-95"}
116
Determine whether the {function_name} code is vulnerable or not.
[ "<?xml version=\"1.1\" encoding=\"UTF-8\"?>", "<!--\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * This software 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 GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n-->", "<xwikidoc version=\"1.1\">\n <web>IconThemesCode</web>\n <name>IconPickerMacro</name>\n <language/>\n <defaultLanguage/>\n <translation>0</translation>\n <creator>xwiki:XWiki.Admin</creator>\n <parent>IconThemes.WebHome</parent>\n <author>xwiki:XWiki.Admin</author>\n <contentAuthor>xwiki:XWiki.Admin</contentAuthor>\n <version>1.1</version>\n <title>Icon Picker Macro</title>\n <comment/>\n <minorEdit>false</minorEdit>\n <syntaxId>xwiki/2.1</syntaxId>\n <hidden>true</hidden>\n <content>= Usage =\n{{code}}\n{{iconPicker id=\"\" class=\"\" prefix=\"\" /}}\n{{/code}}", "**Where:**\n|=id (optional)|DOM id of the input field where the picker will apply\n|=class (optional)|CSS class of inputs where the picker will apply\n|=prefix (optional)|Prefix to add before the name of the icon in the input field (default: \"{{{image:icon:}}}\")\n== Live example ==\n{{code}}\n{{html}}\n &lt;p&gt;Field 1: &lt;input type=\"text\" id=\"myPicker\" /&gt;&lt;/p&gt;\n &lt;p&gt;Field 2: &lt;input type=\"text\" class=\"fieldWithPicker\" /&gt;&lt;/p&gt;\n{{/html}}", "{{iconPicker id=\"myPicker\" class=\"fieldWithPicker\" prefix=\"icon:\" /}}\n{{/code}}\n== Play with it ==\n{{html}}\n &lt;p&gt;Field 1: &lt;input type=\"text\" id=\"myPicker\" /&gt;&lt;/p&gt;\n &lt;p&gt;Field 2: &lt;input type=\"text\" class=\"fieldWithPicker\" /&gt;&lt;/p&gt;\n{{/html}}", "{{iconPicker id=\"myPicker\" class=\"fieldWithPicker\" prefix=\"icon:\" /}}</content>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>0</number>\n <className>XWiki.WikiMacroClass</className>\n <guid>a5daaf5a-bdf5-4a63-b0de-db25061f5874</guid>\n <class>\n <name>XWiki.WikiMacroClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <code>\n <disabled>0</disabled>\n <name>code</name>\n <number>9</number>\n <prettyName>Macro code</prettyName>\n <rows>20</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </code>\n <contentDescription>\n <disabled>0</disabled>\n <name>contentDescription</name>\n <number>8</number>\n <prettyName>Content description (Not applicable for \"No content\" type)</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </contentDescription>\n <contentType>\n <cache>0</cache>\n <disabled>0</disabled>\n <displayType>select</displayType>\n <multiSelect>0</multiSelect>\n <name>contentType</name>\n <number>7</number>\n <prettyName>Macro content type</prettyName>\n <relationalStorage>0</relationalStorage>\n <separator>|</separator>\n <separators>|</separators>\n <size>1</size>\n <unmodifiable>0</unmodifiable>\n <values>Optional|Mandatory|No content</values>\n <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>\n </contentType>\n <defaultCategory>\n <disabled>0</disabled>\n <name>defaultCategory</name>\n <number>4</number>\n <prettyName>Default category</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultCategory>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>3</number>\n <prettyName>Macro description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <id>\n <disabled>0</disabled>\n <name>id</name>\n <number>1</number>\n <prettyName>Macro id</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </id>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>2</number>\n <prettyName>Macro name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n <supportsInlineMode>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>supportsInlineMode</name>\n <number>5</number>\n <prettyName>Supports inline mode</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </supportsInlineMode>\n <visibility>\n <cache>0</cache>\n <disabled>0</disabled>\n <displayType>select</displayType>\n <multiSelect>0</multiSelect>\n <name>visibility</name>\n <number>6</number>\n <prettyName>Macro visibility</prettyName>\n <relationalStorage>0</relationalStorage>\n <separator>|</separator>\n <separators>|</separators>\n <size>1</size>\n <unmodifiable>0</unmodifiable>\n <values>Current User|Current Wiki|Global</values>\n <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>\n </visibility>\n </class>\n <property>\n <code>{{velocity output=\"false\"}}\n $xwiki.ssx.use('IconThemesCode.IconPicker')\n ## The icons themes may need some SSX, so we ask for a rendering of an icon of each icon theme, to be able to display\n ## all icon themes in the picker\n ## ToDo: since it is a bit hacky, a better system would be to dynamically load the needed SSX on demand\n #foreach($iconSetName in $services.icon.iconSetNames)\n $services.icon.render('wiki', $iconSetName)\n #end\n{{/velocity}}", "{{velocity}}\n{{html clean=\"false\"}}\n&lt;script&gt;\n require.config({\n paths: {\n 'xwiki-icon-picker': '$xwiki.getURL($services.model.createDocumentReference('', 'IconThemesCode', 'IconPicker'), 'jsx', \"minify=$!{escapetool.url($request.minify)}\")'\n }\n });\n require(['jquery', 'xwiki-icon-picker'], function($) {\n var options = {};\n #if($xcontext.macro.params.parameterNames.contains('prefix'))\n options['prefix'] = '$escapetool.javascript($xcontext.macro.params.prefix)';\n #end\n #if(\"$!xcontext.macro.params.id\" != '')", " $('#${escapetool.javascript(${xcontext.macro.params.id})}').xwikiIconPicker(options);", " #end\n #if(\"$!xcontext.macro.params.get('class')\" != '')", " $('.${escapetool.javascript(${xcontext.macro.params.get('class')})}').xwikiIconPicker(options);", " #end\n });\n&lt;/script&gt;\n{{/html}}\n{{/velocity}}</code>\n </property>\n <property>\n <contentDescription/>\n </property>\n <property>\n <contentType>No content</contentType>\n </property>\n <property>\n <defaultCategory>Development</defaultCategory>\n </property>\n <property>\n <description>Select an icon within the XWiki icon set.</description>\n </property>\n <property>\n <id>iconPicker</id>\n </property>\n <property>\n <name>Icon Picker</name>\n </property>\n <property>\n <supportsInlineMode>1</supportsInlineMode>\n </property>\n <property>\n <visibility>Current Wiki</visibility>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>0</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>bff4d631-8c3a-47fd-b54a-a542874bb81e</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>DOM id of the input field where the picker will apply</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>id</name>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>1</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>f9169e0d-a47c-4598-b0d7-4211940d1886</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>CSS class of inputs where the picker will apply</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>class</name>\n </property>\n </object>\n <object>\n <name>IconThemesCode.IconPickerMacro</name>\n <number>2</number>\n <className>XWiki.WikiMacroParameterClass</className>\n <guid>3a99d1ba-b108-45c6-a828-e76902f25783</guid>\n <class>\n <name>XWiki.WikiMacroParameterClass</name>\n <customClass/>\n <customMapping/>\n <defaultViewSheet/>\n <defaultEditSheet/>\n <defaultWeb/>\n <nameField/>\n <validationScript/>\n <defaultValue>\n <disabled>0</disabled>\n <name>defaultValue</name>\n <number>4</number>\n <prettyName>Parameter default value</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </defaultValue>\n <description>\n <disabled>0</disabled>\n <name>description</name>\n <number>2</number>\n <prettyName>Parameter description</prettyName>\n <rows>5</rows>\n <size>40</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>\n </description>\n <mandatory>\n <disabled>0</disabled>\n <displayFormType>select</displayFormType>\n <displayType>yesno</displayType>\n <name>mandatory</name>\n <number>3</number>\n <prettyName>Parameter mandatory</prettyName>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>\n </mandatory>\n <name>\n <disabled>0</disabled>\n <name>name</name>\n <number>1</number>\n <prettyName>Parameter name</prettyName>\n <size>30</size>\n <unmodifiable>0</unmodifiable>\n <classType>com.xpn.xwiki.objects.classes.StringClass</classType>\n </name>\n </class>\n <property>\n <defaultValue/>\n </property>\n <property>\n <description>Prefix to add before the name of the icon in the input field (default: \"image:icon:\")</description>\n </property>\n <property>\n <mandatory>0</mandatory>\n </property>\n <property>\n <name>prefix</name>\n </property>\n </object>\n</xwikidoc>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [207], "buggy_code_start_loc": [203], "filenames": ["xwiki-platform-core/xwiki-platform-icon/xwiki-platform-icon-ui/src/main/resources/IconThemesCode/IconPickerMacro.xml"], "fixing_code_end_loc": [207], "fixing_code_start_loc": [203], "message": "xwiki-platform-icon-ui is vulnerable to Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'). Any user with view rights on commonly accessible documents including the icon picker macro can execute arbitrary Groovy, Python or Velocity code in XWiki due to improper neutralization of the macro parameters of the icon picker macro. The problem has been patched in XWiki 13.10.7, 14.5 and 14.4.2. Workarounds: The [patch](https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01) can be manually applied by editing `IconThemesCode.IconPickerMacro` in the object editor. The whole document can also be replaced by the current version by importing the document from the XAR archive of a fixed version as the only changes to the document have been security fixes and small formatting changes.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2983665-C5BF-4D43-983A-585BA30399E7", "versionEndExcluding": "13.10.7", "versionEndIncluding": null, "versionStartExcluding": "6.4", "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "B5DF0A47-B3DD-4A49-BA56-35374D029F02", "versionEndExcluding": "14.4.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "14.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:6.4:milestone2:*:*:*:*:*:*", "matchCriteriaId": "2ED3CF77-5A0B-4A1C-9F83-B5851D415D3E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:6.4:milestone3:*:*:*:*:*:*", "matchCriteriaId": "34004E8E-213E-4D7F-A6BF-953A5A5C3CA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:14.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "C9646DA8-7C5A-458E-975C-A67099D43047", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:14.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "CDAB9E27-2E41-44EA-BBCB-8015B22272B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "xwiki-platform-icon-ui is vulnerable to Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'). Any user with view rights on commonly accessible documents including the icon picker macro can execute arbitrary Groovy, Python or Velocity code in XWiki due to improper neutralization of the macro parameters of the icon picker macro. The problem has been patched in XWiki 13.10.7, 14.5 and 14.4.2. Workarounds: The [patch](https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01) can be manually applied by editing `IconThemesCode.IconPickerMacro` in the object editor. The whole document can also be replaced by the current version by importing the document from the XAR archive of a fixed version as the only changes to the document have been security fixes and small formatting changes."}], "evaluatorComment": null, "id": "CVE-2022-41931", "lastModified": "2022-11-30T17:00:37.137", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.9, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.1, "impactScore": 6.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-11-23T20:15:10.023", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-5j7g-cf6r-g2h7"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-19805"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-95"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/47eb8a5fba550f477944eb6da8ca91b87eaf1d01"}, "type": "CWE-95"}
116
Determine whether the {function_name} code is vulnerable or not.
[ "// SPDX-License-Identifier: GPL-2.0-only\n/*\n * Xen event channels\n *\n * Xen models interrupts with abstract event channels. Because each\n * domain gets 1024 event channels, but NR_IRQ is not that large, we\n * must dynamically map irqs<->event channels. The event channels\n * interface with the rest of the kernel by defining a xen interrupt\n * chip. When an event is received, it is mapped to an irq and sent\n * through the normal interrupt processing path.\n *\n * There are four kinds of events which can be mapped to an event\n * channel:\n *\n * 1. Inter-domain notifications. This includes all the virtual\n * device events, since they're driven by front-ends in another domain\n * (typically dom0).\n * 2. VIRQs, typically used for timers. These are per-cpu events.\n * 3. IPIs.\n * 4. PIRQs - Hardware interrupts.\n *\n * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007\n */", "#define pr_fmt(fmt) \"xen:\" KBUILD_MODNAME \": \" fmt", "#include <linux/linkage.h>\n#include <linux/interrupt.h>\n#include <linux/irq.h>\n#include <linux/moduleparam.h>\n#include <linux/string.h>\n#include <linux/memblock.h>\n#include <linux/slab.h>\n#include <linux/irqnr.h>\n#include <linux/pci.h>", "", "\n#ifdef CONFIG_X86\n#include <asm/desc.h>\n#include <asm/ptrace.h>\n#include <asm/idtentry.h>\n#include <asm/irq.h>\n#include <asm/io_apic.h>\n#include <asm/i8259.h>\n#include <asm/xen/pci.h>\n#endif\n#include <asm/sync_bitops.h>\n#include <asm/xen/hypercall.h>\n#include <asm/xen/hypervisor.h>\n#include <xen/page.h>", "#include <xen/xen.h>\n#include <xen/hvm.h>\n#include <xen/xen-ops.h>\n#include <xen/events.h>\n#include <xen/interface/xen.h>\n#include <xen/interface/event_channel.h>\n#include <xen/interface/hvm/hvm_op.h>\n#include <xen/interface/hvm/params.h>\n#include <xen/interface/physdev.h>\n#include <xen/interface/sched.h>\n#include <xen/interface/vcpu.h>\n#include <asm/hw_irq.h>", "#include \"events_internal.h\"", "const struct evtchn_ops *evtchn_ops;", "/*\n * This lock protects updates to the following mapping and reference-count\n * arrays. The lock does not need to be acquired to read the mapping tables.\n */\nstatic DEFINE_MUTEX(irq_mapping_update_lock);\n", "", "static LIST_HEAD(xen_irq_list_head);", "/* IRQ <-> VIRQ mapping. */\nstatic DEFINE_PER_CPU(int [NR_VIRQS], virq_to_irq) = {[0 ... NR_VIRQS-1] = -1};", "/* IRQ <-> IPI mapping */\nstatic DEFINE_PER_CPU(int [XEN_NR_IPIS], ipi_to_irq) = {[0 ... XEN_NR_IPIS-1] = -1};", "int **evtchn_to_irq;\n#ifdef CONFIG_X86\nstatic unsigned long *pirq_eoi_map;\n#endif\nstatic bool (*pirq_needs_eoi)(unsigned irq);", "#define EVTCHN_ROW(e) (e / (PAGE_SIZE/sizeof(**evtchn_to_irq)))\n#define EVTCHN_COL(e) (e % (PAGE_SIZE/sizeof(**evtchn_to_irq)))\n#define EVTCHN_PER_ROW (PAGE_SIZE / sizeof(**evtchn_to_irq))", "/* Xen will never allocate port zero for any purpose. */\n#define VALID_EVTCHN(chn)\t((chn) != 0)", "static struct irq_info *legacy_info_ptrs[NR_IRQS_LEGACY];", "static struct irq_chip xen_dynamic_chip;\nstatic struct irq_chip xen_percpu_chip;\nstatic struct irq_chip xen_pirq_chip;\nstatic void enable_dynirq(struct irq_data *data);\nstatic void disable_dynirq(struct irq_data *data);", "static void clear_evtchn_to_irq_row(unsigned row)\n{\n\tunsigned col;", "\tfor (col = 0; col < EVTCHN_PER_ROW; col++)", "\t\tevtchn_to_irq[row][col] = -1;", "}", "static void clear_evtchn_to_irq_all(void)\n{\n\tunsigned row;", "\tfor (row = 0; row < EVTCHN_ROW(xen_evtchn_max_channels()); row++) {\n\t\tif (evtchn_to_irq[row] == NULL)\n\t\t\tcontinue;\n\t\tclear_evtchn_to_irq_row(row);\n\t}\n}", "static int set_evtchn_to_irq(evtchn_port_t evtchn, unsigned int irq)\n{\n\tunsigned row;\n\tunsigned col;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -EINVAL;", "\trow = EVTCHN_ROW(evtchn);\n\tcol = EVTCHN_COL(evtchn);", "\tif (evtchn_to_irq[row] == NULL) {\n\t\t/* Unallocated irq entries return -1 anyway */\n\t\tif (irq == -1)\n\t\t\treturn 0;", "\t\tevtchn_to_irq[row] = (int *)get_zeroed_page(GFP_KERNEL);\n\t\tif (evtchn_to_irq[row] == NULL)\n\t\t\treturn -ENOMEM;", "\t\tclear_evtchn_to_irq_row(row);\n\t}\n", "\tevtchn_to_irq[row][col] = irq;", "\treturn 0;\n}", "int get_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -1;\n\tif (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL)\n\t\treturn -1;", "\treturn evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)];", "}", "/* Get info for IRQ */\nstruct irq_info *info_for_irq(unsigned irq)\n{\n\tif (irq < nr_legacy_irqs())\n\t\treturn legacy_info_ptrs[irq];\n\telse\n\t\treturn irq_get_chip_data(irq);\n}", "static void set_info_for_irq(unsigned int irq, struct irq_info *info)\n{\n\tif (irq < nr_legacy_irqs())\n\t\tlegacy_info_ptrs[irq] = info;\n\telse\n\t\tirq_set_chip_data(irq, info);\n}", "/* Constructors for packed IRQ information. */\nstatic int xen_irq_info_common_setup(struct irq_info *info,\n\t\t\t\t unsigned irq,\n\t\t\t\t enum xen_irq_type type,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned short cpu)\n{\n\tint ret;", "\tBUG_ON(info->type != IRQT_UNBOUND && info->type != type);", "\tinfo->type = type;\n\tinfo->irq = irq;\n\tinfo->evtchn = evtchn;\n\tinfo->cpu = cpu;", "\tret = set_evtchn_to_irq(evtchn, irq);\n\tif (ret < 0)\n\t\treturn ret;", "\tirq_clear_status_flags(irq, IRQ_NOREQUEST|IRQ_NOAUTOEN);", "\treturn xen_evtchn_port_setup(info);\n}", "static int xen_irq_info_evtchn_setup(unsigned irq,\n\t\t\t\t evtchn_port_t evtchn)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\treturn xen_irq_info_common_setup(info, irq, IRQT_EVTCHN, evtchn, 0);\n}", "static int xen_irq_info_ipi_setup(unsigned cpu,\n\t\t\t\t unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t enum ipi_vector ipi)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.ipi = ipi;", "\tper_cpu(ipi_to_irq, cpu)[ipi] = irq;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_IPI, evtchn, 0);\n}", "static int xen_irq_info_virq_setup(unsigned cpu,\n\t\t\t\t unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned virq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.virq = virq;", "\tper_cpu(virq_to_irq, cpu)[virq] = irq;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_VIRQ, evtchn, 0);\n}", "static int xen_irq_info_pirq_setup(unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned pirq,\n\t\t\t\t unsigned gsi,\n\t\t\t\t uint16_t domid,\n\t\t\t\t unsigned char flags)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.pirq.pirq = pirq;\n\tinfo->u.pirq.gsi = gsi;\n\tinfo->u.pirq.domid = domid;\n\tinfo->u.pirq.flags = flags;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_PIRQ, evtchn, 0);\n}", "static void xen_irq_info_cleanup(struct irq_info *info)\n{\n\tset_evtchn_to_irq(info->evtchn, -1);\n\tinfo->evtchn = 0;\n}", "/*\n * Accessors for packed IRQ information.\n */\nevtchn_port_t evtchn_from_irq(unsigned irq)\n{", "\tif (WARN(irq >= nr_irqs, \"Invalid irq %d!\\n\", irq))", "\t\treturn 0;\n", "\treturn info_for_irq(irq)->evtchn;", "}", "unsigned int irq_from_evtchn(evtchn_port_t evtchn)\n{\n\treturn get_evtchn_to_irq(evtchn);\n}\nEXPORT_SYMBOL_GPL(irq_from_evtchn);", "int irq_from_virq(unsigned int cpu, unsigned int virq)\n{\n\treturn per_cpu(virq_to_irq, cpu)[virq];\n}", "static enum ipi_vector ipi_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_IPI);", "\treturn info->u.ipi;\n}", "static unsigned virq_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_VIRQ);", "\treturn info->u.virq;\n}", "static unsigned pirq_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_PIRQ);", "\treturn info->u.pirq.pirq;\n}", "static enum xen_irq_type type_from_irq(unsigned irq)\n{\n\treturn info_for_irq(irq)->type;\n}", "unsigned cpu_from_irq(unsigned irq)\n{\n\treturn info_for_irq(irq)->cpu;\n}", "unsigned int cpu_from_evtchn(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tunsigned ret = 0;", "\tif (irq != -1)\n\t\tret = cpu_from_irq(irq);", "\treturn ret;\n}", "#ifdef CONFIG_X86\nstatic bool pirq_check_eoi_map(unsigned irq)\n{\n\treturn test_bit(pirq_from_irq(irq), pirq_eoi_map);\n}\n#endif", "static bool pirq_needs_eoi_flag(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);\n\tBUG_ON(info->type != IRQT_PIRQ);", "\treturn info->u.pirq.flags & PIRQ_NEEDS_EOI;\n}", "static void bind_evtchn_to_cpu(evtchn_port_t evtchn, unsigned int cpu)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(irq == -1);\n#ifdef CONFIG_SMP\n\tcpumask_copy(irq_get_affinity_mask(irq), cpumask_of(cpu));\n#endif\n\txen_evtchn_port_bind_to_cpu(info, cpu);", "\tinfo->cpu = cpu;\n}", "/**\n * notify_remote_via_irq - send event to remote end of event channel via irq\n * @irq: irq of event channel to send event to\n *\n * Unlike notify_remote_via_evtchn(), this is safe to use across\n * save/restore. Notifications on a broken connection are silently\n * dropped.\n */\nvoid notify_remote_via_irq(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tnotify_remote_via_evtchn(evtchn);\n}\nEXPORT_SYMBOL_GPL(notify_remote_via_irq);", "static void xen_irq_init(unsigned irq)\n{\n\tstruct irq_info *info;\n#ifdef CONFIG_SMP\n\t/* By default all event channels notify CPU#0. */\n\tcpumask_copy(irq_get_affinity_mask(irq), cpumask_of(0));\n#endif", "\tinfo = kzalloc(sizeof(*info), GFP_KERNEL);\n\tif (info == NULL)\n\t\tpanic(\"Unable to allocate metadata for IRQ%d\\n\", irq);", "\tinfo->type = IRQT_UNBOUND;\n\tinfo->refcnt = -1;", "\tset_info_for_irq(irq, info);", "\tlist_add_tail(&info->list, &xen_irq_list_head);\n}", "static int __must_check xen_allocate_irqs_dynamic(int nvec)\n{\n\tint i, irq = irq_alloc_descs(-1, 0, nvec, -1);", "\tif (irq >= 0) {\n\t\tfor (i = 0; i < nvec; i++)\n\t\t\txen_irq_init(irq + i);\n\t}", "\treturn irq;\n}", "static inline int __must_check xen_allocate_irq_dynamic(void)\n{", "\treturn xen_allocate_irqs_dynamic(1);\n}", "static int __must_check xen_allocate_irq_gsi(unsigned gsi)\n{\n\tint irq;", "\t/*\n\t * A PV guest has no concept of a GSI (since it has no ACPI\n\t * nor access to/knowledge of the physical APICs). Therefore\n\t * all IRQs are dynamically allocated from the entire IRQ\n\t * space.\n\t */\n\tif (xen_pv_domain() && !xen_initial_domain())\n\t\treturn xen_allocate_irq_dynamic();", "\t/* Legacy IRQ descriptors are already allocated by the arch. */\n\tif (gsi < nr_legacy_irqs())\n\t\tirq = gsi;\n\telse\n\t\tirq = irq_alloc_desc_at(gsi, -1);", "\txen_irq_init(irq);", "\treturn irq;\n}", "static void xen_free_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "", "\n\tif (WARN_ON(!info))\n\t\treturn;\n", "", "\tlist_del(&info->list);", "\tset_info_for_irq(irq, NULL);", "\tWARN_ON(info->refcnt > 0);", "", "\n\tkfree(info);", "\t/* Legacy IRQ descriptors are managed by the arch. */\n\tif (irq < nr_legacy_irqs())\n\t\treturn;", "\tirq_free_desc(irq);\n}", "static void xen_evtchn_close(evtchn_port_t port)\n{\n\tstruct evtchn_close close;", "\tclose.port = port;\n\tif (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close) != 0)\n\t\tBUG();\n}", "static void pirq_query_unmask(int irq)\n{\n\tstruct physdev_irq_status_query irq_status;\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tirq_status.irq = pirq_from_irq(irq);\n\tif (HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query, &irq_status))\n\t\tirq_status.flags = 0;", "\tinfo->u.pirq.flags &= ~PIRQ_NEEDS_EOI;\n\tif (irq_status.flags & XENIRQSTAT_needs_eoi)\n\t\tinfo->u.pirq.flags |= PIRQ_NEEDS_EOI;\n}", "static void eoi_pirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);\n\tstruct physdev_eoi eoi = { .irq = pirq_from_irq(data->irq) };\n\tint rc = 0;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tif (unlikely(irqd_is_setaffinity_pending(data)) &&\n\t likely(!irqd_irq_disabled(data))) {\n\t\tint masked = test_and_set_mask(evtchn);", "\t\tclear_evtchn(evtchn);", "\t\tirq_move_masked_irq(data);", "\t\tif (!masked)\n\t\t\tunmask_evtchn(evtchn);\n\t} else\n\t\tclear_evtchn(evtchn);", "\tif (pirq_needs_eoi(data->irq)) {\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_eoi, &eoi);\n\t\tWARN_ON(rc);\n\t}\n}", "static void mask_ack_pirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n\teoi_pirq(data);\n}", "static unsigned int __startup_pirq(unsigned int irq)\n{\n\tstruct evtchn_bind_pirq bind_pirq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tint rc;", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tif (VALID_EVTCHN(evtchn))\n\t\tgoto out;", "\tbind_pirq.pirq = pirq_from_irq(irq);\n\t/* NB. We are happy to share unless we are probing. */\n\tbind_pirq.flags = info->u.pirq.flags & PIRQ_SHAREABLE ?\n\t\t\t\t\tBIND_PIRQ__WILL_SHARE : 0;\n\trc = HYPERVISOR_event_channel_op(EVTCHNOP_bind_pirq, &bind_pirq);\n\tif (rc != 0) {\n\t\tpr_warn(\"Failed to obtain physical IRQ %d\\n\", irq);\n\t\treturn 0;\n\t}\n\tevtchn = bind_pirq.port;", "\tpirq_query_unmask(irq);", "\trc = set_evtchn_to_irq(evtchn, irq);\n\tif (rc)\n\t\tgoto err;", "\tinfo->evtchn = evtchn;\n\tbind_evtchn_to_cpu(evtchn, 0);", "\trc = xen_evtchn_port_setup(info);\n\tif (rc)\n\t\tgoto err;", "out:\n\tunmask_evtchn(evtchn);\n\teoi_pirq(irq_get_irq_data(irq));", "\treturn 0;", "err:\n\tpr_err(\"irq%d: Failed to set port to irq mapping (%d)\\n\", irq, rc);\n\txen_evtchn_close(evtchn);\n\treturn 0;\n}", "static unsigned int startup_pirq(struct irq_data *data)\n{\n\treturn __startup_pirq(data->irq);\n}", "static void shutdown_pirq(struct irq_data *data)\n{\n\tunsigned int irq = data->irq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tmask_evtchn(evtchn);\n\txen_evtchn_close(evtchn);\n\txen_irq_info_cleanup(info);\n}", "static void enable_pirq(struct irq_data *data)\n{\n\tenable_dynirq(data);\n}", "static void disable_pirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n}", "int xen_irq_from_gsi(unsigned gsi)\n{\n\tstruct irq_info *info;", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;", "\t\tif (info->u.pirq.gsi == gsi)\n\t\t\treturn info->irq;\n\t}", "\treturn -1;\n}\nEXPORT_SYMBOL_GPL(xen_irq_from_gsi);", "static void __unbind_from_irq(unsigned int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (info->refcnt > 0) {\n\t\tinfo->refcnt--;\n\t\tif (info->refcnt != 0)\n\t\t\treturn;\n\t}", "\tif (VALID_EVTCHN(evtchn)) {\n\t\tunsigned int cpu = cpu_from_irq(irq);", "\t\txen_evtchn_close(evtchn);", "\t\tswitch (type_from_irq(irq)) {\n\t\tcase IRQT_VIRQ:\n\t\t\tper_cpu(virq_to_irq, cpu)[virq_from_irq(irq)] = -1;\n\t\t\tbreak;\n\t\tcase IRQT_IPI:\n\t\t\tper_cpu(ipi_to_irq, cpu)[ipi_from_irq(irq)] = -1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}", "\t\txen_irq_info_cleanup(info);\n\t}", "\txen_free_irq(irq);\n}", "/*\n * Do not make any assumptions regarding the relationship between the\n * IRQ number returned here and the Xen pirq argument.\n *\n * Note: We don't assign an event channel until the irq actually started\n * up. Return an existing irq if we've already got one for the gsi.\n *\n * Shareable implies level triggered, not shareable implies edge\n * triggered here.\n */\nint xen_bind_pirq_gsi_to_irq(unsigned gsi,\n\t\t\t unsigned pirq, int shareable, char *name)\n{\n\tint irq = -1;\n\tstruct physdev_irq irq_op;\n\tint ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = xen_irq_from_gsi(gsi);\n\tif (irq != -1) {\n\t\tpr_info(\"%s: returning irq %d for gsi %u\\n\",\n\t\t\t__func__, irq, gsi);\n\t\tgoto out;\n\t}", "\tirq = xen_allocate_irq_gsi(gsi);\n\tif (irq < 0)\n\t\tgoto out;", "\tirq_op.irq = irq;\n\tirq_op.vector = 0;", "\t/* Only the privileged domain can do this. For non-priv, the pcifront\n\t * driver provides a PCI bus that does the call to do exactly\n\t * this in the priv domain. */\n\tif (xen_initial_domain() &&\n\t HYPERVISOR_physdev_op(PHYSDEVOP_alloc_irq_vector, &irq_op)) {\n\t\txen_free_irq(irq);\n\t\tirq = -ENOSPC;\n\t\tgoto out;\n\t}", "\tret = xen_irq_info_pirq_setup(irq, 0, pirq, gsi, DOMID_SELF,\n\t\t\t shareable ? PIRQ_SHAREABLE : 0);\n\tif (ret < 0) {\n\t\t__unbind_from_irq(irq);\n\t\tirq = ret;\n\t\tgoto out;\n\t}", "\tpirq_query_unmask(irq);\n\t/* We try to use the handler with the appropriate semantic for the\n\t * type of interrupt: if the interrupt is an edge triggered\n\t * interrupt we use handle_edge_irq.\n\t *\n\t * On the other hand if the interrupt is level triggered we use\n\t * handle_fasteoi_irq like the native code does for this kind of\n\t * interrupts.\n\t *\n\t * Depending on the Xen version, pirq_needs_eoi might return true\n\t * not only for level triggered interrupts but for edge triggered\n\t * interrupts too. In any case Xen always honors the eoi mechanism,\n\t * not injecting any more pirqs of the same kind if the first one\n\t * hasn't received an eoi yet. Therefore using the fasteoi handler\n\t * is the right choice either way.\n\t */\n\tif (shareable)\n\t\tirq_set_chip_and_handler_name(irq, &xen_pirq_chip,\n\t\t\t\thandle_fasteoi_irq, name);\n\telse\n\t\tirq_set_chip_and_handler_name(irq, &xen_pirq_chip,\n\t\t\t\thandle_edge_irq, name);", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "#ifdef CONFIG_PCI_MSI\nint xen_allocate_pirq_msi(struct pci_dev *dev, struct msi_desc *msidesc)\n{\n\tint rc;\n\tstruct physdev_get_free_pirq op_get_free_pirq;", "\top_get_free_pirq.type = MAP_PIRQ_TYPE_MSI;\n\trc = HYPERVISOR_physdev_op(PHYSDEVOP_get_free_pirq, &op_get_free_pirq);", "\tWARN_ONCE(rc == -ENOSYS,\n\t\t \"hypervisor does not support the PHYSDEVOP_get_free_pirq interface\\n\");", "\treturn rc ? -1 : op_get_free_pirq.pirq;\n}", "int xen_bind_pirq_msi_to_irq(struct pci_dev *dev, struct msi_desc *msidesc,\n\t\t\t int pirq, int nvec, const char *name, domid_t domid)\n{\n\tint i, irq, ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = xen_allocate_irqs_dynamic(nvec);\n\tif (irq < 0)\n\t\tgoto out;", "\tfor (i = 0; i < nvec; i++) {\n\t\tirq_set_chip_and_handler_name(irq + i, &xen_pirq_chip, handle_edge_irq, name);", "\t\tret = xen_irq_info_pirq_setup(irq + i, 0, pirq + i, 0, domid,\n\t\t\t\t\t i == 0 ? 0 : PIRQ_MSI_GROUP);\n\t\tif (ret < 0)\n\t\t\tgoto error_irq;\n\t}", "\tret = irq_set_msi_desc(irq, msidesc);\n\tif (ret < 0)\n\t\tgoto error_irq;\nout:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn irq;\nerror_irq:\n\twhile (nvec--)\n\t\t__unbind_from_irq(irq + nvec);\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn ret;\n}\n#endif", "int xen_destroy_irq(int irq)\n{\n\tstruct physdev_unmap_pirq unmap_irq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tint rc = -ENOENT;", "\tmutex_lock(&irq_mapping_update_lock);", "\t/*\n\t * If trying to remove a vector in a MSI group different\n\t * than the first one skip the PIRQ unmap unless this vector\n\t * is the first one in the group.\n\t */\n\tif (xen_initial_domain() && !(info->u.pirq.flags & PIRQ_MSI_GROUP)) {\n\t\tunmap_irq.pirq = info->u.pirq.pirq;\n\t\tunmap_irq.domid = info->u.pirq.domid;\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_unmap_pirq, &unmap_irq);\n\t\t/* If another domain quits without making the pci_disable_msix\n\t\t * call, the Xen hypervisor takes care of freeing the PIRQs\n\t\t * (free_domain_pirqs).\n\t\t */\n\t\tif ((rc == -ESRCH && info->u.pirq.domid != DOMID_SELF))\n\t\t\tpr_info(\"domain %d does not have %d anymore\\n\",\n\t\t\t\tinfo->u.pirq.domid, info->u.pirq.pirq);\n\t\telse if (rc) {\n\t\t\tpr_warn(\"unmap irq failed %d\\n\", rc);\n\t\t\tgoto out;\n\t\t}\n\t}", "\txen_free_irq(irq);", "out:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn rc;\n}", "int xen_irq_from_pirq(unsigned pirq)\n{\n\tint irq;", "\tstruct irq_info *info;", "\tmutex_lock(&irq_mapping_update_lock);", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;\n\t\tirq = info->irq;\n\t\tif (info->u.pirq.pirq == pirq)\n\t\t\tgoto out;\n\t}\n\tirq = -1;\nout:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "\nint xen_pirq_from_irq(unsigned irq)\n{\n\treturn pirq_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(xen_pirq_from_irq);", "int bind_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tint irq;\n\tint ret;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -ENOMEM;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = get_evtchn_to_irq(evtchn);", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tirq_set_chip_and_handler_name(irq, &xen_dynamic_chip,\n\t\t\t\t\t handle_edge_irq, \"event\");", "\t\tret = xen_irq_info_evtchn_setup(irq, evtchn);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}\n\t\t/* New interdomain events are bound to VCPU 0. */\n\t\tbind_evtchn_to_cpu(evtchn, 0);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_EVTCHN);\n\t}", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_evtchn_to_irq);", "static int bind_ipi_to_irq(unsigned int ipi, unsigned int cpu)\n{\n\tstruct evtchn_bind_ipi bind_ipi;\n\tevtchn_port_t evtchn;\n\tint ret, irq;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = per_cpu(ipi_to_irq, cpu)[ipi];", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tirq_set_chip_and_handler_name(irq, &xen_percpu_chip,\n\t\t\t\t\t handle_percpu_irq, \"ipi\");", "\t\tbind_ipi.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi,\n\t\t\t\t\t\t&bind_ipi) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_ipi.port;", "\t\tret = xen_irq_info_ipi_setup(cpu, irq, evtchn, ipi);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_IPI);\n\t}", " out:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn irq;\n}", "int bind_interdomain_evtchn_to_irq(unsigned int remote_domain,\n\t\t\t\t evtchn_port_t remote_port)\n{\n\tstruct evtchn_bind_interdomain bind_interdomain;\n\tint err;", "\tbind_interdomain.remote_dom = remote_domain;\n\tbind_interdomain.remote_port = remote_port;", "\terr = HYPERVISOR_event_channel_op(EVTCHNOP_bind_interdomain,\n\t\t\t\t\t &bind_interdomain);", "\treturn err ? : bind_evtchn_to_irq(bind_interdomain.local_port);\n}\nEXPORT_SYMBOL_GPL(bind_interdomain_evtchn_to_irq);", "static int find_virq(unsigned int virq, unsigned int cpu, evtchn_port_t *evtchn)\n{\n\tstruct evtchn_status status;\n\tevtchn_port_t port;\n\tint rc = -ENOENT;", "\tmemset(&status, 0, sizeof(status));\n\tfor (port = 0; port < xen_evtchn_max_channels(); port++) {\n\t\tstatus.dom = DOMID_SELF;\n\t\tstatus.port = port;\n\t\trc = HYPERVISOR_event_channel_op(EVTCHNOP_status, &status);\n\t\tif (rc < 0)\n\t\t\tcontinue;\n\t\tif (status.status != EVTCHNSTAT_virq)\n\t\t\tcontinue;\n\t\tif (status.u.virq == virq && status.vcpu == xen_vcpu_nr(cpu)) {\n\t\t\t*evtchn = port;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn rc;\n}", "/**\n * xen_evtchn_nr_channels - number of usable event channel ports\n *\n * This may be less than the maximum supported by the current\n * hypervisor ABI. Use xen_evtchn_max_channels() for the maximum\n * supported.\n */\nunsigned xen_evtchn_nr_channels(void)\n{\n return evtchn_ops->nr_channels();\n}\nEXPORT_SYMBOL_GPL(xen_evtchn_nr_channels);", "int bind_virq_to_irq(unsigned int virq, unsigned int cpu, bool percpu)\n{\n\tstruct evtchn_bind_virq bind_virq;\n\tevtchn_port_t evtchn = 0;\n\tint irq, ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = per_cpu(virq_to_irq, cpu)[virq];", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tif (percpu)\n\t\t\tirq_set_chip_and_handler_name(irq, &xen_percpu_chip,\n\t\t\t\t\t\t handle_percpu_irq, \"virq\");\n\t\telse\n\t\t\tirq_set_chip_and_handler_name(irq, &xen_dynamic_chip,\n\t\t\t\t\t\t handle_edge_irq, \"virq\");", "\t\tbind_virq.virq = virq;\n\t\tbind_virq.vcpu = xen_vcpu_nr(cpu);\n\t\tret = HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq,\n\t\t\t\t\t\t&bind_virq);\n\t\tif (ret == 0)\n\t\t\tevtchn = bind_virq.port;\n\t\telse {\n\t\t\tif (ret == -EEXIST)\n\t\t\t\tret = find_virq(virq, cpu, &evtchn);\n\t\t\tBUG_ON(ret < 0);\n\t\t}", "\t\tret = xen_irq_info_virq_setup(cpu, irq, evtchn, virq);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}", "\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_VIRQ);\n\t}", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "static void unbind_from_irq(unsigned int irq)\n{\n\tmutex_lock(&irq_mapping_update_lock);\n\t__unbind_from_irq(irq);\n\tmutex_unlock(&irq_mapping_update_lock);\n}", "int bind_evtchn_to_irqhandler(evtchn_port_t evtchn,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags,\n\t\t\t const char *devname, void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_evtchn_to_irq(evtchn);\n\tif (irq < 0)\n\t\treturn irq;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_evtchn_to_irqhandler);", "int bind_interdomain_evtchn_to_irqhandler(unsigned int remote_domain,\n\t\t\t\t\t evtchn_port_t remote_port,\n\t\t\t\t\t irq_handler_t handler,\n\t\t\t\t\t unsigned long irqflags,\n\t\t\t\t\t const char *devname,\n\t\t\t\t\t void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_interdomain_evtchn_to_irq(remote_domain, remote_port);\n\tif (irq < 0)\n\t\treturn irq;", "\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_interdomain_evtchn_to_irqhandler);", "int bind_virq_to_irqhandler(unsigned int virq, unsigned int cpu,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags, const char *devname, void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_virq_to_irq(virq, cpu, irqflags & IRQF_PERCPU);\n\tif (irq < 0)\n\t\treturn irq;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_virq_to_irqhandler);", "int bind_ipi_to_irqhandler(enum ipi_vector ipi,\n\t\t\t unsigned int cpu,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags,\n\t\t\t const char *devname,\n\t\t\t void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_ipi_to_irq(ipi, cpu);\n\tif (irq < 0)\n\t\treturn irq;", "\tirqflags |= IRQF_NO_SUSPEND | IRQF_FORCE_RESUME | IRQF_EARLY_RESUME;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}", "void unbind_from_irqhandler(unsigned int irq, void *dev_id)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (WARN_ON(!info))\n\t\treturn;\n\tfree_irq(irq, dev_id);\n\tunbind_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(unbind_from_irqhandler);", "/**\n * xen_set_irq_priority() - set an event channel priority.\n * @irq:irq bound to an event channel.\n * @priority: priority between XEN_IRQ_PRIORITY_MAX and XEN_IRQ_PRIORITY_MIN.\n */\nint xen_set_irq_priority(unsigned irq, unsigned priority)\n{\n\tstruct evtchn_set_priority set_priority;", "\tset_priority.port = evtchn_from_irq(irq);\n\tset_priority.priority = priority;", "\treturn HYPERVISOR_event_channel_op(EVTCHNOP_set_priority,\n\t\t\t\t\t &set_priority);\n}\nEXPORT_SYMBOL_GPL(xen_set_irq_priority);", "int evtchn_make_refcounted(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tstruct irq_info *info;", "\tif (irq == -1)\n\t\treturn -ENOENT;", "\tinfo = info_for_irq(irq);", "\tif (!info)\n\t\treturn -ENOENT;", "\tWARN_ON(info->refcnt != -1);", "\tinfo->refcnt = 1;", "\treturn 0;\n}\nEXPORT_SYMBOL_GPL(evtchn_make_refcounted);", "int evtchn_get(evtchn_port_t evtchn)\n{\n\tint irq;\n\tstruct irq_info *info;\n\tint err = -ENOENT;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -EINVAL;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = get_evtchn_to_irq(evtchn);\n\tif (irq == -1)\n\t\tgoto done;", "\tinfo = info_for_irq(irq);", "\tif (!info)\n\t\tgoto done;", "\terr = -EINVAL;\n\tif (info->refcnt <= 0)\n\t\tgoto done;", "\tinfo->refcnt++;\n\terr = 0;\n done:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn err;\n}\nEXPORT_SYMBOL_GPL(evtchn_get);", "void evtchn_put(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tif (WARN_ON(irq == -1))\n\t\treturn;\n\tunbind_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(evtchn_put);", "void xen_send_IPI_one(unsigned int cpu, enum ipi_vector vector)\n{\n\tint irq;", "#ifdef CONFIG_X86\n\tif (unlikely(vector == XEN_NMI_VECTOR)) {\n\t\tint rc = HYPERVISOR_vcpu_op(VCPUOP_send_nmi, xen_vcpu_nr(cpu),\n\t\t\t\t\t NULL);\n\t\tif (rc < 0)\n\t\t\tprintk(KERN_WARNING \"Sending nmi to CPU%d failed (rc:%d)\\n\", cpu, rc);\n\t\treturn;\n\t}\n#endif\n\tirq = per_cpu(ipi_to_irq, cpu)[vector];\n\tBUG_ON(irq < 0);\n\tnotify_remote_via_irq(irq);\n}", "static void __xen_evtchn_do_upcall(void)\n{\n\tstruct vcpu_info *vcpu_info = __this_cpu_read(xen_vcpu);\n\tint cpu = smp_processor_id();\n", "", "\tdo {\n\t\tvcpu_info->evtchn_upcall_pending = 0;", "\t\txen_evtchn_handle_events(cpu);", "\t\tBUG_ON(!irqs_disabled());", "\t\tvirt_rmb(); /* Hypervisor can set upcall pending. */", "\t} while (vcpu_info->evtchn_upcall_pending);", "", "}", "void xen_evtchn_do_upcall(struct pt_regs *regs)\n{\n\tstruct pt_regs *old_regs = set_irq_regs(regs);", "\tirq_enter();", "\t__xen_evtchn_do_upcall();", "\tirq_exit();\n\tset_irq_regs(old_regs);\n}", "void xen_hvm_evtchn_do_upcall(void)\n{\n\t__xen_evtchn_do_upcall();\n}\nEXPORT_SYMBOL_GPL(xen_hvm_evtchn_do_upcall);", "/* Rebind a new event channel to an existing irq. */\nvoid rebind_evtchn_irq(evtchn_port_t evtchn, int irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (WARN_ON(!info))\n\t\treturn;", "\t/* Make sure the irq is masked, since the new event channel\n\t will also be masked. */\n\tdisable_irq(irq);", "\tmutex_lock(&irq_mapping_update_lock);", "\t/* After resume the irq<->evtchn mappings are all cleared out */\n\tBUG_ON(get_evtchn_to_irq(evtchn) != -1);\n\t/* Expect irq to have been bound before,\n\t so there should be a proper type */\n\tBUG_ON(info->type == IRQT_UNBOUND);", "\t(void)xen_irq_info_evtchn_setup(irq, evtchn);", "\tmutex_unlock(&irq_mapping_update_lock);", " bind_evtchn_to_cpu(evtchn, info->cpu);\n\t/* This will be deferred until interrupt is processed */\n\tirq_set_affinity(irq, cpumask_of(info->cpu));", "\t/* Unmask the event channel. */\n\tenable_irq(irq);\n}", "/* Rebind an evtchn so that it gets delivered to a specific cpu */\nstatic int xen_rebind_evtchn_to_cpu(evtchn_port_t evtchn, unsigned int tcpu)\n{\n\tstruct evtchn_bind_vcpu bind_vcpu;\n\tint masked;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn -1;", "\tif (!xen_support_evtchn_rebind())\n\t\treturn -1;", "\t/* Send future instances of this interrupt to other vcpu. */\n\tbind_vcpu.port = evtchn;\n\tbind_vcpu.vcpu = xen_vcpu_nr(tcpu);", "\t/*\n\t * Mask the event while changing the VCPU binding to prevent\n\t * it being delivered on an unexpected VCPU.\n\t */\n\tmasked = test_and_set_mask(evtchn);", "\t/*\n\t * If this fails, it usually just indicates that we're dealing with a\n\t * virq or IPI channel, which don't actually need to be rebound. Ignore\n\t * it, but don't do the xenlinux-level rebind in that case.\n\t */\n\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_vcpu, &bind_vcpu) >= 0)\n\t\tbind_evtchn_to_cpu(evtchn, tcpu);", "\tif (!masked)\n\t\tunmask_evtchn(evtchn);", "\treturn 0;\n}", "static int set_affinity_irq(struct irq_data *data, const struct cpumask *dest,\n\t\t\t bool force)\n{\n\tunsigned tcpu = cpumask_first_and(dest, cpu_online_mask);\n\tint ret = xen_rebind_evtchn_to_cpu(evtchn_from_irq(data->irq), tcpu);", "\tif (!ret)\n\t\tirq_data_update_effective_affinity(data, cpumask_of(tcpu));", "\treturn ret;\n}", "/* To be called with desc->lock held. */\nint xen_set_affinity_evtchn(struct irq_desc *desc, unsigned int tcpu)\n{\n\tstruct irq_data *d = irq_desc_get_irq_data(desc);", "\treturn set_affinity_irq(d, cpumask_of(tcpu), false);\n}\nEXPORT_SYMBOL_GPL(xen_set_affinity_evtchn);", "static void enable_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tunmask_evtchn(evtchn);\n}", "static void disable_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tmask_evtchn(evtchn);\n}", "static void ack_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tif (unlikely(irqd_is_setaffinity_pending(data)) &&\n\t likely(!irqd_irq_disabled(data))) {\n\t\tint masked = test_and_set_mask(evtchn);", "\t\tclear_evtchn(evtchn);", "\t\tirq_move_masked_irq(data);", "\t\tif (!masked)\n\t\t\tunmask_evtchn(evtchn);\n\t} else\n\t\tclear_evtchn(evtchn);\n}", "static void mask_ack_dynirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n\tack_dynirq(data);\n}", "static int retrigger_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);\n\tint masked;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn 0;", "\tmasked = test_and_set_mask(evtchn);\n\tset_evtchn(evtchn);\n\tif (!masked)\n\t\tunmask_evtchn(evtchn);", "\treturn 1;\n}", "static void restore_pirqs(void)\n{\n\tint pirq, rc, irq, gsi;\n\tstruct physdev_map_pirq map_irq;\n\tstruct irq_info *info;", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;", "\t\tpirq = info->u.pirq.pirq;\n\t\tgsi = info->u.pirq.gsi;\n\t\tirq = info->irq;", "\t\t/* save/restore of PT devices doesn't work, so at this point the\n\t\t * only devices present are GSI based emulated devices */\n\t\tif (!gsi)\n\t\t\tcontinue;", "\t\tmap_irq.domid = DOMID_SELF;\n\t\tmap_irq.type = MAP_PIRQ_TYPE_GSI;\n\t\tmap_irq.index = gsi;\n\t\tmap_irq.pirq = pirq;", "\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_map_pirq, &map_irq);\n\t\tif (rc) {\n\t\t\tpr_warn(\"xen map irq failed gsi=%d irq=%d pirq=%d rc=%d\\n\",\n\t\t\t\tgsi, irq, pirq, rc);\n\t\t\txen_free_irq(irq);\n\t\t\tcontinue;\n\t\t}", "\t\tprintk(KERN_DEBUG \"xen: --> irq=%d, pirq=%d\\n\", irq, map_irq.pirq);", "\t\t__startup_pirq(irq);\n\t}\n}", "static void restore_cpu_virqs(unsigned int cpu)\n{\n\tstruct evtchn_bind_virq bind_virq;\n\tevtchn_port_t evtchn;\n\tint virq, irq;", "\tfor (virq = 0; virq < NR_VIRQS; virq++) {\n\t\tif ((irq = per_cpu(virq_to_irq, cpu)[virq]) == -1)\n\t\t\tcontinue;", "\t\tBUG_ON(virq_from_irq(irq) != virq);", "\t\t/* Get a new binding from Xen. */\n\t\tbind_virq.virq = virq;\n\t\tbind_virq.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq,\n\t\t\t\t\t\t&bind_virq) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_virq.port;", "\t\t/* Record the new mapping. */\n\t\t(void)xen_irq_info_virq_setup(cpu, irq, evtchn, virq);\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t}\n}", "static void restore_cpu_ipis(unsigned int cpu)\n{\n\tstruct evtchn_bind_ipi bind_ipi;\n\tevtchn_port_t evtchn;\n\tint ipi, irq;", "\tfor (ipi = 0; ipi < XEN_NR_IPIS; ipi++) {\n\t\tif ((irq = per_cpu(ipi_to_irq, cpu)[ipi]) == -1)\n\t\t\tcontinue;", "\t\tBUG_ON(ipi_from_irq(irq) != ipi);", "\t\t/* Get a new binding from Xen. */\n\t\tbind_ipi.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi,\n\t\t\t\t\t\t&bind_ipi) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_ipi.port;", "\t\t/* Record the new mapping. */\n\t\t(void)xen_irq_info_ipi_setup(cpu, irq, evtchn, ipi);\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t}\n}", "/* Clear an irq's pending state, in preparation for polling on it */\nvoid xen_clear_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tclear_evtchn(evtchn);\n}\nEXPORT_SYMBOL(xen_clear_irq_pending);\nvoid xen_set_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tset_evtchn(evtchn);\n}", "bool xen_test_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tbool ret = false;", "\tif (VALID_EVTCHN(evtchn))\n\t\tret = test_evtchn(evtchn);", "\treturn ret;\n}", "/* Poll waiting for an irq to become pending with timeout. In the usual case,\n * the irq will be disabled so it won't deliver an interrupt. */\nvoid xen_poll_irq_timeout(int irq, u64 timeout)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn)) {\n\t\tstruct sched_poll poll;", "\t\tpoll.nr_ports = 1;\n\t\tpoll.timeout = timeout;\n\t\tset_xen_guest_handle(poll.ports, &evtchn);", "\t\tif (HYPERVISOR_sched_op(SCHEDOP_poll, &poll) != 0)\n\t\t\tBUG();\n\t}\n}\nEXPORT_SYMBOL(xen_poll_irq_timeout);\n/* Poll waiting for an irq to become pending. In the usual case, the\n * irq will be disabled so it won't deliver an interrupt. */\nvoid xen_poll_irq(int irq)\n{\n\txen_poll_irq_timeout(irq, 0 /* no timeout */);\n}", "/* Check whether the IRQ line is shared with other guests. */\nint xen_test_irq_shared(int irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);\n\tstruct physdev_irq_status_query irq_status;", "\tif (WARN_ON(!info))\n\t\treturn -ENOENT;", "\tirq_status.irq = info->u.pirq.pirq;", "\tif (HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query, &irq_status))\n\t\treturn 0;\n\treturn !(irq_status.flags & XENIRQSTAT_shared);\n}\nEXPORT_SYMBOL_GPL(xen_test_irq_shared);", "void xen_irq_resume(void)\n{\n\tunsigned int cpu;\n\tstruct irq_info *info;", "\t/* New event-channel space is not 'live' yet. */\n\txen_evtchn_resume();", "\t/* No IRQ <-> event-channel mappings. */\n\tlist_for_each_entry(info, &xen_irq_list_head, list)\n\t\tinfo->evtchn = 0; /* zap event-channel binding */", "\tclear_evtchn_to_irq_all();", "\tfor_each_possible_cpu(cpu) {\n\t\trestore_cpu_virqs(cpu);\n\t\trestore_cpu_ipis(cpu);\n\t}", "\trestore_pirqs();\n}", "static struct irq_chip xen_dynamic_chip __read_mostly = {\n\t.name\t\t\t= \"xen-dyn\",", "\t.irq_disable\t\t= disable_dynirq,\n\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= ack_dynirq,\n\t.irq_mask_ack\t\t= mask_ack_dynirq,", "\t.irq_set_affinity\t= set_affinity_irq,\n\t.irq_retrigger\t\t= retrigger_dynirq,\n};", "static struct irq_chip xen_pirq_chip __read_mostly = {\n\t.name\t\t\t= \"xen-pirq\",", "\t.irq_startup\t\t= startup_pirq,\n\t.irq_shutdown\t\t= shutdown_pirq,\n\t.irq_enable\t\t= enable_pirq,\n\t.irq_disable\t\t= disable_pirq,", "\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= eoi_pirq,\n\t.irq_eoi\t\t= eoi_pirq,\n\t.irq_mask_ack\t\t= mask_ack_pirq,", "\t.irq_set_affinity\t= set_affinity_irq,", "\t.irq_retrigger\t\t= retrigger_dynirq,\n};", "static struct irq_chip xen_percpu_chip __read_mostly = {\n\t.name\t\t\t= \"xen-percpu\",", "\t.irq_disable\t\t= disable_dynirq,\n\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= ack_dynirq,\n};", "int xen_set_callback_via(uint64_t via)\n{\n\tstruct xen_hvm_param a;\n\ta.domid = DOMID_SELF;\n\ta.index = HVM_PARAM_CALLBACK_IRQ;\n\ta.value = via;\n\treturn HYPERVISOR_hvm_op(HVMOP_set_param, &a);\n}\nEXPORT_SYMBOL_GPL(xen_set_callback_via);", "#ifdef CONFIG_XEN_PVHVM\n/* Vector callbacks are better than PCI interrupts to receive event\n * channel notifications because we can receive vector callbacks on any\n * vcpu and we don't need PCI support or APIC interactions. */\nvoid xen_setup_callback_vector(void)\n{\n\tuint64_t callback_via;", "\tif (xen_have_vector_callback) {\n\t\tcallback_via = HVM_CALLBACK_VECTOR(HYPERVISOR_CALLBACK_VECTOR);\n\t\tif (xen_set_callback_via(callback_via)) {\n\t\t\tpr_err(\"Request for Xen HVM callback vector failed\\n\");\n\t\t\txen_have_vector_callback = 0;\n\t\t}\n\t}\n}", "static __init void xen_alloc_callback_vector(void)\n{\n\tif (!xen_have_vector_callback)\n\t\treturn;", "\tpr_info(\"Xen HVM callback vector for event delivery is enabled\\n\");\n\talloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_xen_hvm_callback);\n}\n#else\nvoid xen_setup_callback_vector(void) {}\nstatic inline void xen_alloc_callback_vector(void) {}\n#endif", "#undef MODULE_PARAM_PREFIX\n#define MODULE_PARAM_PREFIX \"xen.\"", "static bool fifo_events = true;\nmodule_param(fifo_events, bool, 0);", "void __init xen_init_IRQ(void)\n{\n\tint ret = -EINVAL;\n\tevtchn_port_t evtchn;", "\tif (fifo_events)\n\t\tret = xen_evtchn_fifo_init();\n\tif (ret < 0)\n\t\txen_evtchn_2l_init();", "\tevtchn_to_irq = kcalloc(EVTCHN_ROW(xen_evtchn_max_channels()),\n\t\t\t\tsizeof(*evtchn_to_irq), GFP_KERNEL);\n\tBUG_ON(!evtchn_to_irq);", "\t/* No event channels are 'live' right now. */\n\tfor (evtchn = 0; evtchn < xen_evtchn_nr_channels(); evtchn++)\n\t\tmask_evtchn(evtchn);", "\tpirq_needs_eoi = pirq_needs_eoi_flag;", "#ifdef CONFIG_X86\n\tif (xen_pv_domain()) {\n\t\tif (xen_initial_domain())\n\t\t\tpci_xen_initial_domain();\n\t}\n\tif (xen_feature(XENFEAT_hvm_callback_vector)) {\n\t\txen_setup_callback_vector();\n\t\txen_alloc_callback_vector();\n\t}", "\tif (xen_hvm_domain()) {\n\t\tnative_init_IRQ();\n\t\t/* pci_xen_hvm_init must be called after native_init_IRQ so that\n\t\t * __acpi_register_gsi can point at the right function */\n\t\tpci_xen_hvm_init();\n\t} else {\n\t\tint rc;\n\t\tstruct physdev_pirq_eoi_gmfn eoi_gmfn;", "\t\tpirq_eoi_map = (void *)__get_free_page(GFP_KERNEL|__GFP_ZERO);\n\t\teoi_gmfn.gmfn = virt_to_gfn(pirq_eoi_map);\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_pirq_eoi_gmfn_v2, &eoi_gmfn);\n\t\tif (rc != 0) {\n\t\t\tfree_page((unsigned long) pirq_eoi_map);\n\t\t\tpirq_eoi_map = NULL;\n\t\t} else\n\t\t\tpirq_needs_eoi = pirq_check_eoi_map;\n\t}\n#endif\n}" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1245], "buggy_code_start_loc": [35], "filenames": ["drivers/xen/events/events_base.c"], "fixing_code_end_loc": [1277], "fixing_code_start_loc": [36], "message": "An issue was discovered in the Linux kernel through 5.9.1, as used with Xen through 4.14.x. drivers/xen/events/events_base.c allows event-channel removal during the event-handling loop (a race condition). This can cause a use-after-free or NULL pointer dereference, as demonstrated by a dom0 crash via events for an in-reconfiguration paravirtualized device, aka CID-073d0552ead5.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7E1EBA7-1B6D-4A6D-ADFF-2B556573F073", "versionEndExcluding": null, "versionEndIncluding": "5.9.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the Linux kernel through 5.9.1, as used with Xen through 4.14.x. drivers/xen/events/events_base.c allows event-channel removal during the event-handling loop (a race condition). This can cause a use-after-free or NULL pointer dereference, as demonstrated by a dom0 crash via events for an in-reconfiguration paravirtualized device, aka CID-073d0552ead5."}, {"lang": "es", "value": "Se detect\u00f3 un problema en el kernel de Linux versiones hasta 5.9.1, como es usado con Xen versiones hasta 4.14.x.&#xa0;El archivo drivers/xen/events/events_base.c permite la eliminaci\u00f3n del canal de eventos durante el ciclo de manejo de eventos (una condici\u00f3n de carrera).&#xa0;Esto puede causar una desreferencia del puntero NULL y un uso de la memoria previamente liberada como es demostrado por un bloqueo dom0 por medio de eventos para un dispositivo paravirtualizado en reconfiguraci\u00f3n, tambi\u00e9n se conoce como CID-073d0552ead5"}], "evaluatorComment": null, "id": "CVE-2020-27675", "lastModified": "2022-04-26T16:29:52.957", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.7, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 4.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.0, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-10-22T21:15:14.153", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2021/01/19/3"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/12/msg00015.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/12/msg00027.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3ZG6TZLD23QO3PV2AN2HB625ZX47ALTT/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/6USZ4APZSBQDHGJLJMHW5JBN4QZV6SKZ/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GNF2R7FUT4IOJ2RIRGQ7X5R4F4FVVLSR/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202011-06"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://xenbits.xen.org/xsa/advisory-331.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}, {"lang": "en", "value": "CWE-416"}, {"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, "type": "CWE-362"}
117
Determine whether the {function_name} code is vulnerable or not.
[ "// SPDX-License-Identifier: GPL-2.0-only\n/*\n * Xen event channels\n *\n * Xen models interrupts with abstract event channels. Because each\n * domain gets 1024 event channels, but NR_IRQ is not that large, we\n * must dynamically map irqs<->event channels. The event channels\n * interface with the rest of the kernel by defining a xen interrupt\n * chip. When an event is received, it is mapped to an irq and sent\n * through the normal interrupt processing path.\n *\n * There are four kinds of events which can be mapped to an event\n * channel:\n *\n * 1. Inter-domain notifications. This includes all the virtual\n * device events, since they're driven by front-ends in another domain\n * (typically dom0).\n * 2. VIRQs, typically used for timers. These are per-cpu events.\n * 3. IPIs.\n * 4. PIRQs - Hardware interrupts.\n *\n * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007\n */", "#define pr_fmt(fmt) \"xen:\" KBUILD_MODNAME \": \" fmt", "#include <linux/linkage.h>\n#include <linux/interrupt.h>\n#include <linux/irq.h>\n#include <linux/moduleparam.h>\n#include <linux/string.h>\n#include <linux/memblock.h>\n#include <linux/slab.h>\n#include <linux/irqnr.h>\n#include <linux/pci.h>", "#include <linux/spinlock.h>", "\n#ifdef CONFIG_X86\n#include <asm/desc.h>\n#include <asm/ptrace.h>\n#include <asm/idtentry.h>\n#include <asm/irq.h>\n#include <asm/io_apic.h>\n#include <asm/i8259.h>\n#include <asm/xen/pci.h>\n#endif\n#include <asm/sync_bitops.h>\n#include <asm/xen/hypercall.h>\n#include <asm/xen/hypervisor.h>\n#include <xen/page.h>", "#include <xen/xen.h>\n#include <xen/hvm.h>\n#include <xen/xen-ops.h>\n#include <xen/events.h>\n#include <xen/interface/xen.h>\n#include <xen/interface/event_channel.h>\n#include <xen/interface/hvm/hvm_op.h>\n#include <xen/interface/hvm/params.h>\n#include <xen/interface/physdev.h>\n#include <xen/interface/sched.h>\n#include <xen/interface/vcpu.h>\n#include <asm/hw_irq.h>", "#include \"events_internal.h\"", "const struct evtchn_ops *evtchn_ops;", "/*\n * This lock protects updates to the following mapping and reference-count\n * arrays. The lock does not need to be acquired to read the mapping tables.\n */\nstatic DEFINE_MUTEX(irq_mapping_update_lock);\n", "/*\n * Lock protecting event handling loop against removing event channels.\n * Adding of event channels is no issue as the associated IRQ becomes active\n * only after everything is setup (before request_[threaded_]irq() the handler\n * can't be entered for an event, as the event channel will be unmasked only\n * then).\n */\nstatic DEFINE_RWLOCK(evtchn_rwlock);", "/*\n * Lock hierarchy:\n *\n * irq_mapping_update_lock\n * evtchn_rwlock\n * IRQ-desc lock\n */\n", "static LIST_HEAD(xen_irq_list_head);", "/* IRQ <-> VIRQ mapping. */\nstatic DEFINE_PER_CPU(int [NR_VIRQS], virq_to_irq) = {[0 ... NR_VIRQS-1] = -1};", "/* IRQ <-> IPI mapping */\nstatic DEFINE_PER_CPU(int [XEN_NR_IPIS], ipi_to_irq) = {[0 ... XEN_NR_IPIS-1] = -1};", "int **evtchn_to_irq;\n#ifdef CONFIG_X86\nstatic unsigned long *pirq_eoi_map;\n#endif\nstatic bool (*pirq_needs_eoi)(unsigned irq);", "#define EVTCHN_ROW(e) (e / (PAGE_SIZE/sizeof(**evtchn_to_irq)))\n#define EVTCHN_COL(e) (e % (PAGE_SIZE/sizeof(**evtchn_to_irq)))\n#define EVTCHN_PER_ROW (PAGE_SIZE / sizeof(**evtchn_to_irq))", "/* Xen will never allocate port zero for any purpose. */\n#define VALID_EVTCHN(chn)\t((chn) != 0)", "static struct irq_info *legacy_info_ptrs[NR_IRQS_LEGACY];", "static struct irq_chip xen_dynamic_chip;\nstatic struct irq_chip xen_percpu_chip;\nstatic struct irq_chip xen_pirq_chip;\nstatic void enable_dynirq(struct irq_data *data);\nstatic void disable_dynirq(struct irq_data *data);", "static void clear_evtchn_to_irq_row(unsigned row)\n{\n\tunsigned col;", "\tfor (col = 0; col < EVTCHN_PER_ROW; col++)", "\t\tWRITE_ONCE(evtchn_to_irq[row][col], -1);", "}", "static void clear_evtchn_to_irq_all(void)\n{\n\tunsigned row;", "\tfor (row = 0; row < EVTCHN_ROW(xen_evtchn_max_channels()); row++) {\n\t\tif (evtchn_to_irq[row] == NULL)\n\t\t\tcontinue;\n\t\tclear_evtchn_to_irq_row(row);\n\t}\n}", "static int set_evtchn_to_irq(evtchn_port_t evtchn, unsigned int irq)\n{\n\tunsigned row;\n\tunsigned col;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -EINVAL;", "\trow = EVTCHN_ROW(evtchn);\n\tcol = EVTCHN_COL(evtchn);", "\tif (evtchn_to_irq[row] == NULL) {\n\t\t/* Unallocated irq entries return -1 anyway */\n\t\tif (irq == -1)\n\t\t\treturn 0;", "\t\tevtchn_to_irq[row] = (int *)get_zeroed_page(GFP_KERNEL);\n\t\tif (evtchn_to_irq[row] == NULL)\n\t\t\treturn -ENOMEM;", "\t\tclear_evtchn_to_irq_row(row);\n\t}\n", "\tWRITE_ONCE(evtchn_to_irq[row][col], irq);", "\treturn 0;\n}", "int get_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -1;\n\tif (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL)\n\t\treturn -1;", "\treturn READ_ONCE(evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)]);", "}", "/* Get info for IRQ */\nstruct irq_info *info_for_irq(unsigned irq)\n{\n\tif (irq < nr_legacy_irqs())\n\t\treturn legacy_info_ptrs[irq];\n\telse\n\t\treturn irq_get_chip_data(irq);\n}", "static void set_info_for_irq(unsigned int irq, struct irq_info *info)\n{\n\tif (irq < nr_legacy_irqs())\n\t\tlegacy_info_ptrs[irq] = info;\n\telse\n\t\tirq_set_chip_data(irq, info);\n}", "/* Constructors for packed IRQ information. */\nstatic int xen_irq_info_common_setup(struct irq_info *info,\n\t\t\t\t unsigned irq,\n\t\t\t\t enum xen_irq_type type,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned short cpu)\n{\n\tint ret;", "\tBUG_ON(info->type != IRQT_UNBOUND && info->type != type);", "\tinfo->type = type;\n\tinfo->irq = irq;\n\tinfo->evtchn = evtchn;\n\tinfo->cpu = cpu;", "\tret = set_evtchn_to_irq(evtchn, irq);\n\tif (ret < 0)\n\t\treturn ret;", "\tirq_clear_status_flags(irq, IRQ_NOREQUEST|IRQ_NOAUTOEN);", "\treturn xen_evtchn_port_setup(info);\n}", "static int xen_irq_info_evtchn_setup(unsigned irq,\n\t\t\t\t evtchn_port_t evtchn)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\treturn xen_irq_info_common_setup(info, irq, IRQT_EVTCHN, evtchn, 0);\n}", "static int xen_irq_info_ipi_setup(unsigned cpu,\n\t\t\t\t unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t enum ipi_vector ipi)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.ipi = ipi;", "\tper_cpu(ipi_to_irq, cpu)[ipi] = irq;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_IPI, evtchn, 0);\n}", "static int xen_irq_info_virq_setup(unsigned cpu,\n\t\t\t\t unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned virq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.virq = virq;", "\tper_cpu(virq_to_irq, cpu)[virq] = irq;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_VIRQ, evtchn, 0);\n}", "static int xen_irq_info_pirq_setup(unsigned irq,\n\t\t\t\t evtchn_port_t evtchn,\n\t\t\t\t unsigned pirq,\n\t\t\t\t unsigned gsi,\n\t\t\t\t uint16_t domid,\n\t\t\t\t unsigned char flags)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tinfo->u.pirq.pirq = pirq;\n\tinfo->u.pirq.gsi = gsi;\n\tinfo->u.pirq.domid = domid;\n\tinfo->u.pirq.flags = flags;", "\treturn xen_irq_info_common_setup(info, irq, IRQT_PIRQ, evtchn, 0);\n}", "static void xen_irq_info_cleanup(struct irq_info *info)\n{\n\tset_evtchn_to_irq(info->evtchn, -1);\n\tinfo->evtchn = 0;\n}", "/*\n * Accessors for packed IRQ information.\n */\nevtchn_port_t evtchn_from_irq(unsigned irq)\n{", "\tconst struct irq_info *info = NULL;", "\tif (likely(irq < nr_irqs))\n\t\tinfo = info_for_irq(irq);\n\tif (!info)", "\t\treturn 0;\n", "\treturn info->evtchn;", "}", "unsigned int irq_from_evtchn(evtchn_port_t evtchn)\n{\n\treturn get_evtchn_to_irq(evtchn);\n}\nEXPORT_SYMBOL_GPL(irq_from_evtchn);", "int irq_from_virq(unsigned int cpu, unsigned int virq)\n{\n\treturn per_cpu(virq_to_irq, cpu)[virq];\n}", "static enum ipi_vector ipi_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_IPI);", "\treturn info->u.ipi;\n}", "static unsigned virq_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_VIRQ);", "\treturn info->u.virq;\n}", "static unsigned pirq_from_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info == NULL);\n\tBUG_ON(info->type != IRQT_PIRQ);", "\treturn info->u.pirq.pirq;\n}", "static enum xen_irq_type type_from_irq(unsigned irq)\n{\n\treturn info_for_irq(irq)->type;\n}", "unsigned cpu_from_irq(unsigned irq)\n{\n\treturn info_for_irq(irq)->cpu;\n}", "unsigned int cpu_from_evtchn(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tunsigned ret = 0;", "\tif (irq != -1)\n\t\tret = cpu_from_irq(irq);", "\treturn ret;\n}", "#ifdef CONFIG_X86\nstatic bool pirq_check_eoi_map(unsigned irq)\n{\n\treturn test_bit(pirq_from_irq(irq), pirq_eoi_map);\n}\n#endif", "static bool pirq_needs_eoi_flag(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);\n\tBUG_ON(info->type != IRQT_PIRQ);", "\treturn info->u.pirq.flags & PIRQ_NEEDS_EOI;\n}", "static void bind_evtchn_to_cpu(evtchn_port_t evtchn, unsigned int cpu)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(irq == -1);\n#ifdef CONFIG_SMP\n\tcpumask_copy(irq_get_affinity_mask(irq), cpumask_of(cpu));\n#endif\n\txen_evtchn_port_bind_to_cpu(info, cpu);", "\tinfo->cpu = cpu;\n}", "/**\n * notify_remote_via_irq - send event to remote end of event channel via irq\n * @irq: irq of event channel to send event to\n *\n * Unlike notify_remote_via_evtchn(), this is safe to use across\n * save/restore. Notifications on a broken connection are silently\n * dropped.\n */\nvoid notify_remote_via_irq(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tnotify_remote_via_evtchn(evtchn);\n}\nEXPORT_SYMBOL_GPL(notify_remote_via_irq);", "static void xen_irq_init(unsigned irq)\n{\n\tstruct irq_info *info;\n#ifdef CONFIG_SMP\n\t/* By default all event channels notify CPU#0. */\n\tcpumask_copy(irq_get_affinity_mask(irq), cpumask_of(0));\n#endif", "\tinfo = kzalloc(sizeof(*info), GFP_KERNEL);\n\tif (info == NULL)\n\t\tpanic(\"Unable to allocate metadata for IRQ%d\\n\", irq);", "\tinfo->type = IRQT_UNBOUND;\n\tinfo->refcnt = -1;", "\tset_info_for_irq(irq, info);", "\tlist_add_tail(&info->list, &xen_irq_list_head);\n}", "static int __must_check xen_allocate_irqs_dynamic(int nvec)\n{\n\tint i, irq = irq_alloc_descs(-1, 0, nvec, -1);", "\tif (irq >= 0) {\n\t\tfor (i = 0; i < nvec; i++)\n\t\t\txen_irq_init(irq + i);\n\t}", "\treturn irq;\n}", "static inline int __must_check xen_allocate_irq_dynamic(void)\n{", "\treturn xen_allocate_irqs_dynamic(1);\n}", "static int __must_check xen_allocate_irq_gsi(unsigned gsi)\n{\n\tint irq;", "\t/*\n\t * A PV guest has no concept of a GSI (since it has no ACPI\n\t * nor access to/knowledge of the physical APICs). Therefore\n\t * all IRQs are dynamically allocated from the entire IRQ\n\t * space.\n\t */\n\tif (xen_pv_domain() && !xen_initial_domain())\n\t\treturn xen_allocate_irq_dynamic();", "\t/* Legacy IRQ descriptors are already allocated by the arch. */\n\tif (gsi < nr_legacy_irqs())\n\t\tirq = gsi;\n\telse\n\t\tirq = irq_alloc_desc_at(gsi, -1);", "\txen_irq_init(irq);", "\treturn irq;\n}", "static void xen_free_irq(unsigned irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tunsigned long flags;", "\n\tif (WARN_ON(!info))\n\t\treturn;\n", "\twrite_lock_irqsave(&evtchn_rwlock, flags);\n", "\tlist_del(&info->list);", "\tset_info_for_irq(irq, NULL);", "\tWARN_ON(info->refcnt > 0);", "\n\twrite_unlock_irqrestore(&evtchn_rwlock, flags);", "\n\tkfree(info);", "\t/* Legacy IRQ descriptors are managed by the arch. */\n\tif (irq < nr_legacy_irqs())\n\t\treturn;", "\tirq_free_desc(irq);\n}", "static void xen_evtchn_close(evtchn_port_t port)\n{\n\tstruct evtchn_close close;", "\tclose.port = port;\n\tif (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close) != 0)\n\t\tBUG();\n}", "static void pirq_query_unmask(int irq)\n{\n\tstruct physdev_irq_status_query irq_status;\n\tstruct irq_info *info = info_for_irq(irq);", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tirq_status.irq = pirq_from_irq(irq);\n\tif (HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query, &irq_status))\n\t\tirq_status.flags = 0;", "\tinfo->u.pirq.flags &= ~PIRQ_NEEDS_EOI;\n\tif (irq_status.flags & XENIRQSTAT_needs_eoi)\n\t\tinfo->u.pirq.flags |= PIRQ_NEEDS_EOI;\n}", "static void eoi_pirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);\n\tstruct physdev_eoi eoi = { .irq = pirq_from_irq(data->irq) };\n\tint rc = 0;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tif (unlikely(irqd_is_setaffinity_pending(data)) &&\n\t likely(!irqd_irq_disabled(data))) {\n\t\tint masked = test_and_set_mask(evtchn);", "\t\tclear_evtchn(evtchn);", "\t\tirq_move_masked_irq(data);", "\t\tif (!masked)\n\t\t\tunmask_evtchn(evtchn);\n\t} else\n\t\tclear_evtchn(evtchn);", "\tif (pirq_needs_eoi(data->irq)) {\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_eoi, &eoi);\n\t\tWARN_ON(rc);\n\t}\n}", "static void mask_ack_pirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n\teoi_pirq(data);\n}", "static unsigned int __startup_pirq(unsigned int irq)\n{\n\tstruct evtchn_bind_pirq bind_pirq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tint rc;", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tif (VALID_EVTCHN(evtchn))\n\t\tgoto out;", "\tbind_pirq.pirq = pirq_from_irq(irq);\n\t/* NB. We are happy to share unless we are probing. */\n\tbind_pirq.flags = info->u.pirq.flags & PIRQ_SHAREABLE ?\n\t\t\t\t\tBIND_PIRQ__WILL_SHARE : 0;\n\trc = HYPERVISOR_event_channel_op(EVTCHNOP_bind_pirq, &bind_pirq);\n\tif (rc != 0) {\n\t\tpr_warn(\"Failed to obtain physical IRQ %d\\n\", irq);\n\t\treturn 0;\n\t}\n\tevtchn = bind_pirq.port;", "\tpirq_query_unmask(irq);", "\trc = set_evtchn_to_irq(evtchn, irq);\n\tif (rc)\n\t\tgoto err;", "\tinfo->evtchn = evtchn;\n\tbind_evtchn_to_cpu(evtchn, 0);", "\trc = xen_evtchn_port_setup(info);\n\tif (rc)\n\t\tgoto err;", "out:\n\tunmask_evtchn(evtchn);\n\teoi_pirq(irq_get_irq_data(irq));", "\treturn 0;", "err:\n\tpr_err(\"irq%d: Failed to set port to irq mapping (%d)\\n\", irq, rc);\n\txen_evtchn_close(evtchn);\n\treturn 0;\n}", "static unsigned int startup_pirq(struct irq_data *data)\n{\n\treturn __startup_pirq(data->irq);\n}", "static void shutdown_pirq(struct irq_data *data)\n{\n\tunsigned int irq = data->irq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tBUG_ON(info->type != IRQT_PIRQ);", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tmask_evtchn(evtchn);\n\txen_evtchn_close(evtchn);\n\txen_irq_info_cleanup(info);\n}", "static void enable_pirq(struct irq_data *data)\n{\n\tenable_dynirq(data);\n}", "static void disable_pirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n}", "int xen_irq_from_gsi(unsigned gsi)\n{\n\tstruct irq_info *info;", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;", "\t\tif (info->u.pirq.gsi == gsi)\n\t\t\treturn info->irq;\n\t}", "\treturn -1;\n}\nEXPORT_SYMBOL_GPL(xen_irq_from_gsi);", "static void __unbind_from_irq(unsigned int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (info->refcnt > 0) {\n\t\tinfo->refcnt--;\n\t\tif (info->refcnt != 0)\n\t\t\treturn;\n\t}", "\tif (VALID_EVTCHN(evtchn)) {\n\t\tunsigned int cpu = cpu_from_irq(irq);", "\t\txen_evtchn_close(evtchn);", "\t\tswitch (type_from_irq(irq)) {\n\t\tcase IRQT_VIRQ:\n\t\t\tper_cpu(virq_to_irq, cpu)[virq_from_irq(irq)] = -1;\n\t\t\tbreak;\n\t\tcase IRQT_IPI:\n\t\t\tper_cpu(ipi_to_irq, cpu)[ipi_from_irq(irq)] = -1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}", "\t\txen_irq_info_cleanup(info);\n\t}", "\txen_free_irq(irq);\n}", "/*\n * Do not make any assumptions regarding the relationship between the\n * IRQ number returned here and the Xen pirq argument.\n *\n * Note: We don't assign an event channel until the irq actually started\n * up. Return an existing irq if we've already got one for the gsi.\n *\n * Shareable implies level triggered, not shareable implies edge\n * triggered here.\n */\nint xen_bind_pirq_gsi_to_irq(unsigned gsi,\n\t\t\t unsigned pirq, int shareable, char *name)\n{\n\tint irq = -1;\n\tstruct physdev_irq irq_op;\n\tint ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = xen_irq_from_gsi(gsi);\n\tif (irq != -1) {\n\t\tpr_info(\"%s: returning irq %d for gsi %u\\n\",\n\t\t\t__func__, irq, gsi);\n\t\tgoto out;\n\t}", "\tirq = xen_allocate_irq_gsi(gsi);\n\tif (irq < 0)\n\t\tgoto out;", "\tirq_op.irq = irq;\n\tirq_op.vector = 0;", "\t/* Only the privileged domain can do this. For non-priv, the pcifront\n\t * driver provides a PCI bus that does the call to do exactly\n\t * this in the priv domain. */\n\tif (xen_initial_domain() &&\n\t HYPERVISOR_physdev_op(PHYSDEVOP_alloc_irq_vector, &irq_op)) {\n\t\txen_free_irq(irq);\n\t\tirq = -ENOSPC;\n\t\tgoto out;\n\t}", "\tret = xen_irq_info_pirq_setup(irq, 0, pirq, gsi, DOMID_SELF,\n\t\t\t shareable ? PIRQ_SHAREABLE : 0);\n\tif (ret < 0) {\n\t\t__unbind_from_irq(irq);\n\t\tirq = ret;\n\t\tgoto out;\n\t}", "\tpirq_query_unmask(irq);\n\t/* We try to use the handler with the appropriate semantic for the\n\t * type of interrupt: if the interrupt is an edge triggered\n\t * interrupt we use handle_edge_irq.\n\t *\n\t * On the other hand if the interrupt is level triggered we use\n\t * handle_fasteoi_irq like the native code does for this kind of\n\t * interrupts.\n\t *\n\t * Depending on the Xen version, pirq_needs_eoi might return true\n\t * not only for level triggered interrupts but for edge triggered\n\t * interrupts too. In any case Xen always honors the eoi mechanism,\n\t * not injecting any more pirqs of the same kind if the first one\n\t * hasn't received an eoi yet. Therefore using the fasteoi handler\n\t * is the right choice either way.\n\t */\n\tif (shareable)\n\t\tirq_set_chip_and_handler_name(irq, &xen_pirq_chip,\n\t\t\t\thandle_fasteoi_irq, name);\n\telse\n\t\tirq_set_chip_and_handler_name(irq, &xen_pirq_chip,\n\t\t\t\thandle_edge_irq, name);", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "#ifdef CONFIG_PCI_MSI\nint xen_allocate_pirq_msi(struct pci_dev *dev, struct msi_desc *msidesc)\n{\n\tint rc;\n\tstruct physdev_get_free_pirq op_get_free_pirq;", "\top_get_free_pirq.type = MAP_PIRQ_TYPE_MSI;\n\trc = HYPERVISOR_physdev_op(PHYSDEVOP_get_free_pirq, &op_get_free_pirq);", "\tWARN_ONCE(rc == -ENOSYS,\n\t\t \"hypervisor does not support the PHYSDEVOP_get_free_pirq interface\\n\");", "\treturn rc ? -1 : op_get_free_pirq.pirq;\n}", "int xen_bind_pirq_msi_to_irq(struct pci_dev *dev, struct msi_desc *msidesc,\n\t\t\t int pirq, int nvec, const char *name, domid_t domid)\n{\n\tint i, irq, ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = xen_allocate_irqs_dynamic(nvec);\n\tif (irq < 0)\n\t\tgoto out;", "\tfor (i = 0; i < nvec; i++) {\n\t\tirq_set_chip_and_handler_name(irq + i, &xen_pirq_chip, handle_edge_irq, name);", "\t\tret = xen_irq_info_pirq_setup(irq + i, 0, pirq + i, 0, domid,\n\t\t\t\t\t i == 0 ? 0 : PIRQ_MSI_GROUP);\n\t\tif (ret < 0)\n\t\t\tgoto error_irq;\n\t}", "\tret = irq_set_msi_desc(irq, msidesc);\n\tif (ret < 0)\n\t\tgoto error_irq;\nout:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn irq;\nerror_irq:\n\twhile (nvec--)\n\t\t__unbind_from_irq(irq + nvec);\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn ret;\n}\n#endif", "int xen_destroy_irq(int irq)\n{\n\tstruct physdev_unmap_pirq unmap_irq;\n\tstruct irq_info *info = info_for_irq(irq);\n\tint rc = -ENOENT;", "\tmutex_lock(&irq_mapping_update_lock);", "\t/*\n\t * If trying to remove a vector in a MSI group different\n\t * than the first one skip the PIRQ unmap unless this vector\n\t * is the first one in the group.\n\t */\n\tif (xen_initial_domain() && !(info->u.pirq.flags & PIRQ_MSI_GROUP)) {\n\t\tunmap_irq.pirq = info->u.pirq.pirq;\n\t\tunmap_irq.domid = info->u.pirq.domid;\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_unmap_pirq, &unmap_irq);\n\t\t/* If another domain quits without making the pci_disable_msix\n\t\t * call, the Xen hypervisor takes care of freeing the PIRQs\n\t\t * (free_domain_pirqs).\n\t\t */\n\t\tif ((rc == -ESRCH && info->u.pirq.domid != DOMID_SELF))\n\t\t\tpr_info(\"domain %d does not have %d anymore\\n\",\n\t\t\t\tinfo->u.pirq.domid, info->u.pirq.pirq);\n\t\telse if (rc) {\n\t\t\tpr_warn(\"unmap irq failed %d\\n\", rc);\n\t\t\tgoto out;\n\t\t}\n\t}", "\txen_free_irq(irq);", "out:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn rc;\n}", "int xen_irq_from_pirq(unsigned pirq)\n{\n\tint irq;", "\tstruct irq_info *info;", "\tmutex_lock(&irq_mapping_update_lock);", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;\n\t\tirq = info->irq;\n\t\tif (info->u.pirq.pirq == pirq)\n\t\t\tgoto out;\n\t}\n\tirq = -1;\nout:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "\nint xen_pirq_from_irq(unsigned irq)\n{\n\treturn pirq_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(xen_pirq_from_irq);", "int bind_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tint irq;\n\tint ret;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -ENOMEM;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = get_evtchn_to_irq(evtchn);", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tirq_set_chip_and_handler_name(irq, &xen_dynamic_chip,\n\t\t\t\t\t handle_edge_irq, \"event\");", "\t\tret = xen_irq_info_evtchn_setup(irq, evtchn);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}\n\t\t/* New interdomain events are bound to VCPU 0. */\n\t\tbind_evtchn_to_cpu(evtchn, 0);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_EVTCHN);\n\t}", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_evtchn_to_irq);", "static int bind_ipi_to_irq(unsigned int ipi, unsigned int cpu)\n{\n\tstruct evtchn_bind_ipi bind_ipi;\n\tevtchn_port_t evtchn;\n\tint ret, irq;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = per_cpu(ipi_to_irq, cpu)[ipi];", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tirq_set_chip_and_handler_name(irq, &xen_percpu_chip,\n\t\t\t\t\t handle_percpu_irq, \"ipi\");", "\t\tbind_ipi.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi,\n\t\t\t\t\t\t&bind_ipi) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_ipi.port;", "\t\tret = xen_irq_info_ipi_setup(cpu, irq, evtchn, ipi);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_IPI);\n\t}", " out:\n\tmutex_unlock(&irq_mapping_update_lock);\n\treturn irq;\n}", "int bind_interdomain_evtchn_to_irq(unsigned int remote_domain,\n\t\t\t\t evtchn_port_t remote_port)\n{\n\tstruct evtchn_bind_interdomain bind_interdomain;\n\tint err;", "\tbind_interdomain.remote_dom = remote_domain;\n\tbind_interdomain.remote_port = remote_port;", "\terr = HYPERVISOR_event_channel_op(EVTCHNOP_bind_interdomain,\n\t\t\t\t\t &bind_interdomain);", "\treturn err ? : bind_evtchn_to_irq(bind_interdomain.local_port);\n}\nEXPORT_SYMBOL_GPL(bind_interdomain_evtchn_to_irq);", "static int find_virq(unsigned int virq, unsigned int cpu, evtchn_port_t *evtchn)\n{\n\tstruct evtchn_status status;\n\tevtchn_port_t port;\n\tint rc = -ENOENT;", "\tmemset(&status, 0, sizeof(status));\n\tfor (port = 0; port < xen_evtchn_max_channels(); port++) {\n\t\tstatus.dom = DOMID_SELF;\n\t\tstatus.port = port;\n\t\trc = HYPERVISOR_event_channel_op(EVTCHNOP_status, &status);\n\t\tif (rc < 0)\n\t\t\tcontinue;\n\t\tif (status.status != EVTCHNSTAT_virq)\n\t\t\tcontinue;\n\t\tif (status.u.virq == virq && status.vcpu == xen_vcpu_nr(cpu)) {\n\t\t\t*evtchn = port;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn rc;\n}", "/**\n * xen_evtchn_nr_channels - number of usable event channel ports\n *\n * This may be less than the maximum supported by the current\n * hypervisor ABI. Use xen_evtchn_max_channels() for the maximum\n * supported.\n */\nunsigned xen_evtchn_nr_channels(void)\n{\n return evtchn_ops->nr_channels();\n}\nEXPORT_SYMBOL_GPL(xen_evtchn_nr_channels);", "int bind_virq_to_irq(unsigned int virq, unsigned int cpu, bool percpu)\n{\n\tstruct evtchn_bind_virq bind_virq;\n\tevtchn_port_t evtchn = 0;\n\tint irq, ret;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = per_cpu(virq_to_irq, cpu)[virq];", "\tif (irq == -1) {\n\t\tirq = xen_allocate_irq_dynamic();\n\t\tif (irq < 0)\n\t\t\tgoto out;", "\t\tif (percpu)\n\t\t\tirq_set_chip_and_handler_name(irq, &xen_percpu_chip,\n\t\t\t\t\t\t handle_percpu_irq, \"virq\");\n\t\telse\n\t\t\tirq_set_chip_and_handler_name(irq, &xen_dynamic_chip,\n\t\t\t\t\t\t handle_edge_irq, \"virq\");", "\t\tbind_virq.virq = virq;\n\t\tbind_virq.vcpu = xen_vcpu_nr(cpu);\n\t\tret = HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq,\n\t\t\t\t\t\t&bind_virq);\n\t\tif (ret == 0)\n\t\t\tevtchn = bind_virq.port;\n\t\telse {\n\t\t\tif (ret == -EEXIST)\n\t\t\t\tret = find_virq(virq, cpu, &evtchn);\n\t\t\tBUG_ON(ret < 0);\n\t\t}", "\t\tret = xen_irq_info_virq_setup(cpu, irq, evtchn, virq);\n\t\tif (ret < 0) {\n\t\t\t__unbind_from_irq(irq);\n\t\t\tirq = ret;\n\t\t\tgoto out;\n\t\t}", "\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t} else {\n\t\tstruct irq_info *info = info_for_irq(irq);\n\t\tWARN_ON(info == NULL || info->type != IRQT_VIRQ);\n\t}", "out:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn irq;\n}", "static void unbind_from_irq(unsigned int irq)\n{\n\tmutex_lock(&irq_mapping_update_lock);\n\t__unbind_from_irq(irq);\n\tmutex_unlock(&irq_mapping_update_lock);\n}", "int bind_evtchn_to_irqhandler(evtchn_port_t evtchn,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags,\n\t\t\t const char *devname, void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_evtchn_to_irq(evtchn);\n\tif (irq < 0)\n\t\treturn irq;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_evtchn_to_irqhandler);", "int bind_interdomain_evtchn_to_irqhandler(unsigned int remote_domain,\n\t\t\t\t\t evtchn_port_t remote_port,\n\t\t\t\t\t irq_handler_t handler,\n\t\t\t\t\t unsigned long irqflags,\n\t\t\t\t\t const char *devname,\n\t\t\t\t\t void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_interdomain_evtchn_to_irq(remote_domain, remote_port);\n\tif (irq < 0)\n\t\treturn irq;", "\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_interdomain_evtchn_to_irqhandler);", "int bind_virq_to_irqhandler(unsigned int virq, unsigned int cpu,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags, const char *devname, void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_virq_to_irq(virq, cpu, irqflags & IRQF_PERCPU);\n\tif (irq < 0)\n\t\treturn irq;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}\nEXPORT_SYMBOL_GPL(bind_virq_to_irqhandler);", "int bind_ipi_to_irqhandler(enum ipi_vector ipi,\n\t\t\t unsigned int cpu,\n\t\t\t irq_handler_t handler,\n\t\t\t unsigned long irqflags,\n\t\t\t const char *devname,\n\t\t\t void *dev_id)\n{\n\tint irq, retval;", "\tirq = bind_ipi_to_irq(ipi, cpu);\n\tif (irq < 0)\n\t\treturn irq;", "\tirqflags |= IRQF_NO_SUSPEND | IRQF_FORCE_RESUME | IRQF_EARLY_RESUME;\n\tretval = request_irq(irq, handler, irqflags, devname, dev_id);\n\tif (retval != 0) {\n\t\tunbind_from_irq(irq);\n\t\treturn retval;\n\t}", "\treturn irq;\n}", "void unbind_from_irqhandler(unsigned int irq, void *dev_id)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (WARN_ON(!info))\n\t\treturn;\n\tfree_irq(irq, dev_id);\n\tunbind_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(unbind_from_irqhandler);", "/**\n * xen_set_irq_priority() - set an event channel priority.\n * @irq:irq bound to an event channel.\n * @priority: priority between XEN_IRQ_PRIORITY_MAX and XEN_IRQ_PRIORITY_MIN.\n */\nint xen_set_irq_priority(unsigned irq, unsigned priority)\n{\n\tstruct evtchn_set_priority set_priority;", "\tset_priority.port = evtchn_from_irq(irq);\n\tset_priority.priority = priority;", "\treturn HYPERVISOR_event_channel_op(EVTCHNOP_set_priority,\n\t\t\t\t\t &set_priority);\n}\nEXPORT_SYMBOL_GPL(xen_set_irq_priority);", "int evtchn_make_refcounted(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tstruct irq_info *info;", "\tif (irq == -1)\n\t\treturn -ENOENT;", "\tinfo = info_for_irq(irq);", "\tif (!info)\n\t\treturn -ENOENT;", "\tWARN_ON(info->refcnt != -1);", "\tinfo->refcnt = 1;", "\treturn 0;\n}\nEXPORT_SYMBOL_GPL(evtchn_make_refcounted);", "int evtchn_get(evtchn_port_t evtchn)\n{\n\tint irq;\n\tstruct irq_info *info;\n\tint err = -ENOENT;", "\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -EINVAL;", "\tmutex_lock(&irq_mapping_update_lock);", "\tirq = get_evtchn_to_irq(evtchn);\n\tif (irq == -1)\n\t\tgoto done;", "\tinfo = info_for_irq(irq);", "\tif (!info)\n\t\tgoto done;", "\terr = -EINVAL;\n\tif (info->refcnt <= 0)\n\t\tgoto done;", "\tinfo->refcnt++;\n\terr = 0;\n done:\n\tmutex_unlock(&irq_mapping_update_lock);", "\treturn err;\n}\nEXPORT_SYMBOL_GPL(evtchn_get);", "void evtchn_put(evtchn_port_t evtchn)\n{\n\tint irq = get_evtchn_to_irq(evtchn);\n\tif (WARN_ON(irq == -1))\n\t\treturn;\n\tunbind_from_irq(irq);\n}\nEXPORT_SYMBOL_GPL(evtchn_put);", "void xen_send_IPI_one(unsigned int cpu, enum ipi_vector vector)\n{\n\tint irq;", "#ifdef CONFIG_X86\n\tif (unlikely(vector == XEN_NMI_VECTOR)) {\n\t\tint rc = HYPERVISOR_vcpu_op(VCPUOP_send_nmi, xen_vcpu_nr(cpu),\n\t\t\t\t\t NULL);\n\t\tif (rc < 0)\n\t\t\tprintk(KERN_WARNING \"Sending nmi to CPU%d failed (rc:%d)\\n\", cpu, rc);\n\t\treturn;\n\t}\n#endif\n\tirq = per_cpu(ipi_to_irq, cpu)[vector];\n\tBUG_ON(irq < 0);\n\tnotify_remote_via_irq(irq);\n}", "static void __xen_evtchn_do_upcall(void)\n{\n\tstruct vcpu_info *vcpu_info = __this_cpu_read(xen_vcpu);\n\tint cpu = smp_processor_id();\n", "\tread_lock(&evtchn_rwlock);\n", "\tdo {\n\t\tvcpu_info->evtchn_upcall_pending = 0;", "\t\txen_evtchn_handle_events(cpu);", "\t\tBUG_ON(!irqs_disabled());", "\t\tvirt_rmb(); /* Hypervisor can set upcall pending. */", "\t} while (vcpu_info->evtchn_upcall_pending);", "\n\tread_unlock(&evtchn_rwlock);", "}", "void xen_evtchn_do_upcall(struct pt_regs *regs)\n{\n\tstruct pt_regs *old_regs = set_irq_regs(regs);", "\tirq_enter();", "\t__xen_evtchn_do_upcall();", "\tirq_exit();\n\tset_irq_regs(old_regs);\n}", "void xen_hvm_evtchn_do_upcall(void)\n{\n\t__xen_evtchn_do_upcall();\n}\nEXPORT_SYMBOL_GPL(xen_hvm_evtchn_do_upcall);", "/* Rebind a new event channel to an existing irq. */\nvoid rebind_evtchn_irq(evtchn_port_t evtchn, int irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);", "\tif (WARN_ON(!info))\n\t\treturn;", "\t/* Make sure the irq is masked, since the new event channel\n\t will also be masked. */\n\tdisable_irq(irq);", "\tmutex_lock(&irq_mapping_update_lock);", "\t/* After resume the irq<->evtchn mappings are all cleared out */\n\tBUG_ON(get_evtchn_to_irq(evtchn) != -1);\n\t/* Expect irq to have been bound before,\n\t so there should be a proper type */\n\tBUG_ON(info->type == IRQT_UNBOUND);", "\t(void)xen_irq_info_evtchn_setup(irq, evtchn);", "\tmutex_unlock(&irq_mapping_update_lock);", " bind_evtchn_to_cpu(evtchn, info->cpu);\n\t/* This will be deferred until interrupt is processed */\n\tirq_set_affinity(irq, cpumask_of(info->cpu));", "\t/* Unmask the event channel. */\n\tenable_irq(irq);\n}", "/* Rebind an evtchn so that it gets delivered to a specific cpu */\nstatic int xen_rebind_evtchn_to_cpu(evtchn_port_t evtchn, unsigned int tcpu)\n{\n\tstruct evtchn_bind_vcpu bind_vcpu;\n\tint masked;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn -1;", "\tif (!xen_support_evtchn_rebind())\n\t\treturn -1;", "\t/* Send future instances of this interrupt to other vcpu. */\n\tbind_vcpu.port = evtchn;\n\tbind_vcpu.vcpu = xen_vcpu_nr(tcpu);", "\t/*\n\t * Mask the event while changing the VCPU binding to prevent\n\t * it being delivered on an unexpected VCPU.\n\t */\n\tmasked = test_and_set_mask(evtchn);", "\t/*\n\t * If this fails, it usually just indicates that we're dealing with a\n\t * virq or IPI channel, which don't actually need to be rebound. Ignore\n\t * it, but don't do the xenlinux-level rebind in that case.\n\t */\n\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_vcpu, &bind_vcpu) >= 0)\n\t\tbind_evtchn_to_cpu(evtchn, tcpu);", "\tif (!masked)\n\t\tunmask_evtchn(evtchn);", "\treturn 0;\n}", "static int set_affinity_irq(struct irq_data *data, const struct cpumask *dest,\n\t\t\t bool force)\n{\n\tunsigned tcpu = cpumask_first_and(dest, cpu_online_mask);\n\tint ret = xen_rebind_evtchn_to_cpu(evtchn_from_irq(data->irq), tcpu);", "\tif (!ret)\n\t\tirq_data_update_effective_affinity(data, cpumask_of(tcpu));", "\treturn ret;\n}", "/* To be called with desc->lock held. */\nint xen_set_affinity_evtchn(struct irq_desc *desc, unsigned int tcpu)\n{\n\tstruct irq_data *d = irq_desc_get_irq_data(desc);", "\treturn set_affinity_irq(d, cpumask_of(tcpu), false);\n}\nEXPORT_SYMBOL_GPL(xen_set_affinity_evtchn);", "static void enable_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tunmask_evtchn(evtchn);\n}", "static void disable_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tmask_evtchn(evtchn);\n}", "static void ack_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn;", "\tif (unlikely(irqd_is_setaffinity_pending(data)) &&\n\t likely(!irqd_irq_disabled(data))) {\n\t\tint masked = test_and_set_mask(evtchn);", "\t\tclear_evtchn(evtchn);", "\t\tirq_move_masked_irq(data);", "\t\tif (!masked)\n\t\t\tunmask_evtchn(evtchn);\n\t} else\n\t\tclear_evtchn(evtchn);\n}", "static void mask_ack_dynirq(struct irq_data *data)\n{\n\tdisable_dynirq(data);\n\tack_dynirq(data);\n}", "static int retrigger_dynirq(struct irq_data *data)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(data->irq);\n\tint masked;", "\tif (!VALID_EVTCHN(evtchn))\n\t\treturn 0;", "\tmasked = test_and_set_mask(evtchn);\n\tset_evtchn(evtchn);\n\tif (!masked)\n\t\tunmask_evtchn(evtchn);", "\treturn 1;\n}", "static void restore_pirqs(void)\n{\n\tint pirq, rc, irq, gsi;\n\tstruct physdev_map_pirq map_irq;\n\tstruct irq_info *info;", "\tlist_for_each_entry(info, &xen_irq_list_head, list) {\n\t\tif (info->type != IRQT_PIRQ)\n\t\t\tcontinue;", "\t\tpirq = info->u.pirq.pirq;\n\t\tgsi = info->u.pirq.gsi;\n\t\tirq = info->irq;", "\t\t/* save/restore of PT devices doesn't work, so at this point the\n\t\t * only devices present are GSI based emulated devices */\n\t\tif (!gsi)\n\t\t\tcontinue;", "\t\tmap_irq.domid = DOMID_SELF;\n\t\tmap_irq.type = MAP_PIRQ_TYPE_GSI;\n\t\tmap_irq.index = gsi;\n\t\tmap_irq.pirq = pirq;", "\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_map_pirq, &map_irq);\n\t\tif (rc) {\n\t\t\tpr_warn(\"xen map irq failed gsi=%d irq=%d pirq=%d rc=%d\\n\",\n\t\t\t\tgsi, irq, pirq, rc);\n\t\t\txen_free_irq(irq);\n\t\t\tcontinue;\n\t\t}", "\t\tprintk(KERN_DEBUG \"xen: --> irq=%d, pirq=%d\\n\", irq, map_irq.pirq);", "\t\t__startup_pirq(irq);\n\t}\n}", "static void restore_cpu_virqs(unsigned int cpu)\n{\n\tstruct evtchn_bind_virq bind_virq;\n\tevtchn_port_t evtchn;\n\tint virq, irq;", "\tfor (virq = 0; virq < NR_VIRQS; virq++) {\n\t\tif ((irq = per_cpu(virq_to_irq, cpu)[virq]) == -1)\n\t\t\tcontinue;", "\t\tBUG_ON(virq_from_irq(irq) != virq);", "\t\t/* Get a new binding from Xen. */\n\t\tbind_virq.virq = virq;\n\t\tbind_virq.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq,\n\t\t\t\t\t\t&bind_virq) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_virq.port;", "\t\t/* Record the new mapping. */\n\t\t(void)xen_irq_info_virq_setup(cpu, irq, evtchn, virq);\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t}\n}", "static void restore_cpu_ipis(unsigned int cpu)\n{\n\tstruct evtchn_bind_ipi bind_ipi;\n\tevtchn_port_t evtchn;\n\tint ipi, irq;", "\tfor (ipi = 0; ipi < XEN_NR_IPIS; ipi++) {\n\t\tif ((irq = per_cpu(ipi_to_irq, cpu)[ipi]) == -1)\n\t\t\tcontinue;", "\t\tBUG_ON(ipi_from_irq(irq) != ipi);", "\t\t/* Get a new binding from Xen. */\n\t\tbind_ipi.vcpu = xen_vcpu_nr(cpu);\n\t\tif (HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi,\n\t\t\t\t\t\t&bind_ipi) != 0)\n\t\t\tBUG();\n\t\tevtchn = bind_ipi.port;", "\t\t/* Record the new mapping. */\n\t\t(void)xen_irq_info_ipi_setup(cpu, irq, evtchn, ipi);\n\t\tbind_evtchn_to_cpu(evtchn, cpu);\n\t}\n}", "/* Clear an irq's pending state, in preparation for polling on it */\nvoid xen_clear_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tclear_evtchn(evtchn);\n}\nEXPORT_SYMBOL(xen_clear_irq_pending);\nvoid xen_set_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn))\n\t\tset_evtchn(evtchn);\n}", "bool xen_test_irq_pending(int irq)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);\n\tbool ret = false;", "\tif (VALID_EVTCHN(evtchn))\n\t\tret = test_evtchn(evtchn);", "\treturn ret;\n}", "/* Poll waiting for an irq to become pending with timeout. In the usual case,\n * the irq will be disabled so it won't deliver an interrupt. */\nvoid xen_poll_irq_timeout(int irq, u64 timeout)\n{\n\tevtchn_port_t evtchn = evtchn_from_irq(irq);", "\tif (VALID_EVTCHN(evtchn)) {\n\t\tstruct sched_poll poll;", "\t\tpoll.nr_ports = 1;\n\t\tpoll.timeout = timeout;\n\t\tset_xen_guest_handle(poll.ports, &evtchn);", "\t\tif (HYPERVISOR_sched_op(SCHEDOP_poll, &poll) != 0)\n\t\t\tBUG();\n\t}\n}\nEXPORT_SYMBOL(xen_poll_irq_timeout);\n/* Poll waiting for an irq to become pending. In the usual case, the\n * irq will be disabled so it won't deliver an interrupt. */\nvoid xen_poll_irq(int irq)\n{\n\txen_poll_irq_timeout(irq, 0 /* no timeout */);\n}", "/* Check whether the IRQ line is shared with other guests. */\nint xen_test_irq_shared(int irq)\n{\n\tstruct irq_info *info = info_for_irq(irq);\n\tstruct physdev_irq_status_query irq_status;", "\tif (WARN_ON(!info))\n\t\treturn -ENOENT;", "\tirq_status.irq = info->u.pirq.pirq;", "\tif (HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query, &irq_status))\n\t\treturn 0;\n\treturn !(irq_status.flags & XENIRQSTAT_shared);\n}\nEXPORT_SYMBOL_GPL(xen_test_irq_shared);", "void xen_irq_resume(void)\n{\n\tunsigned int cpu;\n\tstruct irq_info *info;", "\t/* New event-channel space is not 'live' yet. */\n\txen_evtchn_resume();", "\t/* No IRQ <-> event-channel mappings. */\n\tlist_for_each_entry(info, &xen_irq_list_head, list)\n\t\tinfo->evtchn = 0; /* zap event-channel binding */", "\tclear_evtchn_to_irq_all();", "\tfor_each_possible_cpu(cpu) {\n\t\trestore_cpu_virqs(cpu);\n\t\trestore_cpu_ipis(cpu);\n\t}", "\trestore_pirqs();\n}", "static struct irq_chip xen_dynamic_chip __read_mostly = {\n\t.name\t\t\t= \"xen-dyn\",", "\t.irq_disable\t\t= disable_dynirq,\n\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= ack_dynirq,\n\t.irq_mask_ack\t\t= mask_ack_dynirq,", "\t.irq_set_affinity\t= set_affinity_irq,\n\t.irq_retrigger\t\t= retrigger_dynirq,\n};", "static struct irq_chip xen_pirq_chip __read_mostly = {\n\t.name\t\t\t= \"xen-pirq\",", "\t.irq_startup\t\t= startup_pirq,\n\t.irq_shutdown\t\t= shutdown_pirq,\n\t.irq_enable\t\t= enable_pirq,\n\t.irq_disable\t\t= disable_pirq,", "\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= eoi_pirq,\n\t.irq_eoi\t\t= eoi_pirq,\n\t.irq_mask_ack\t\t= mask_ack_pirq,", "\t.irq_set_affinity\t= set_affinity_irq,", "\t.irq_retrigger\t\t= retrigger_dynirq,\n};", "static struct irq_chip xen_percpu_chip __read_mostly = {\n\t.name\t\t\t= \"xen-percpu\",", "\t.irq_disable\t\t= disable_dynirq,\n\t.irq_mask\t\t= disable_dynirq,\n\t.irq_unmask\t\t= enable_dynirq,", "\t.irq_ack\t\t= ack_dynirq,\n};", "int xen_set_callback_via(uint64_t via)\n{\n\tstruct xen_hvm_param a;\n\ta.domid = DOMID_SELF;\n\ta.index = HVM_PARAM_CALLBACK_IRQ;\n\ta.value = via;\n\treturn HYPERVISOR_hvm_op(HVMOP_set_param, &a);\n}\nEXPORT_SYMBOL_GPL(xen_set_callback_via);", "#ifdef CONFIG_XEN_PVHVM\n/* Vector callbacks are better than PCI interrupts to receive event\n * channel notifications because we can receive vector callbacks on any\n * vcpu and we don't need PCI support or APIC interactions. */\nvoid xen_setup_callback_vector(void)\n{\n\tuint64_t callback_via;", "\tif (xen_have_vector_callback) {\n\t\tcallback_via = HVM_CALLBACK_VECTOR(HYPERVISOR_CALLBACK_VECTOR);\n\t\tif (xen_set_callback_via(callback_via)) {\n\t\t\tpr_err(\"Request for Xen HVM callback vector failed\\n\");\n\t\t\txen_have_vector_callback = 0;\n\t\t}\n\t}\n}", "static __init void xen_alloc_callback_vector(void)\n{\n\tif (!xen_have_vector_callback)\n\t\treturn;", "\tpr_info(\"Xen HVM callback vector for event delivery is enabled\\n\");\n\talloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_xen_hvm_callback);\n}\n#else\nvoid xen_setup_callback_vector(void) {}\nstatic inline void xen_alloc_callback_vector(void) {}\n#endif", "#undef MODULE_PARAM_PREFIX\n#define MODULE_PARAM_PREFIX \"xen.\"", "static bool fifo_events = true;\nmodule_param(fifo_events, bool, 0);", "void __init xen_init_IRQ(void)\n{\n\tint ret = -EINVAL;\n\tevtchn_port_t evtchn;", "\tif (fifo_events)\n\t\tret = xen_evtchn_fifo_init();\n\tif (ret < 0)\n\t\txen_evtchn_2l_init();", "\tevtchn_to_irq = kcalloc(EVTCHN_ROW(xen_evtchn_max_channels()),\n\t\t\t\tsizeof(*evtchn_to_irq), GFP_KERNEL);\n\tBUG_ON(!evtchn_to_irq);", "\t/* No event channels are 'live' right now. */\n\tfor (evtchn = 0; evtchn < xen_evtchn_nr_channels(); evtchn++)\n\t\tmask_evtchn(evtchn);", "\tpirq_needs_eoi = pirq_needs_eoi_flag;", "#ifdef CONFIG_X86\n\tif (xen_pv_domain()) {\n\t\tif (xen_initial_domain())\n\t\t\tpci_xen_initial_domain();\n\t}\n\tif (xen_feature(XENFEAT_hvm_callback_vector)) {\n\t\txen_setup_callback_vector();\n\t\txen_alloc_callback_vector();\n\t}", "\tif (xen_hvm_domain()) {\n\t\tnative_init_IRQ();\n\t\t/* pci_xen_hvm_init must be called after native_init_IRQ so that\n\t\t * __acpi_register_gsi can point at the right function */\n\t\tpci_xen_hvm_init();\n\t} else {\n\t\tint rc;\n\t\tstruct physdev_pirq_eoi_gmfn eoi_gmfn;", "\t\tpirq_eoi_map = (void *)__get_free_page(GFP_KERNEL|__GFP_ZERO);\n\t\teoi_gmfn.gmfn = virt_to_gfn(pirq_eoi_map);\n\t\trc = HYPERVISOR_physdev_op(PHYSDEVOP_pirq_eoi_gmfn_v2, &eoi_gmfn);\n\t\tif (rc != 0) {\n\t\t\tfree_page((unsigned long) pirq_eoi_map);\n\t\t\tpirq_eoi_map = NULL;\n\t\t} else\n\t\t\tpirq_needs_eoi = pirq_check_eoi_map;\n\t}\n#endif\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1245], "buggy_code_start_loc": [35], "filenames": ["drivers/xen/events/events_base.c"], "fixing_code_end_loc": [1277], "fixing_code_start_loc": [36], "message": "An issue was discovered in the Linux kernel through 5.9.1, as used with Xen through 4.14.x. drivers/xen/events/events_base.c allows event-channel removal during the event-handling loop (a race condition). This can cause a use-after-free or NULL pointer dereference, as demonstrated by a dom0 crash via events for an in-reconfiguration paravirtualized device, aka CID-073d0552ead5.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7E1EBA7-1B6D-4A6D-ADFF-2B556573F073", "versionEndExcluding": null, "versionEndIncluding": "5.9.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the Linux kernel through 5.9.1, as used with Xen through 4.14.x. drivers/xen/events/events_base.c allows event-channel removal during the event-handling loop (a race condition). This can cause a use-after-free or NULL pointer dereference, as demonstrated by a dom0 crash via events for an in-reconfiguration paravirtualized device, aka CID-073d0552ead5."}, {"lang": "es", "value": "Se detect\u00f3 un problema en el kernel de Linux versiones hasta 5.9.1, como es usado con Xen versiones hasta 4.14.x.&#xa0;El archivo drivers/xen/events/events_base.c permite la eliminaci\u00f3n del canal de eventos durante el ciclo de manejo de eventos (una condici\u00f3n de carrera).&#xa0;Esto puede causar una desreferencia del puntero NULL y un uso de la memoria previamente liberada como es demostrado por un bloqueo dom0 por medio de eventos para un dispositivo paravirtualizado en reconfiguraci\u00f3n, tambi\u00e9n se conoce como CID-073d0552ead5"}], "evaluatorComment": null, "id": "CVE-2020-27675", "lastModified": "2022-04-26T16:29:52.957", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.7, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 4.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.0, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-10-22T21:15:14.153", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2021/01/19/3"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/12/msg00015.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/12/msg00027.html"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/3ZG6TZLD23QO3PV2AN2HB625ZX47ALTT/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/6USZ4APZSBQDHGJLJMHW5JBN4QZV6SKZ/"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GNF2R7FUT4IOJ2RIRGQ7X5R4F4FVVLSR/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202011-06"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://xenbits.xen.org/xsa/advisory-331.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}, {"lang": "en", "value": "CWE-416"}, {"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/073d0552ead5bfc7a3a9c01de590e924f11b5dd2"}, "type": "CWE-362"}
117
Determine whether the {function_name} code is vulnerable or not.
[ "var http = require('http');\nvar fs = require('fs');", "", "\nfs.exists = fs.exists || require('path').exists;", "var SERVER_PORT = 8080;", "var FILE_TYPE_GZIP = 1;", "var FILE_EXT_GZIP = '.gz';\nvar FILE_EXT_CSS = '.css';\nvar FILE_EXT_JS = '.js';", "// GZIP text/plain required to get Chrome XHR to decompress file.\nvar MIME_TYPE_GZIP = 'text/plain';\nvar MIME_TYPE_JS = 'text/javascript';\nvar MIME_TYPE_CSS = 'text/css';", "function log(code, string) {", " //console.log('[' + code + '] ' + string);", "}", "var server = http.createServer(function(request, response) {\n var filePath = request.url;", " // Remove query strings from uri\n if (filePath.indexOf('?') > -1) {\n filePath = filePath.substr(0, filePath.indexOf('?'));\n }\n", " filePath = '.' + filePath;", "\n fs.exists(filePath, function(exists) {\n if (!exists) {", " log(404, filePath)", " response.writeHead(404);\n response.end();", " return;", "", " }", " var mimeType = '';\n var fileType = -1;", " if (filePath.substring(filePath.length - FILE_EXT_GZIP.length) == FILE_EXT_GZIP) {\n fileType = FILE_TYPE_GZIP;\n mimeType = MIME_TYPE_GZIP;\n } else if (filePath.substring(filePath.length - FILE_EXT_JS.length) == FILE_EXT_JS) {\n mimeType = MIME_TYPE_JS;\n } else if (filePath.substring(filePath.length - FILE_EXT_CSS.length) == FILE_EXT_CSS) {\n mimeType = MIME_TYPE_CSS;\n }", " var acceptEncoding = request.headers['accept-encoding'];\n if (!acceptEncoding) {\n acceptEncoding = '';\n }", " fs.readFile(filePath, function(error, content) {\n if (error) {\n log(500, filePath);\n response.writeHead(500);\n response.end();\n } else {\n log(200, filePath);\n var raw = fs.createReadStream(filePath);", " if (fileType == FILE_TYPE_GZIP && acceptEncoding.match(/\\bgzip\\b/)) {\n response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip' });\n } else if (mimeType) {\n response.writeHead(200, { 'Content-Type': mimeType });\n } else {\n response.writeHead(200, {});\n }", " raw.pipe(response);\n }\n });\n });\n});", "server.on('error', function (e) {\n if (e.code == 'EADDRINUSE') {\n console.log('Port ' + SERVER_PORT + ' already in use.');\n }\n});", "server.listen(SERVER_PORT);\nconsole.log('Server listening on port ' + SERVER_PORT);" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [39], "buggy_code_start_loc": [2], "filenames": ["http-server.js"], "fixing_code_end_loc": [57], "fixing_code_start_loc": [3], "message": "A vulnerability was found in saxman maps-js-icoads and classified as critical. This issue affects some unknown processing of the file http-server.js. The manipulation leads to path traversal. The name of the patch is 34b8b0cce2807b119f4cffda2ac48fc8f427d69a. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217643.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:maps-js-icoads_project:maps-js-icoads:*:*:*:*:*:*:*:*", "matchCriteriaId": "59C94DDF-A874-499D-A89D-2A8D7E062E55", "versionEndExcluding": "09-02-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in saxman maps-js-icoads and classified as critical. This issue affects some unknown processing of the file http-server.js. The manipulation leads to path traversal. The name of the patch is 34b8b0cce2807b119f4cffda2ac48fc8f427d69a. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217643."}], "evaluatorComment": null, "id": "CVE-2014-125068", "lastModified": "2023-01-12T16:48:03.227", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T11:15:09.917", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/saxman/maps-js-icoads/commit/34b8b0cce2807b119f4cffda2ac48fc8f427d69a"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217643"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217643"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/saxman/maps-js-icoads/commit/34b8b0cce2807b119f4cffda2ac48fc8f427d69a"}, "type": "CWE-22"}
118
Determine whether the {function_name} code is vulnerable or not.
[ "var http = require('http');\nvar fs = require('fs');", "var path = require('path');", "\nfs.exists = fs.exists || require('path').exists;", "var SERVER_PORT = 8080;", "var FILE_TYPE_GZIP = 1;", "var FILE_EXT_GZIP = '.gz';\nvar FILE_EXT_CSS = '.css';\nvar FILE_EXT_JS = '.js';", "// GZIP text/plain required to get Chrome XHR to decompress file.\nvar MIME_TYPE_GZIP = 'text/plain';\nvar MIME_TYPE_JS = 'text/javascript';\nvar MIME_TYPE_CSS = 'text/css';", "function log(code, string) {", "// console.log('[' + code + '] ' + string);", "}", "var server = http.createServer(function(request, response) {\n var filePath = request.url;", " // Remove query strings from uri\n if (filePath.indexOf('?') > -1) {\n filePath = filePath.substr(0, filePath.indexOf('?'));\n }\n", " // Get the absolute path for the request\n filePath = path.resolve('.' + filePath);", " // Rejesct queries ouside of the server root\n var serverPath = path.resolve('.');\n if (filePath.indexOf(serverPath) != 0 ) {\n log(403, filePath);\n response.writeHeader(403);\n response.end();", " return;\n }", "\n fs.exists(filePath, function(exists) {\n if (!exists) {", " log(404, filePath);", " response.writeHead(404);\n response.end();", " return;", " }", " // Return index.html if directroy requested.\n if (fs.statSync(filePath).isDirectory()) {\n filePath += '/index.html';", " }", " var mimeType = '';\n var fileType = -1;", " if (filePath.substring(filePath.length - FILE_EXT_GZIP.length) == FILE_EXT_GZIP) {\n fileType = FILE_TYPE_GZIP;\n mimeType = MIME_TYPE_GZIP;\n } else if (filePath.substring(filePath.length - FILE_EXT_JS.length) == FILE_EXT_JS) {\n mimeType = MIME_TYPE_JS;\n } else if (filePath.substring(filePath.length - FILE_EXT_CSS.length) == FILE_EXT_CSS) {\n mimeType = MIME_TYPE_CSS;\n }", " var acceptEncoding = request.headers['accept-encoding'];\n if (!acceptEncoding) {\n acceptEncoding = '';\n }", " fs.readFile(filePath, function(error, content) {\n if (error) {\n log(500, filePath);\n response.writeHead(500);\n response.end();\n } else {\n log(200, filePath);\n var raw = fs.createReadStream(filePath);", " if (fileType == FILE_TYPE_GZIP && acceptEncoding.match(/\\bgzip\\b/)) {\n response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip' });\n } else if (mimeType) {\n response.writeHead(200, { 'Content-Type': mimeType });\n } else {\n response.writeHead(200, {});\n }", " raw.pipe(response);\n }\n });\n });\n});", "server.on('error', function (e) {\n if (e.code == 'EADDRINUSE') {\n console.log('Port ' + SERVER_PORT + ' already in use.');\n }\n});", "server.listen(SERVER_PORT);\nconsole.log('Server listening on port ' + SERVER_PORT);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [39], "buggy_code_start_loc": [2], "filenames": ["http-server.js"], "fixing_code_end_loc": [57], "fixing_code_start_loc": [3], "message": "A vulnerability was found in saxman maps-js-icoads and classified as critical. This issue affects some unknown processing of the file http-server.js. The manipulation leads to path traversal. The name of the patch is 34b8b0cce2807b119f4cffda2ac48fc8f427d69a. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217643.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:maps-js-icoads_project:maps-js-icoads:*:*:*:*:*:*:*:*", "matchCriteriaId": "59C94DDF-A874-499D-A89D-2A8D7E062E55", "versionEndExcluding": "09-02-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in saxman maps-js-icoads and classified as critical. This issue affects some unknown processing of the file http-server.js. The manipulation leads to path traversal. The name of the patch is 34b8b0cce2807b119f4cffda2ac48fc8f427d69a. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217643."}], "evaluatorComment": null, "id": "CVE-2014-125068", "lastModified": "2023-01-12T16:48:03.227", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T11:15:09.917", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/saxman/maps-js-icoads/commit/34b8b0cce2807b119f4cffda2ac48fc8f427d69a"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217643"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217643"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/saxman/maps-js-icoads/commit/34b8b0cce2807b119f4cffda2ac48fc8f427d69a"}, "type": "CWE-22"}
118
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http://www.apache.org/licenses/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: xinhua.guo <woshiguo35@gmail.com> |\n +----------------------------------------------------------------------+\n */", "#include \"php_swoole.h\"\n#include \"swoole_serialize.h\"\n#ifdef __SSE2__\n#include <emmintrin.h>\n#endif", "#if PHP_MAJOR_VERSION >= 7\n#define CPINLINE sw_inline", "ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_pack, 0, 0, 1)\nZEND_ARG_INFO(0, data)\nZEND_ARG_INFO(0, flag)\nZEND_END_ARG_INFO()", "ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_unpack, 0, 0, 1)\nZEND_ARG_INFO(0, string)\nZEND_ARG_INFO(0, args)\nZEND_END_ARG_INFO()", "static void swoole_serialize_object(seriaString *buffer, zval *zvalue, size_t start);\nstatic void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue);\nstatic void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t num, long flag);\nstatic void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag);", "static PHP_METHOD(swoole_serialize, pack);\nstatic PHP_METHOD(swoole_serialize, unpack);", "\nstatic const zend_function_entry swoole_serialize_methods[] = {\n PHP_ME(swoole_serialize, pack, arginfo_swoole_serialize_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)\n PHP_ME(swoole_serialize, unpack, arginfo_swoole_serialize_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)\n PHP_FE_END\n};", "zend_class_entry swoole_serialize_ce;\nzend_class_entry *swoole_serialize_class_entry_ptr;", "#define SWOOLE_SERI_EOF \"EOF\"", "", "\nstatic struct _swSeriaG swSeriaG;", "", "\nvoid swoole_serialize_init(int module_number TSRMLS_DC)\n{\n SWOOLE_INIT_CLASS_ENTRY(swoole_serialize_ce, \"swoole_serialize\", \"Swoole\\\\Serialize\", swoole_serialize_methods);\n swoole_serialize_class_entry_ptr = zend_register_internal_class(&swoole_serialize_ce TSRMLS_CC);\n SWOOLE_CLASS_ALIAS(swoole_serialize, \"Swoole\\\\Serialize\");", " // ZVAL_STRING(&swSeriaG.sleep_fname, \"__sleep\");\n zend_string *zstr_sleep = zend_string_init(\"__sleep\", sizeof (\"__sleep\") - 1, 1);\n zend_string *zstr_weekup = zend_string_init(\"__weekup\", sizeof (\"__weekup\") - 1, 1);\n ZVAL_STR(&swSeriaG.sleep_fname, zstr_sleep);\n ZVAL_STR(&swSeriaG.weekup_fname, zstr_weekup);\n // ZVAL_STRING(&swSeriaG.weekup_fname, \"__weekup\");", " memset(&swSeriaG.filter, 0, sizeof (swSeriaG.filter));\n memset(&mini_filter, 0, sizeof (mini_filter));", " REGISTER_LONG_CONSTANT(\"SWOOLE_FAST_PACK\", SW_FAST_PACK, CONST_CS | CONST_PERSISTENT);\n REGISTER_LONG_CONSTANT(\"UNSERIALIZE_OBJECT_TO_ARRAY\", UNSERIALIZE_OBJECT_TO_ARRAY, CONST_CS | CONST_PERSISTENT);\n REGISTER_LONG_CONSTANT(\"UNSERIALIZE_OBJECT_TO_STDCLASS\", UNSERIALIZE_OBJECT_TO_STDCLASS, CONST_CS | CONST_PERSISTENT);\n}", "static CPINLINE int swoole_string_new(size_t size, seriaString *str, zend_uchar type)\n{\n int total = ZEND_MM_ALIGNED_SIZE(_STR_HEADER_SIZE + size + 1);\n str->total = total;\n //escape the header for later\n str->offset = _STR_HEADER_SIZE;\n //zend string addr\n str->buffer = ecalloc(1, total);\n if (!str->buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_ERROR, \"malloc Error: %s [%d]\", strerror(errno), errno);\n }", " SBucketType real_type = {0};\n real_type.data_type = type;\n *(SBucketType*) (str->buffer + str->offset) = real_type;\n str->offset += sizeof (SBucketType);\n return 0;\n}", "static CPINLINE void swoole_check_size(seriaString *str, size_t len)\n{\n int new_size = len + str->offset;\n // int new_size = len + str->offset + 3 + sizeof (zend_ulong); //space 1 for the type and 2 for key string len or index len and(zend_ulong) for key h\n if (str->total < new_size)\n {//extend it", " new_size = ZEND_MM_ALIGNED_SIZE(new_size + SERIA_SIZE);\n str->buffer = erealloc2(str->buffer, new_size, str->offset);\n if (!str->buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_ERROR, \"realloc Error: %s [%d]\", strerror(errno), errno);\n }\n str->total = new_size;\n }\n}\n#ifdef __SSE2__", "", "void CPINLINE swoole_mini_memcpy(void *dst, const void *src, size_t len)\n{\n register unsigned char *dd = (unsigned char*) dst + len;\n register const unsigned char *ss = (const unsigned char*) src + len;\n switch (len)\n {\n case 68: *((int*) (dd - 68)) = *((int*) (ss - 68));", " /* no break */", " case 64: *((int*) (dd - 64)) = *((int*) (ss - 64));", " /* no break */", " case 60: *((int*) (dd - 60)) = *((int*) (ss - 60));", " /* no break */", " case 56: *((int*) (dd - 56)) = *((int*) (ss - 56));", " /* no break */", " case 52: *((int*) (dd - 52)) = *((int*) (ss - 52));", " /* no break */", " case 48: *((int*) (dd - 48)) = *((int*) (ss - 48));", " /* no break */", " case 44: *((int*) (dd - 44)) = *((int*) (ss - 44));", " /* no break */", " case 40: *((int*) (dd - 40)) = *((int*) (ss - 40));", " /* no break */", " case 36: *((int*) (dd - 36)) = *((int*) (ss - 36));", " /* no break */", " case 32: *((int*) (dd - 32)) = *((int*) (ss - 32));", " /* no break */", " case 28: *((int*) (dd - 28)) = *((int*) (ss - 28));", " /* no break */", " case 24: *((int*) (dd - 24)) = *((int*) (ss - 24));", " /* no break */", " case 20: *((int*) (dd - 20)) = *((int*) (ss - 20));", " /* no break */", " case 16: *((int*) (dd - 16)) = *((int*) (ss - 16));", " /* no break */", " case 12: *((int*) (dd - 12)) = *((int*) (ss - 12));", " /* no break */", " case 8: *((int*) (dd - 8)) = *((int*) (ss - 8));", " /* no break */", " case 4: *((int*) (dd - 4)) = *((int*) (ss - 4));\n break;\n case 67: *((int*) (dd - 67)) = *((int*) (ss - 67));", " /* no break */", " case 63: *((int*) (dd - 63)) = *((int*) (ss - 63));", " /* no break */", " case 59: *((int*) (dd - 59)) = *((int*) (ss - 59));", " /* no break */", " case 55: *((int*) (dd - 55)) = *((int*) (ss - 55));", " /* no break */", " case 51: *((int*) (dd - 51)) = *((int*) (ss - 51));", " /* no break */", " case 47: *((int*) (dd - 47)) = *((int*) (ss - 47));", " /* no break */", " case 43: *((int*) (dd - 43)) = *((int*) (ss - 43));", " /* no break */", " case 39: *((int*) (dd - 39)) = *((int*) (ss - 39));", " /* no break */", " case 35: *((int*) (dd - 35)) = *((int*) (ss - 35));", " /* no break */", " case 31: *((int*) (dd - 31)) = *((int*) (ss - 31));", " /* no break */", " case 27: *((int*) (dd - 27)) = *((int*) (ss - 27));", " /* no break */", " case 23: *((int*) (dd - 23)) = *((int*) (ss - 23));", " /* no break */", " case 19: *((int*) (dd - 19)) = *((int*) (ss - 19));", " /* no break */", " case 15: *((int*) (dd - 15)) = *((int*) (ss - 15));", " /* no break */", " case 11: *((int*) (dd - 11)) = *((int*) (ss - 11));", " /* no break */", " case 7: *((int*) (dd - 7)) = *((int*) (ss - 7));\n *((int*) (dd - 4)) = *((int*) (ss - 4));\n break;\n case 3: *((short*) (dd - 3)) = *((short*) (ss - 3));\n dd[-1] = ss[-1];\n break;\n case 66: *((int*) (dd - 66)) = *((int*) (ss - 66));", " /* no break */", " case 62: *((int*) (dd - 62)) = *((int*) (ss - 62));", " /* no break */", " case 58: *((int*) (dd - 58)) = *((int*) (ss - 58));", " /* no break */", " case 54: *((int*) (dd - 54)) = *((int*) (ss - 54));", " /* no break */", " case 50: *((int*) (dd - 50)) = *((int*) (ss - 50));", " /* no break */", " case 46: *((int*) (dd - 46)) = *((int*) (ss - 46));", " /* no break */", " case 42: *((int*) (dd - 42)) = *((int*) (ss - 42));", " /* no break */", " case 38: *((int*) (dd - 38)) = *((int*) (ss - 38));", " /* no break */", " case 34: *((int*) (dd - 34)) = *((int*) (ss - 34));", " /* no break */", " case 30: *((int*) (dd - 30)) = *((int*) (ss - 30));", " /* no break */", " case 26: *((int*) (dd - 26)) = *((int*) (ss - 26));", " /* no break */", " case 22: *((int*) (dd - 22)) = *((int*) (ss - 22));", " /* no break */", " case 18: *((int*) (dd - 18)) = *((int*) (ss - 18));", " /* no break */", " case 14: *((int*) (dd - 14)) = *((int*) (ss - 14));", " /* no break */", " case 10: *((int*) (dd - 10)) = *((int*) (ss - 10));", " /* no break */", " case 6: *((int*) (dd - 6)) = *((int*) (ss - 6));", " /* no break */", " case 2: *((short*) (dd - 2)) = *((short*) (ss - 2));\n break;\n case 65: *((int*) (dd - 65)) = *((int*) (ss - 65));", " /* no break */", " case 61: *((int*) (dd - 61)) = *((int*) (ss - 61));", " /* no break */", " case 57: *((int*) (dd - 57)) = *((int*) (ss - 57));", " /* no break */", " case 53: *((int*) (dd - 53)) = *((int*) (ss - 53));", " /* no break */", " case 49: *((int*) (dd - 49)) = *((int*) (ss - 49));", " /* no break */", " case 45: *((int*) (dd - 45)) = *((int*) (ss - 45));", " /* no break */", " case 41: *((int*) (dd - 41)) = *((int*) (ss - 41));", " /* no break */", " case 37: *((int*) (dd - 37)) = *((int*) (ss - 37));", " /* no break */", " case 33: *((int*) (dd - 33)) = *((int*) (ss - 33));", " /* no break */", " case 29: *((int*) (dd - 29)) = *((int*) (ss - 29));", " /* no break */", " case 25: *((int*) (dd - 25)) = *((int*) (ss - 25));", " /* no break */", " case 21: *((int*) (dd - 21)) = *((int*) (ss - 21));", " /* no break */", " case 17: *((int*) (dd - 17)) = *((int*) (ss - 17));", " /* no break */", " case 13: *((int*) (dd - 13)) = *((int*) (ss - 13));", " /* no break */", " case 9: *((int*) (dd - 9)) = *((int*) (ss - 9));", " /* no break */", " case 5: *((int*) (dd - 5)) = *((int*) (ss - 5));", " /* no break */", " case 1: dd[-1] = ss[-1];\n break;\n case 0:\n default: break;\n }\n}", "void CPINLINE swoole_memcpy_fast(void *destination, const void *source, size_t size)\n{\n unsigned char *dst = (unsigned char*) destination;\n const unsigned char *src = (const unsigned char*) source;", " // small memory copy\n if (size < 64)\n {\n swoole_mini_memcpy(dst, src, size);\n return;\n }", " size_t diff = (((size_t) dst + 15L) & (~15L)) - ((size_t) dst);\n if (diff > 0)\n {\n swoole_mini_memcpy(dst, src, diff);\n dst += diff;\n src += diff;\n size -= diff;\n }", " // 4个寄存器\n __m128i c1, c2, c3, c4;", " if ((((size_t) src) & 15L) == 0)\n {\n for(; size >= 64; size -= 64)\n {\n //load 时候将下次要用的数据提前fetch\n _mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);\n _mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);\n //从内存中load到寄存器\n c1 = _mm_load_si128(((const __m128i*) src) + 0);\n c2 = _mm_load_si128(((const __m128i*) src) + 1);\n c3 = _mm_load_si128(((const __m128i*) src) + 2);\n c4 = _mm_load_si128(((const __m128i*) src) + 3);\n src += 64;\n //写回内存\n _mm_store_si128((((__m128i*) dst) + 0), c1);\n _mm_store_si128((((__m128i*) dst) + 1), c2);\n _mm_store_si128((((__m128i*) dst) + 2), c3);\n _mm_store_si128((((__m128i*) dst) + 3), c4);\n dst += 64;\n }\n }\n else\n {\n for(; size >= 64; size -= 64)\n {\n _mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);\n _mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);\n c1 = _mm_loadu_si128(((const __m128i*) src) + 0);\n c2 = _mm_loadu_si128(((const __m128i*) src) + 1);\n c3 = _mm_loadu_si128(((const __m128i*) src) + 2);\n c4 = _mm_loadu_si128(((const __m128i*) src) + 3);\n src += 64;\n _mm_store_si128((((__m128i*) dst) + 0), c1);\n _mm_store_si128((((__m128i*) dst) + 1), c2);\n _mm_store_si128((((__m128i*) dst) + 2), c3);\n _mm_store_si128((((__m128i*) dst) + 3), c4);\n dst += 64;\n }\n }\n // _mm_sfence();", " // return memcpy_tiny(dst, src, size);\n}\n#endif", "static CPINLINE void swoole_string_cpy(seriaString *str, void *mem, size_t len)\n{\n swoole_check_size(str, len + 15L);\n //example:13+15=28 28& 11111111 11111111 11111111 11110000\n //str->offset = ((str->offset + 15L) & ~15L);\n // swoole_memcspy_fast(str->buffer + str->offset, mem, len);\n memcpy(str->buffer + str->offset, mem, len);\n str->offset = len + str->offset;\n}", "static CPINLINE void swoole_set_zend_value(seriaString *str, void *value)\n{\n swoole_check_size(str, sizeof (zend_value));\n *(zend_value*) (str->buffer + str->offset) = *((zend_value*) value);\n str->offset = sizeof (zend_value) + str->offset;\n}", "static CPINLINE void swoole_serialize_long(seriaString *buffer, zval *zvalue, SBucketType* type)\n{\n zend_long value = Z_LVAL_P(zvalue);\n //01111111 - 11111111\n if (value <= 0x7f && value >= -0x7f)\n {\n type->data_len = 0;\n SERIA_SET_ENTRY_TYPE_WITH_MINUS(buffer, value);\n }\n else if (value <= 0x7fff && value >= -0x7fff)\n {\n type->data_len = 1;\n SERIA_SET_ENTRY_SHORT_WITH_MINUS(buffer, value);\n }\n else if (value <= 0x7fffffff && value >= -0x7fffffff)\n {\n type->data_len = 2;\n SERIA_SET_ENTRY_SIZE4_WITH_MINUS(buffer, value);\n }\n else\n {\n type->data_len = 3;\n swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));\n }", "}", "static CPINLINE void* swoole_unserialize_long(void *buffer, zval *ret_value, SBucketType type)\n{\n if (type.data_len == 0)\n {//1 byte\n Z_LVAL_P(ret_value) = *((char*) buffer);\n buffer += sizeof (char);\n }\n else if (type.data_len == 1)\n {//2 byte\n Z_LVAL_P(ret_value) = *((short*) buffer);\n buffer += sizeof (short);\n }\n else if (type.data_len == 2)\n {//4 byte\n Z_LVAL_P(ret_value) = *((int32_t *) buffer);\n buffer += sizeof (int32_t);\n }\n else\n {//8 byte\n ret_value->value = *((zend_value*) buffer);\n buffer += sizeof (zend_value);\n }\n return buffer;\n}", "static uint32_t CPINLINE cp_zend_hash_check_size(uint32_t nSize)\n{\n#if defined(ZEND_WIN32)\n unsigned long index;\n#endif", " /* Use big enough power of 2 */\n /* size should be between HT_MIN_SIZE and HT_MAX_SIZE */\n if (nSize < HT_MIN_SIZE)\n {\n nSize = HT_MIN_SIZE;\n }// else if (UNEXPECTED(nSize >= 1000000))\n else if (UNEXPECTED(nSize >= HT_MAX_SIZE))\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"invalid unserialize data\");\n return 0;\n }", "#if defined(ZEND_WIN32)\n if (BitScanReverse(&index, nSize - 1))\n {\n return 0x2 << ((31 - index) ^ 0x1f);\n }\n else\n {\n /* nSize is ensured to be in the valid range, fall back to it\n rather than using an undefined bis scan result. */\n return nSize;\n }\n#elif (defined(__GNUC__) || __has_builtin(__builtin_clz)) && defined(PHP_HAVE_BUILTIN_CLZ)\n return 0x2 << (__builtin_clz(nSize - 1) ^ 0x1f);\n#else\n nSize -= 1;\n nSize |= (nSize >> 1);\n nSize |= (nSize >> 2);\n nSize |= (nSize >> 4);\n nSize |= (nSize >> 8);\n nSize |= (nSize >> 16);\n return nSize + 1;\n#endif\n}", "static CPINLINE void swoole_mini_filter_clear()\n{\n if (swSeriaG.pack_string)\n {\n memset(&mini_filter, 0, sizeof (mini_filter));\n if (bigger_filter)\n {\n efree(bigger_filter);\n bigger_filter = NULL;", " }\n memset(&swSeriaG.filter, 0, sizeof (struct _swMinFilter));\n }\n}", "static CPINLINE void swoole_make_bigger_filter_size()\n{\n if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&\n swSeriaG.filter.mini_fillter_find_cnt < swSeriaG.filter.mini_fillter_miss_cnt)\n // if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&\n // (swSeriaG.filter.mini_fillter_find_cnt / swSeriaG.filter.mini_fillter_miss_cnt) < 1)\n {\n swSeriaG.filter.bigger_fillter_size = swSeriaG.filter.mini_fillter_miss_cnt * 128;\n bigger_filter = (swPoolstr*) ecalloc(1, sizeof (swPoolstr) * swSeriaG.filter.bigger_fillter_size);\n memcpy(bigger_filter, &mini_filter, sizeof (mini_filter));\n }\n}", "static CPINLINE void swoole_mini_filter_add(zend_string *zstr, size_t offset, zend_uchar byte)\n{\n if (swSeriaG.pack_string)\n {\n offset -= _STR_HEADER_SIZE;\n //head 3bit is overhead\n if (offset >= 0x1fffffff)\n {\n return;\n }\n if (bigger_filter)\n {\n uint32_t mod_big = zstr->h & (swSeriaG.filter.bigger_fillter_size - 1);", " bigger_filter[mod_big].offset = offset << 3;\n if (offset <= 0x1fff)\n {\n bigger_filter[mod_big].offset |= byte;\n }\n else\n {\n bigger_filter[mod_big].offset |= (byte | 4);\n }\n bigger_filter[mod_big].str = zstr;\n }\n else\n {\n uint16_t mod = zstr->h & (FILTER_SIZE - 1);\n //repalce it is effective,cause the principle of locality\n mini_filter[mod].offset = offset << 3;\n if (offset <= 0x1fff)\n {\n mini_filter[mod].offset |= byte;\n }\n else\n {\n mini_filter[mod].offset |= (byte | 4);\n }\n mini_filter[mod].str = zstr;\n swSeriaG.filter.mini_fillter_miss_cnt++;\n swoole_make_bigger_filter_size();\n }\n }", "}", "static CPINLINE swPoolstr* swoole_mini_filter_find(zend_string *zstr)\n{\n if (swSeriaG.pack_string)\n {\n zend_ulong h = zend_string_hash_val(zstr);\n swPoolstr* str = NULL;\n if (bigger_filter)\n {\n str = &bigger_filter[h & (swSeriaG.filter.bigger_fillter_size - 1)];\n }\n else\n {\n str = &mini_filter[h & (FILTER_SIZE - 1)];\n }", " if (!str->str)\n {\n return NULL;\n }", " if (str->str->h == h &&\n zstr->len == str->str->len &&\n memcmp(zstr->val, str->str->val, zstr->len) == 0)\n {\n swSeriaG.filter.mini_fillter_find_cnt++;\n return str;\n }\n else\n {\n return NULL;\n }\n }\n else\n {\n return NULL;\n }\n}", "/*\n * arr layout\n * type|key?|bucketlen|buckets\n */\nstatic CPINLINE void seria_array_type(zend_array *ht, seriaString *buffer, size_t type_offset, size_t blen_offset)\n{\n buffer->offset = blen_offset;\n if (ht->nNumOfElements <= 0xff)\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, ht->nNumOfElements)\n }\n else if (ht->nNumOfElements <= 0xffff)\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 2;\n SERIA_SET_ENTRY_SHORT(buffer, ht->nNumOfElements);\n }\n else\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 0;\n swoole_string_cpy(buffer, &ht->nNumOfElements, sizeof (uint32_t));\n }\n}", "/*\n * buffer is bucket len addr\n */\nstatic CPINLINE void* get_array_real_len(void *buffer, zend_uchar data_len, uint32_t *nNumOfElements)\n{\n if (data_len == 1)\n {\n *nNumOfElements = *((zend_uchar*) buffer);\n return buffer + sizeof (zend_uchar);\n }\n else if (data_len == 2)\n {\n *nNumOfElements = *((unsigned short*) buffer);\n return buffer + sizeof (short);\n }\n else\n {\n *nNumOfElements = *((uint32_t*) buffer);\n return buffer + sizeof (uint32_t);\n }\n}", "static CPINLINE void * get_pack_string_len_addr(void ** buffer, size_t *strlen)\n{", " uint8_t overhead = (*(uint8_t*) * buffer);\n uint32_t real_offset;\n uint8_t len_byte;", " if (overhead & 4)\n {\n real_offset = (*(uint32_t*) * buffer) >> 3;\n len_byte = overhead & 3;\n (*buffer) += 4;\n }\n else\n {\n real_offset = (*(uint16_t*) * buffer) >> 3;\n len_byte = overhead & 3;\n (*buffer) += 2;\n }\n void *str_pool_addr = unser_start + real_offset;\n if (len_byte == 1)\n {\n *strlen = *((zend_uchar*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (zend_uchar);\n }\n else if (len_byte == 2)\n {\n *strlen = *((unsigned short*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (unsigned short);\n }\n else\n {\n *strlen = *((size_t*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (size_t);\n }\n // size_t tmp = *strlen;\n return str_pool_addr;\n}", "/*\n * array\n */", "static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t nNumOfElements, long flag)\n{\n //Initialize zend array\n zend_ulong h, nIndex, max_index = 0;\n uint32_t size = cp_zend_hash_check_size(nNumOfElements);", "", " if (!size)\n {\n return NULL;\n }\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n ZVAL_NEW_ARR(zvalue);\n //Initialize buckets\n zend_array *ht = Z_ARR_P(zvalue);\n ht->nTableSize = size;\n ht->nNumUsed = nNumOfElements;\n ht->nNumOfElements = nNumOfElements;\n ht->nNextFreeElement = 0;\n#ifdef HASH_FLAG_APPLY_PROTECTION\n ht->u.flags = HASH_FLAG_APPLY_PROTECTION;\n#endif\n ht->nTableMask = -(ht->nTableSize);\n ht->pDestructor = ZVAL_PTR_DTOR;", " GC_SET_REFCOUNT(ht, 1);\n GC_TYPE_INFO(ht) = IS_ARRAY;\n // if (ht->nNumUsed)\n //{\n // void *arData = ecalloc(1, len);\n HT_SET_DATA_ADDR(ht, emalloc(HT_SIZE(ht)));\n ht->u.flags |= HASH_FLAG_INITIALIZED;\n int ht_hash_size = HT_HASH_SIZE((ht)->nTableMask);\n if (ht_hash_size <= 0)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n HT_HASH_RESET(ht);\n //}", "\n int idx;\n Bucket *p;\n for(idx = 0; idx < nNumOfElements; idx++)\n {\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal array unserialize data\");\n return NULL;\n }\n SBucketType type = *((SBucketType*) buffer);\n buffer += sizeof (SBucketType);\n p = ht->arData + idx;\n /* Initialize key */\n if (type.key_type == KEY_TYPE_STRING)\n {\n size_t key_len;\n if (type.key_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &key_len);\n p->key = zend_string_init((char*) str_pool_addr, key_len, 0);\n h = zend_inline_hash_func((char*) str_pool_addr, key_len);\n p->key->h = p->h = h;\n }\n else\n {//move step\n if (type.key_len == 1)\n {\n key_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n key_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n key_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }", "", " p->key = zend_string_init((char*) buffer, key_len, 0);\n // h = zend_inline_hash_func((char*) buffer, key_len);\n h = zend_inline_hash_func((char*) buffer, key_len);\n buffer += key_len;\n p->key->h = p->h = h;\n }\n }\n else\n {\n if (type.key_len == 0)\n {\n //means pack\n h = p->h = idx;\n p->key = NULL;\n max_index = p->h + 1;\n // ht->u.flags |= HASH_FLAG_PACKED;\n }\n else\n {\n if (type.key_len == 1)\n {\n h = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n h = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n h = *((zend_ulong*) buffer);\n buffer += sizeof (zend_ulong);\n }\n p->h = h;\n p->key = NULL;\n if (h >= max_index)\n {\n max_index = h + 1;\n }\n }\n }\n /* Initialize hash */\n nIndex = h | ht->nTableMask;\n Z_NEXT(p->val) = HT_HASH(ht, nIndex);\n HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(idx);", " /* Initialize data type */\n p->val.u1.v.type = type.data_type;\n Z_TYPE_FLAGS(p->val) = 0;", " /* Initialize data */\n if (type.data_type == IS_STRING)\n {\n size_t data_len;\n if (type.data_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &data_len);\n p->val.value.str = zend_string_init((char*) str_pool_addr, data_len, 0);\n }\n else\n {\n if (type.data_len == 1)\n {\n data_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.data_len == 2)\n {\n data_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n data_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }", "", " p->val.value.str = zend_string_init((char*) buffer, data_len, 0);\n buffer += data_len;\n }\n Z_TYPE_INFO(p->val) = IS_STRING_EX;\n }\n else if (type.data_type == IS_ARRAY)\n {\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n buffer = swoole_unserialize_arr(buffer, &p->val, num, flag);\n }\n else if (type.data_type == IS_LONG)\n {\n buffer = swoole_unserialize_long(buffer, &p->val, type);\n }\n else if (type.data_type == IS_DOUBLE)\n {\n p->val.value = *((zend_value*) buffer);\n buffer += sizeof (zend_value);\n }\n else if (type.data_type == IS_UNDEF)\n {\n buffer = swoole_unserialize_object(buffer, &p->val, type.data_len, NULL, flag);\n Z_TYPE_INFO(p->val) = IS_OBJECT_EX;\n }", " }\n ht->nNextFreeElement = max_index;", "", "\n return buffer;", "}", "/*\n * arr layout\n * type|key?|bucketlen|buckets\n */\nstatic void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)\n{\n zval *data;\n zend_string *key;\n zend_ulong index;\n swPoolstr *swStr = NULL;\n zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;", " ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)\n {\n SBucketType type = {0};\n type.data_type = Z_TYPE_P(data);\n //start point\n size_t p = buffer->offset;", " if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)\n {\n type.key_type = KEY_TYPE_INDEX;\n type.key_len = 0;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n }\n else\n {\n //seria key\n if (key)\n {\n type.key_type = KEY_TYPE_STRING;\n if ((swStr = swoole_mini_filter_find(key)))\n {\n type.key_len = 3; //means use same string\n SERIA_SET_ENTRY_TYPE(buffer, type);\n if (swStr->offset & 4)\n {\n SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n }\n }\n else\n {\n if (key->len <= 0xff)\n {\n type.key_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 1);\n SERIA_SET_ENTRY_TYPE(buffer, key->len);\n swoole_string_cpy(buffer, key->val, key->len);\n }\n else if (key->len <= 0xffff)\n {//if more than this don't need optimize\n type.key_len = 2;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 2);\n SERIA_SET_ENTRY_SHORT(buffer, key->len);\n swoole_string_cpy(buffer, key->val, key->len);\n }\n else\n {\n type.key_len = 0;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 3);\n swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);\n }\n }\n }\n else\n {\n type.key_type = KEY_TYPE_INDEX;\n if (index <= 0xff)\n {\n type.key_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_TYPE(buffer, index);\n }\n else if (index <= 0xffff)\n {\n type.key_len = 2;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_SHORT(buffer, index);\n }\n else\n {\n type.key_len = 3;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_ULONG(buffer, index);\n }", " }\n }\n //seria data\ntry_again:\n switch (Z_TYPE_P(data))\n {\n case IS_STRING:\n {\n if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string\n if (swStr->offset & 4)\n {\n SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n }\n }\n else\n {\n if (Z_STRLEN_P(data) <= 0xff)\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 1;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);\n SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));\n swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n }\n else if (Z_STRLEN_P(data) <= 0xffff)\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 2;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);\n SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));\n swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n }\n else\n {//if more than this don't need optimize\n ((SBucketType*) (buffer->buffer + p))->data_len = 0;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);\n swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));\n }\n }\n break;\n }\n case IS_LONG:\n {\n SBucketType* long_type = (SBucketType*) (buffer->buffer + p);\n swoole_serialize_long(buffer, data, long_type);\n break;\n }\n case IS_DOUBLE:\n swoole_set_zend_value(buffer, &(data->value));\n break;\n case IS_REFERENCE:\n data = Z_REFVAL_P(data);\n ((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);\n goto try_again;\n break;\n case IS_ARRAY:\n {\n zend_array *ht = Z_ARRVAL_P(data);", " if (GC_IS_RECURSIVE(ht))\n {", " ((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL;//reset type null", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the array has cycle ref\");\n }\n else\n {\n seria_array_type(ht, buffer, p, buffer->offset);\n if (ZEND_HASH_APPLY_PROTECTION(ht))\n {\n GC_PROTECT_RECURSION(ht);\n swoole_serialize_arr(buffer, ht);\n GC_UNPROTECT_RECURSION(ht);\n }\n else\n {\n swoole_serialize_arr(buffer, ht);\n }", " }\n break;\n }\n //object propterty table is this type\n case IS_INDIRECT:\n data = Z_INDIRECT_P(data);\n zend_uchar type = Z_TYPE_P(data);\n ((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);\n goto try_again;\n break;\n case IS_OBJECT:\n {\n /*\n * layout\n * type | key | namelen | name | bucket len |buckets\n */\n ((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;", " if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))\n {\n GC_PROTECT_RECURSION(Z_OBJPROP_P(data));\n swoole_serialize_object(buffer, data, p);\n GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));\n }\n else\n {\n swoole_serialize_object(buffer, data, p);\n }", " break;\n }\n default://\n break;", " }", " }\n ZEND_HASH_FOREACH_END();\n}", "/*\n * string\n */\nstatic CPINLINE void swoole_serialize_string(seriaString *buffer, zval *zvalue)\n{", " swoole_string_cpy(buffer, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue));\n}", "static CPINLINE zend_string* swoole_unserialize_string(void *buffer, size_t len)\n{", " return zend_string_init(buffer, len, 0);\n}", "/*\n * raw\n */\nstatic CPINLINE void swoole_unserialize_raw(void *buffer, zval *zvalue)\n{", " memcpy(&zvalue->value, buffer, sizeof (zend_value));\n}", "#if 0", "", "/*\n * null\n */\nstatic CPINLINE void swoole_unserialize_null(void *buffer, zval *zvalue)\n{", " memcpy(&zvalue->value, buffer, sizeof (zend_value));\n}\n#endif", "static CPINLINE void swoole_serialize_raw(seriaString *buffer, zval *zvalue)\n{", " swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));\n}", "/*\n * obj layout\n * type|bucket key|name len| name| buket len |buckets\n */\nstatic void swoole_serialize_object(seriaString *buffer, zval *obj, size_t start)\n{\n zend_string *name = Z_OBJCE_P(obj)->name;\n if (GC_IS_RECURSIVE(Z_OBJPROP_P(obj)))\n {\n zend_throw_exception_ex(NULL, 0, \"the object %s has cycle ref.\", name->val);\n return;\n }\n if (name->len > 0xffff)\n {//so long?\n zend_throw_exception_ex(NULL, 0, \"the object name is too long.\");\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, name->len);\n swoole_string_cpy(buffer, name->val, name->len);\n }", " zend_class_entry *ce = Z_OBJ_P(obj)->ce;\n if (ce && zend_hash_exists(&ce->function_table, Z_STR(swSeriaG.sleep_fname)))\n {\n zval retval;\n if (call_user_function_ex(NULL, obj, &swSeriaG.sleep_fname, &retval, 0, 0, 1, NULL) == SUCCESS)\n {\n if (EG(exception))\n {\n zval_dtor(&retval);\n return;\n }\n if (Z_TYPE(retval) == IS_ARRAY)\n {\n zend_string *prop_key;\n zval *prop_value, *sleep_value;\n const char *prop_name, *class_name;\n size_t prop_key_len;\n int got_num = 0;", " //for the zero malloc\n zend_array tmp_arr;\n zend_array *ht = (zend_array *) & tmp_arr;\n#if PHP_VERSION_ID >= 70300\n _zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0);\n#else\n _zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_CC);\n#endif\n ht->nTableMask = -(ht)->nTableSize;\n ALLOCA_FLAG(use_heap);\n void *ht_addr = do_alloca(HT_SIZE(ht), use_heap);\n HT_SET_DATA_ADDR(ht, ht_addr);\n ht->u.flags |= HASH_FLAG_INITIALIZED;\n HT_HASH_RESET(ht);", " //just clean property do not add null when does not exist\n //we double for each, cause we do not malloc and release it", " ZEND_HASH_FOREACH_STR_KEY_VAL(Z_OBJPROP_P(obj), prop_key, prop_value)\n {\n //get origin property name\n zend_unmangle_property_name_ex(prop_key, &class_name, &prop_name, &prop_key_len);", " ZEND_HASH_FOREACH_VAL(Z_ARRVAL(retval), sleep_value)\n {\n if (Z_TYPE_P(sleep_value) == IS_STRING &&\n Z_STRLEN_P(sleep_value) == prop_key_len &&\n memcmp(Z_STRVAL_P(sleep_value), prop_name, prop_key_len) == 0)\n {\n got_num++;\n //add mangle key,unmangle in unseria\n _zend_hash_add_or_update(ht, prop_key, prop_value, HASH_UPDATE ZEND_FILE_LINE_CC);", " break;\n }", " }\n ZEND_HASH_FOREACH_END();", " }\n ZEND_HASH_FOREACH_END();", " //there some member not in property\n if (zend_hash_num_elements(Z_ARRVAL(retval)) > got_num)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"__sleep() retrun a member but does not exist in property\");", " }\n seria_array_type(ht, buffer, start, buffer->offset);\n swoole_serialize_arr(buffer, ht);\n ZSTR_ALLOCA_FREE(ht_addr, use_heap);\n zval_dtor(&retval);\n return;", " }\n else\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \" __sleep should return an array only containing the \"\n \"names of instance-variables to serialize\");\n zval_dtor(&retval);\n }", " }\n }\n seria_array_type(Z_OBJPROP_P(obj), buffer, start, buffer->offset);\n swoole_serialize_arr(buffer, Z_OBJPROP_P(obj));\n // printf(\"hash2 %u\\n\",ce->properties_info.arData[0].key->h);\n}", "/*\n * for the zero malloc\n */\nstatic CPINLINE zend_string * swoole_string_init(const char *str, size_t len)\n{\n#ifdef ZEND_DEBUG\n return zend_string_init(str, len, 0);\n#else\n ALLOCA_FLAG(use_heap);\n zend_string *ret;\n ZSTR_ALLOCA_INIT(ret, str, len, use_heap);", " return ret;\n#endif\n}", "/*\n * for the zero malloc\n */\nstatic CPINLINE void swoole_string_release(zend_string *str)\n{\n#ifdef ZEND_DEBUG\n zend_string_release(str);\n#else\n //if dont support alloc 0 will ignore\n //if support alloc size is definitely < ZEND_ALLOCA_MAX_SIZE\n ZSTR_ALLOCA_FREE(str, 0);\n#endif\n}", "static CPINLINE zend_class_entry* swoole_try_get_ce(zend_string *class_name)\n{\n //user class , do not support incomplete class now\n zend_class_entry *ce = zend_lookup_class(class_name);\n if (ce)\n {\n return ce;\n }\n // try call unserialize callback and retry lookup\n zval user_func, args[1], retval;", " /* Check for unserialize callback */\n if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\\0'))\n {\n zend_throw_exception_ex(NULL, 0, \"can not find class %s\", class_name->val TSRMLS_CC);\n return NULL;\n }", " ", " zend_string *fname = swoole_string_init(ZEND_STRL(PG(unserialize_callback_func)));\n Z_STR(user_func) = fname;\n Z_TYPE_INFO(user_func) = IS_STRING_EX;\n ZVAL_STR(&args[0], class_name);", " call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL);", " swoole_string_release(fname);", " //user class , do not support incomplete class now\n ce = zend_lookup_class(class_name);\n if (!ce)\n {\n zend_throw_exception_ex(NULL, 0, \"can not find class %s\", class_name->val TSRMLS_CC);\n return NULL;\n }\n else\n {\n return ce;\n }\n}", "/*\n * obj layout\n * type| key[0|1] |name len| name| buket len |buckets\n */\nstatic void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag)\n{\n zval property;\n uint32_t arr_num = 0;\n size_t name_len = *((unsigned short*) buffer);", "", " if (!name_len)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n buffer += 2;\n zend_string *class_name;", " if (flag == UNSERIALIZE_OBJECT_TO_STDCLASS) ", " {\n class_name = swoole_string_init(ZEND_STRL(\"StdClass\"));", " } \n else ", " {\n class_name = swoole_string_init((char*) buffer, name_len);\n }\n buffer += name_len;\n zend_class_entry *ce = swoole_try_get_ce(class_name);\n swoole_string_release(class_name);", "", "\n if (!ce)\n {\n return NULL;\n }", " buffer = get_array_real_len(buffer, bucket_len, &arr_num);\n buffer = swoole_unserialize_arr(buffer, &property, arr_num, flag);", " object_init_ex(return_value, ce);\n", " zval *data,*d;", " zend_string *key;\n zend_ulong index;\n", " ", " ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(property), index, key, data)\n {\n const char *prop_name, *tmp;\n size_t prop_len;\n if (key)\n {", " if ((d = zend_hash_find(Z_OBJPROP_P(return_value), key)) != NULL)\n {\n if (Z_TYPE_P(d) == IS_INDIRECT)\n {\n d = Z_INDIRECT_P(d);\n }\n zval_dtor(d);\n ZVAL_COPY(d, data);\n }\n else\n {\n zend_unmangle_property_name_ex(key, &tmp, &prop_name, &prop_len);\n zend_update_property(ce, return_value, prop_name, prop_len, data);\n }", "// zend_hash_update(Z_OBJPROP_P(return_value),key,data);\n// zend_update_property(ce, return_value, ZSTR_VAL(key), ZSTR_LEN(key), data);", " }\n else\n {\n zend_hash_next_index_insert(Z_OBJPROP_P(return_value), data);\n }\n }\n ZEND_HASH_FOREACH_END();\n zval_dtor(&property);", " if (ce->constructor)\n {\n // zend_fcall_info fci = {0};\n // zend_fcall_info_cache fcc = {0};\n // fci.size = sizeof (zend_fcall_info);\n // zval retval;\n // ZVAL_UNDEF(&fci.function_name);\n // fci.retval = &retval;\n // fci.param_count = 0;\n // fci.params = NULL;\n // fci.no_separation = 1;\n // fci.object = Z_OBJ_P(return_value);\n //\n // zend_fcall_info_args_ex(&fci, ce->constructor, args);\n //\n // fcc.initialized = 1;\n // fcc.function_handler = ce->constructor;\n // // fcc.calling_scope = EG(scope);\n // fcc.called_scope = Z_OBJCE_P(return_value);\n // fcc.object = Z_OBJ_P(return_value);\n //\n // if (zend_call_function(&fci, &fcc) == FAILURE)\n // {\n // zend_throw_exception_ex(NULL, 0, \"could not call class constructor\");\n // }\n // zend_fcall_info_args_clear(&fci, 1);\n }", "\n //call object __wakeup\n if (zend_hash_str_exists(&ce->function_table, ZEND_STRL(\"__wakeup\")))\n {\n zval ret, wakeup;\n zend_string *fname = swoole_string_init(ZEND_STRL(\"__wakeup\"));\n Z_STR(wakeup) = fname;\n Z_TYPE_INFO(wakeup) = IS_STRING_EX;\n call_user_function_ex(CG(function_table), return_value, &wakeup, &ret, 0, NULL, 1, NULL);\n swoole_string_release(fname);\n zval_ptr_dtor(&ret);\n }", "", " return buffer;", "}", "/*\n * dispatch\n */", "static CPINLINE void swoole_seria_dispatch(seriaString *buffer, zval *zvalue)\n{\nagain:\n switch (Z_TYPE_P(zvalue))\n {\n case IS_NULL:\n case IS_TRUE:\n case IS_FALSE:\n break;\n case IS_LONG:\n {\n SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);\n swoole_serialize_long(buffer, zvalue, type);\n break;\n }\n case IS_DOUBLE:\n swoole_serialize_raw(buffer, zvalue);\n break;\n case IS_STRING:\n swoole_serialize_string(buffer, zvalue);\n break;\n case IS_ARRAY:\n {\n seria_array_type(Z_ARRVAL_P(zvalue), buffer, _STR_HEADER_SIZE, _STR_HEADER_SIZE + 1);\n swoole_serialize_arr(buffer, Z_ARRVAL_P(zvalue));\n swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);\n swoole_mini_filter_clear();\n break;\n }\n case IS_REFERENCE:\n zvalue = Z_REFVAL_P(zvalue);\n goto again;\n break;\n case IS_OBJECT:\n {\n SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);\n type->data_type = IS_UNDEF;\n swoole_serialize_object(buffer, zvalue, _STR_HEADER_SIZE);\n swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);\n swoole_mini_filter_clear();\n break;\n }\n default:\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the type is not supported by swoole serialize.\");", " break;\n }\n}", "PHPAPI zend_string* php_swoole_serialize(zval *zvalue)\n{", " seriaString str;\n swoole_string_new(SERIA_SIZE, &str, Z_TYPE_P(zvalue));\n swoole_seria_dispatch(&str, zvalue); //serialize into a string\n zend_string *z_str = (zend_string *) str.buffer;", " z_str->len = str.offset - _STR_HEADER_SIZE;\n z_str->val[z_str->len] = '\\0';\n z_str->h = 0;\n GC_SET_REFCOUNT(z_str, 1);\n GC_TYPE_INFO(z_str) = IS_STRING_EX;", " return z_str;\n}", "static CPINLINE int swoole_seria_check_eof(void *buffer, size_t len)\n{\n void *eof_str = buffer - sizeof (SBucketType) + len - 3;\n if (memcmp(eof_str, SWOOLE_SERI_EOF, 3) == 0)\n {\n return 0;\n }\n else\n {\n return -1;\n }\n}", "/*\n * buffer is seria string buffer\n * len is string len\n * return_value is unseria bucket\n * args is for the object ctor (can be NULL)\n */\nPHPAPI int php_swoole_unserialize(void *buffer, size_t len, zval *return_value, zval *object_args, long flag)\n{\n SBucketType type = *(SBucketType*) (buffer);\n zend_uchar real_type = type.data_type;", "", " buffer += sizeof (SBucketType);\n switch (real_type)\n {\n case IS_NULL:\n case IS_TRUE:\n case IS_FALSE:\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_LONG:\n swoole_unserialize_long(buffer, return_value, type);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_DOUBLE:\n swoole_unserialize_raw(buffer, return_value);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_STRING:\n len -= sizeof (SBucketType);\n zend_string *str = swoole_unserialize_string(buffer, len);\n ZVAL_STR(return_value, str);\n break;\n case IS_ARRAY:\n {\n if (swoole_seria_check_eof(buffer, len) < 0)\n {", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;", " }\n unser_start = buffer - sizeof (SBucketType);\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n if (!swoole_unserialize_arr(buffer, return_value, num, flag))\n {\n return SW_FALSE;\n }\n break;\n }\n case IS_UNDEF:\n if (swoole_seria_check_eof(buffer, len) < 0)\n {", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;", " }\n unser_start = buffer - sizeof (SBucketType);\n if (!swoole_unserialize_object(buffer, return_value, type.data_len, object_args, flag))\n {\n return SW_FALSE;\n }\n break;\n default:\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the type is not supported by swoole serialize.\");\n return SW_FALSE;\n }", " return SW_TRUE;\n}", "static PHP_METHOD(swoole_serialize, pack)\n{\n zval *zvalue;\n zend_size_t is_fast = 0;", " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z|l\", &zvalue, &is_fast) == FAILURE)\n {\n RETURN_FALSE;\n }\n swSeriaG.pack_string = !is_fast;\n zend_string *z_str = php_swoole_serialize(zvalue);", " RETURN_STR(z_str);\n}", "static PHP_METHOD(swoole_serialize, unpack)\n{\n char *buffer = NULL;\n size_t arg_len;\n zval *args = NULL; //for object\n long flag = 0;", " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|la\", &buffer, &arg_len, &flag, &args) == FAILURE)\n {\n RETURN_FALSE;\n }\n if (!php_swoole_unserialize(buffer, arg_len, return_value, args, flag))\n {\n RETURN_FALSE;\n }\n}", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1531], "buggy_code_start_loc": [54], "filenames": ["swoole_serialize.c"], "fixing_code_end_loc": [1541], "fixing_code_start_loc": [55], "message": "The unpack implementation in Swoole version 4.0.4 lacks correct size checks in the deserialization process. An attacker can craft a serialized object to exploit this vulnerability and cause a SEGV.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:swoole:swoole:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "93EF17F5-CCB3-4CB8-AFE3-706C531F3B1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The unpack implementation in Swoole version 4.0.4 lacks correct size checks in the deserialization process. An attacker can craft a serialized object to exploit this vulnerability and cause a SEGV."}, {"lang": "es", "value": "La implementaci\u00f3n de desempaquetado en la versi\u00f3n 4.0.4 de Swoole carece de controles de tama\u00f1o correctos en el proceso de deserializaci\u00f3n. Un atacante puede crear un objeto serializado para explotar esta vulnerabilidad y provocar un SEGV."}], "evaluatorComment": null, "id": "CVE-2018-15503", "lastModified": "2018-11-08T20:49:48.653", "metrics": {"cvssMetricV2": [{"acInsufInfo": true, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-18T02:29:01.903", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/swoole/swoole-src/commit/4cdbce5d9bf2fe596bb6acd7d6611f9e8c253a76"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://github.com/swoole/swoole-src/issues/1882"}, {"source": "cve@mitre.org", "tags": ["Technical Description", "Third Party Advisory"], "url": "https://x-c3ll.github.io/posts/swoole-deserialization-cve-2018-15503/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/swoole/swoole-src/commit/4cdbce5d9bf2fe596bb6acd7d6611f9e8c253a76"}, "type": "CWE-502"}
119
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http://www.apache.org/licenses/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: xinhua.guo <woshiguo35@gmail.com> |\n +----------------------------------------------------------------------+\n */", "#include \"php_swoole.h\"\n#include \"swoole_serialize.h\"\n#ifdef __SSE2__\n#include <emmintrin.h>\n#endif", "#if PHP_MAJOR_VERSION >= 7\n#define CPINLINE sw_inline", "ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_pack, 0, 0, 1)\nZEND_ARG_INFO(0, data)\nZEND_ARG_INFO(0, flag)\nZEND_END_ARG_INFO()", "ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_unpack, 0, 0, 1)\nZEND_ARG_INFO(0, string)\nZEND_ARG_INFO(0, args)\nZEND_END_ARG_INFO()", "static void swoole_serialize_object(seriaString *buffer, zval *zvalue, size_t start);\nstatic void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue);\nstatic void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t num, long flag);\nstatic void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag);", "static PHP_METHOD(swoole_serialize, pack);\nstatic PHP_METHOD(swoole_serialize, unpack);", "\nstatic const zend_function_entry swoole_serialize_methods[] = {\n PHP_ME(swoole_serialize, pack, arginfo_swoole_serialize_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)\n PHP_ME(swoole_serialize, unpack, arginfo_swoole_serialize_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)\n PHP_FE_END\n};", "zend_class_entry swoole_serialize_ce;\nzend_class_entry *swoole_serialize_class_entry_ptr;", "#define SWOOLE_SERI_EOF \"EOF\"", "#define CHECK_STEP if(buffer>unseri_buffer_end){ php_error_docref(NULL TSRMLS_CC, E_ERROR, \"illegal unserialize data\"); return NULL;}", "\nstatic struct _swSeriaG swSeriaG;", "char *unseri_buffer_end = NULL;", "\nvoid swoole_serialize_init(int module_number TSRMLS_DC)\n{\n SWOOLE_INIT_CLASS_ENTRY(swoole_serialize_ce, \"swoole_serialize\", \"Swoole\\\\Serialize\", swoole_serialize_methods);\n swoole_serialize_class_entry_ptr = zend_register_internal_class(&swoole_serialize_ce TSRMLS_CC);\n SWOOLE_CLASS_ALIAS(swoole_serialize, \"Swoole\\\\Serialize\");", " // ZVAL_STRING(&swSeriaG.sleep_fname, \"__sleep\");\n zend_string *zstr_sleep = zend_string_init(\"__sleep\", sizeof (\"__sleep\") - 1, 1);\n zend_string *zstr_weekup = zend_string_init(\"__weekup\", sizeof (\"__weekup\") - 1, 1);\n ZVAL_STR(&swSeriaG.sleep_fname, zstr_sleep);\n ZVAL_STR(&swSeriaG.weekup_fname, zstr_weekup);\n // ZVAL_STRING(&swSeriaG.weekup_fname, \"__weekup\");", " memset(&swSeriaG.filter, 0, sizeof (swSeriaG.filter));\n memset(&mini_filter, 0, sizeof (mini_filter));", " REGISTER_LONG_CONSTANT(\"SWOOLE_FAST_PACK\", SW_FAST_PACK, CONST_CS | CONST_PERSISTENT);\n REGISTER_LONG_CONSTANT(\"UNSERIALIZE_OBJECT_TO_ARRAY\", UNSERIALIZE_OBJECT_TO_ARRAY, CONST_CS | CONST_PERSISTENT);\n REGISTER_LONG_CONSTANT(\"UNSERIALIZE_OBJECT_TO_STDCLASS\", UNSERIALIZE_OBJECT_TO_STDCLASS, CONST_CS | CONST_PERSISTENT);\n}", "static CPINLINE int swoole_string_new(size_t size, seriaString *str, zend_uchar type)\n{\n int total = ZEND_MM_ALIGNED_SIZE(_STR_HEADER_SIZE + size + 1);\n str->total = total;\n //escape the header for later\n str->offset = _STR_HEADER_SIZE;\n //zend string addr\n str->buffer = ecalloc(1, total);\n if (!str->buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_ERROR, \"malloc Error: %s [%d]\", strerror(errno), errno);\n }", " SBucketType real_type = {0};\n real_type.data_type = type;\n *(SBucketType*) (str->buffer + str->offset) = real_type;\n str->offset += sizeof (SBucketType);\n return 0;\n}", "static CPINLINE void swoole_check_size(seriaString *str, size_t len)\n{\n int new_size = len + str->offset;\n // int new_size = len + str->offset + 3 + sizeof (zend_ulong); //space 1 for the type and 2 for key string len or index len and(zend_ulong) for key h\n if (str->total < new_size)\n {//extend it", " new_size = ZEND_MM_ALIGNED_SIZE(new_size + SERIA_SIZE);\n str->buffer = erealloc2(str->buffer, new_size, str->offset);\n if (!str->buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_ERROR, \"realloc Error: %s [%d]\", strerror(errno), errno);\n }\n str->total = new_size;\n }\n}\n#ifdef __SSE2__", "", "void CPINLINE swoole_mini_memcpy(void *dst, const void *src, size_t len)\n{\n register unsigned char *dd = (unsigned char*) dst + len;\n register const unsigned char *ss = (const unsigned char*) src + len;\n switch (len)\n {\n case 68: *((int*) (dd - 68)) = *((int*) (ss - 68));", " /* no break */", " case 64: *((int*) (dd - 64)) = *((int*) (ss - 64));", " /* no break */", " case 60: *((int*) (dd - 60)) = *((int*) (ss - 60));", " /* no break */", " case 56: *((int*) (dd - 56)) = *((int*) (ss - 56));", " /* no break */", " case 52: *((int*) (dd - 52)) = *((int*) (ss - 52));", " /* no break */", " case 48: *((int*) (dd - 48)) = *((int*) (ss - 48));", " /* no break */", " case 44: *((int*) (dd - 44)) = *((int*) (ss - 44));", " /* no break */", " case 40: *((int*) (dd - 40)) = *((int*) (ss - 40));", " /* no break */", " case 36: *((int*) (dd - 36)) = *((int*) (ss - 36));", " /* no break */", " case 32: *((int*) (dd - 32)) = *((int*) (ss - 32));", " /* no break */", " case 28: *((int*) (dd - 28)) = *((int*) (ss - 28));", " /* no break */", " case 24: *((int*) (dd - 24)) = *((int*) (ss - 24));", " /* no break */", " case 20: *((int*) (dd - 20)) = *((int*) (ss - 20));", " /* no break */", " case 16: *((int*) (dd - 16)) = *((int*) (ss - 16));", " /* no break */", " case 12: *((int*) (dd - 12)) = *((int*) (ss - 12));", " /* no break */", " case 8: *((int*) (dd - 8)) = *((int*) (ss - 8));", " /* no break */", " case 4: *((int*) (dd - 4)) = *((int*) (ss - 4));\n break;\n case 67: *((int*) (dd - 67)) = *((int*) (ss - 67));", " /* no break */", " case 63: *((int*) (dd - 63)) = *((int*) (ss - 63));", " /* no break */", " case 59: *((int*) (dd - 59)) = *((int*) (ss - 59));", " /* no break */", " case 55: *((int*) (dd - 55)) = *((int*) (ss - 55));", " /* no break */", " case 51: *((int*) (dd - 51)) = *((int*) (ss - 51));", " /* no break */", " case 47: *((int*) (dd - 47)) = *((int*) (ss - 47));", " /* no break */", " case 43: *((int*) (dd - 43)) = *((int*) (ss - 43));", " /* no break */", " case 39: *((int*) (dd - 39)) = *((int*) (ss - 39));", " /* no break */", " case 35: *((int*) (dd - 35)) = *((int*) (ss - 35));", " /* no break */", " case 31: *((int*) (dd - 31)) = *((int*) (ss - 31));", " /* no break */", " case 27: *((int*) (dd - 27)) = *((int*) (ss - 27));", " /* no break */", " case 23: *((int*) (dd - 23)) = *((int*) (ss - 23));", " /* no break */", " case 19: *((int*) (dd - 19)) = *((int*) (ss - 19));", " /* no break */", " case 15: *((int*) (dd - 15)) = *((int*) (ss - 15));", " /* no break */", " case 11: *((int*) (dd - 11)) = *((int*) (ss - 11));", " /* no break */", " case 7: *((int*) (dd - 7)) = *((int*) (ss - 7));\n *((int*) (dd - 4)) = *((int*) (ss - 4));\n break;\n case 3: *((short*) (dd - 3)) = *((short*) (ss - 3));\n dd[-1] = ss[-1];\n break;\n case 66: *((int*) (dd - 66)) = *((int*) (ss - 66));", " /* no break */", " case 62: *((int*) (dd - 62)) = *((int*) (ss - 62));", " /* no break */", " case 58: *((int*) (dd - 58)) = *((int*) (ss - 58));", " /* no break */", " case 54: *((int*) (dd - 54)) = *((int*) (ss - 54));", " /* no break */", " case 50: *((int*) (dd - 50)) = *((int*) (ss - 50));", " /* no break */", " case 46: *((int*) (dd - 46)) = *((int*) (ss - 46));", " /* no break */", " case 42: *((int*) (dd - 42)) = *((int*) (ss - 42));", " /* no break */", " case 38: *((int*) (dd - 38)) = *((int*) (ss - 38));", " /* no break */", " case 34: *((int*) (dd - 34)) = *((int*) (ss - 34));", " /* no break */", " case 30: *((int*) (dd - 30)) = *((int*) (ss - 30));", " /* no break */", " case 26: *((int*) (dd - 26)) = *((int*) (ss - 26));", " /* no break */", " case 22: *((int*) (dd - 22)) = *((int*) (ss - 22));", " /* no break */", " case 18: *((int*) (dd - 18)) = *((int*) (ss - 18));", " /* no break */", " case 14: *((int*) (dd - 14)) = *((int*) (ss - 14));", " /* no break */", " case 10: *((int*) (dd - 10)) = *((int*) (ss - 10));", " /* no break */", " case 6: *((int*) (dd - 6)) = *((int*) (ss - 6));", " /* no break */", " case 2: *((short*) (dd - 2)) = *((short*) (ss - 2));\n break;\n case 65: *((int*) (dd - 65)) = *((int*) (ss - 65));", " /* no break */", " case 61: *((int*) (dd - 61)) = *((int*) (ss - 61));", " /* no break */", " case 57: *((int*) (dd - 57)) = *((int*) (ss - 57));", " /* no break */", " case 53: *((int*) (dd - 53)) = *((int*) (ss - 53));", " /* no break */", " case 49: *((int*) (dd - 49)) = *((int*) (ss - 49));", " /* no break */", " case 45: *((int*) (dd - 45)) = *((int*) (ss - 45));", " /* no break */", " case 41: *((int*) (dd - 41)) = *((int*) (ss - 41));", " /* no break */", " case 37: *((int*) (dd - 37)) = *((int*) (ss - 37));", " /* no break */", " case 33: *((int*) (dd - 33)) = *((int*) (ss - 33));", " /* no break */", " case 29: *((int*) (dd - 29)) = *((int*) (ss - 29));", " /* no break */", " case 25: *((int*) (dd - 25)) = *((int*) (ss - 25));", " /* no break */", " case 21: *((int*) (dd - 21)) = *((int*) (ss - 21));", " /* no break */", " case 17: *((int*) (dd - 17)) = *((int*) (ss - 17));", " /* no break */", " case 13: *((int*) (dd - 13)) = *((int*) (ss - 13));", " /* no break */", " case 9: *((int*) (dd - 9)) = *((int*) (ss - 9));", " /* no break */", " case 5: *((int*) (dd - 5)) = *((int*) (ss - 5));", " /* no break */", " case 1: dd[-1] = ss[-1];\n break;\n case 0:\n default: break;\n }\n}", "void CPINLINE swoole_memcpy_fast(void *destination, const void *source, size_t size)\n{\n unsigned char *dst = (unsigned char*) destination;\n const unsigned char *src = (const unsigned char*) source;", " // small memory copy\n if (size < 64)\n {\n swoole_mini_memcpy(dst, src, size);\n return;\n }", " size_t diff = (((size_t) dst + 15L) & (~15L)) - ((size_t) dst);\n if (diff > 0)\n {\n swoole_mini_memcpy(dst, src, diff);\n dst += diff;\n src += diff;\n size -= diff;\n }", " // 4个寄存器\n __m128i c1, c2, c3, c4;", " if ((((size_t) src) & 15L) == 0)\n {\n for(; size >= 64; size -= 64)\n {\n //load 时候将下次要用的数据提前fetch\n _mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);\n _mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);\n //从内存中load到寄存器\n c1 = _mm_load_si128(((const __m128i*) src) + 0);\n c2 = _mm_load_si128(((const __m128i*) src) + 1);\n c3 = _mm_load_si128(((const __m128i*) src) + 2);\n c4 = _mm_load_si128(((const __m128i*) src) + 3);\n src += 64;\n //写回内存\n _mm_store_si128((((__m128i*) dst) + 0), c1);\n _mm_store_si128((((__m128i*) dst) + 1), c2);\n _mm_store_si128((((__m128i*) dst) + 2), c3);\n _mm_store_si128((((__m128i*) dst) + 3), c4);\n dst += 64;\n }\n }\n else\n {\n for(; size >= 64; size -= 64)\n {\n _mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);\n _mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);\n c1 = _mm_loadu_si128(((const __m128i*) src) + 0);\n c2 = _mm_loadu_si128(((const __m128i*) src) + 1);\n c3 = _mm_loadu_si128(((const __m128i*) src) + 2);\n c4 = _mm_loadu_si128(((const __m128i*) src) + 3);\n src += 64;\n _mm_store_si128((((__m128i*) dst) + 0), c1);\n _mm_store_si128((((__m128i*) dst) + 1), c2);\n _mm_store_si128((((__m128i*) dst) + 2), c3);\n _mm_store_si128((((__m128i*) dst) + 3), c4);\n dst += 64;\n }\n }\n // _mm_sfence();", " // return memcpy_tiny(dst, src, size);\n}\n#endif", "static CPINLINE void swoole_string_cpy(seriaString *str, void *mem, size_t len)\n{\n swoole_check_size(str, len + 15L);\n //example:13+15=28 28& 11111111 11111111 11111111 11110000\n //str->offset = ((str->offset + 15L) & ~15L);\n // swoole_memcspy_fast(str->buffer + str->offset, mem, len);\n memcpy(str->buffer + str->offset, mem, len);\n str->offset = len + str->offset;\n}", "static CPINLINE void swoole_set_zend_value(seriaString *str, void *value)\n{\n swoole_check_size(str, sizeof (zend_value));\n *(zend_value*) (str->buffer + str->offset) = *((zend_value*) value);\n str->offset = sizeof (zend_value) + str->offset;\n}", "static CPINLINE void swoole_serialize_long(seriaString *buffer, zval *zvalue, SBucketType* type)\n{\n zend_long value = Z_LVAL_P(zvalue);\n //01111111 - 11111111\n if (value <= 0x7f && value >= -0x7f)\n {\n type->data_len = 0;\n SERIA_SET_ENTRY_TYPE_WITH_MINUS(buffer, value);\n }\n else if (value <= 0x7fff && value >= -0x7fff)\n {\n type->data_len = 1;\n SERIA_SET_ENTRY_SHORT_WITH_MINUS(buffer, value);\n }\n else if (value <= 0x7fffffff && value >= -0x7fffffff)\n {\n type->data_len = 2;\n SERIA_SET_ENTRY_SIZE4_WITH_MINUS(buffer, value);\n }\n else\n {\n type->data_len = 3;\n swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));\n }", "}", "static CPINLINE void* swoole_unserialize_long(void *buffer, zval *ret_value, SBucketType type)\n{\n if (type.data_len == 0)\n {//1 byte\n Z_LVAL_P(ret_value) = *((char*) buffer);\n buffer += sizeof (char);\n }\n else if (type.data_len == 1)\n {//2 byte\n Z_LVAL_P(ret_value) = *((short*) buffer);\n buffer += sizeof (short);\n }\n else if (type.data_len == 2)\n {//4 byte\n Z_LVAL_P(ret_value) = *((int32_t *) buffer);\n buffer += sizeof (int32_t);\n }\n else\n {//8 byte\n ret_value->value = *((zend_value*) buffer);\n buffer += sizeof (zend_value);\n }\n return buffer;\n}", "static uint32_t CPINLINE cp_zend_hash_check_size(uint32_t nSize)\n{\n#if defined(ZEND_WIN32)\n unsigned long index;\n#endif", " /* Use big enough power of 2 */\n /* size should be between HT_MIN_SIZE and HT_MAX_SIZE */\n if (nSize < HT_MIN_SIZE)\n {\n nSize = HT_MIN_SIZE;\n }// else if (UNEXPECTED(nSize >= 1000000))\n else if (UNEXPECTED(nSize >= HT_MAX_SIZE))\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"invalid unserialize data\");\n return 0;\n }", "#if defined(ZEND_WIN32)\n if (BitScanReverse(&index, nSize - 1))\n {\n return 0x2 << ((31 - index) ^ 0x1f);\n }\n else\n {\n /* nSize is ensured to be in the valid range, fall back to it\n rather than using an undefined bis scan result. */\n return nSize;\n }\n#elif (defined(__GNUC__) || __has_builtin(__builtin_clz)) && defined(PHP_HAVE_BUILTIN_CLZ)\n return 0x2 << (__builtin_clz(nSize - 1) ^ 0x1f);\n#else\n nSize -= 1;\n nSize |= (nSize >> 1);\n nSize |= (nSize >> 2);\n nSize |= (nSize >> 4);\n nSize |= (nSize >> 8);\n nSize |= (nSize >> 16);\n return nSize + 1;\n#endif\n}", "static CPINLINE void swoole_mini_filter_clear()\n{\n if (swSeriaG.pack_string)\n {\n memset(&mini_filter, 0, sizeof (mini_filter));\n if (bigger_filter)\n {\n efree(bigger_filter);\n bigger_filter = NULL;", " }\n memset(&swSeriaG.filter, 0, sizeof (struct _swMinFilter));\n }\n}", "static CPINLINE void swoole_make_bigger_filter_size()\n{\n if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&\n swSeriaG.filter.mini_fillter_find_cnt < swSeriaG.filter.mini_fillter_miss_cnt)\n // if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&\n // (swSeriaG.filter.mini_fillter_find_cnt / swSeriaG.filter.mini_fillter_miss_cnt) < 1)\n {\n swSeriaG.filter.bigger_fillter_size = swSeriaG.filter.mini_fillter_miss_cnt * 128;\n bigger_filter = (swPoolstr*) ecalloc(1, sizeof (swPoolstr) * swSeriaG.filter.bigger_fillter_size);\n memcpy(bigger_filter, &mini_filter, sizeof (mini_filter));\n }\n}", "static CPINLINE void swoole_mini_filter_add(zend_string *zstr, size_t offset, zend_uchar byte)\n{\n if (swSeriaG.pack_string)\n {\n offset -= _STR_HEADER_SIZE;\n //head 3bit is overhead\n if (offset >= 0x1fffffff)\n {\n return;\n }\n if (bigger_filter)\n {\n uint32_t mod_big = zstr->h & (swSeriaG.filter.bigger_fillter_size - 1);", " bigger_filter[mod_big].offset = offset << 3;\n if (offset <= 0x1fff)\n {\n bigger_filter[mod_big].offset |= byte;\n }\n else\n {\n bigger_filter[mod_big].offset |= (byte | 4);\n }\n bigger_filter[mod_big].str = zstr;\n }\n else\n {\n uint16_t mod = zstr->h & (FILTER_SIZE - 1);\n //repalce it is effective,cause the principle of locality\n mini_filter[mod].offset = offset << 3;\n if (offset <= 0x1fff)\n {\n mini_filter[mod].offset |= byte;\n }\n else\n {\n mini_filter[mod].offset |= (byte | 4);\n }\n mini_filter[mod].str = zstr;\n swSeriaG.filter.mini_fillter_miss_cnt++;\n swoole_make_bigger_filter_size();\n }\n }", "}", "static CPINLINE swPoolstr* swoole_mini_filter_find(zend_string *zstr)\n{\n if (swSeriaG.pack_string)\n {\n zend_ulong h = zend_string_hash_val(zstr);\n swPoolstr* str = NULL;\n if (bigger_filter)\n {\n str = &bigger_filter[h & (swSeriaG.filter.bigger_fillter_size - 1)];\n }\n else\n {\n str = &mini_filter[h & (FILTER_SIZE - 1)];\n }", " if (!str->str)\n {\n return NULL;\n }", " if (str->str->h == h &&\n zstr->len == str->str->len &&\n memcmp(zstr->val, str->str->val, zstr->len) == 0)\n {\n swSeriaG.filter.mini_fillter_find_cnt++;\n return str;\n }\n else\n {\n return NULL;\n }\n }\n else\n {\n return NULL;\n }\n}", "/*\n * arr layout\n * type|key?|bucketlen|buckets\n */\nstatic CPINLINE void seria_array_type(zend_array *ht, seriaString *buffer, size_t type_offset, size_t blen_offset)\n{\n buffer->offset = blen_offset;\n if (ht->nNumOfElements <= 0xff)\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, ht->nNumOfElements)\n }\n else if (ht->nNumOfElements <= 0xffff)\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 2;\n SERIA_SET_ENTRY_SHORT(buffer, ht->nNumOfElements);\n }\n else\n {\n ((SBucketType*) (buffer->buffer + type_offset))->data_len = 0;\n swoole_string_cpy(buffer, &ht->nNumOfElements, sizeof (uint32_t));\n }\n}", "/*\n * buffer is bucket len addr\n */\nstatic CPINLINE void* get_array_real_len(void *buffer, zend_uchar data_len, uint32_t *nNumOfElements)\n{\n if (data_len == 1)\n {\n *nNumOfElements = *((zend_uchar*) buffer);\n return buffer + sizeof (zend_uchar);\n }\n else if (data_len == 2)\n {\n *nNumOfElements = *((unsigned short*) buffer);\n return buffer + sizeof (short);\n }\n else\n {\n *nNumOfElements = *((uint32_t*) buffer);\n return buffer + sizeof (uint32_t);\n }\n}", "static CPINLINE void * get_pack_string_len_addr(void ** buffer, size_t *strlen)\n{", " uint8_t overhead = (*(uint8_t*) * buffer);\n uint32_t real_offset;\n uint8_t len_byte;", " if (overhead & 4)\n {\n real_offset = (*(uint32_t*) * buffer) >> 3;\n len_byte = overhead & 3;\n (*buffer) += 4;\n }\n else\n {\n real_offset = (*(uint16_t*) * buffer) >> 3;\n len_byte = overhead & 3;\n (*buffer) += 2;\n }\n void *str_pool_addr = unser_start + real_offset;\n if (len_byte == 1)\n {\n *strlen = *((zend_uchar*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (zend_uchar);\n }\n else if (len_byte == 2)\n {\n *strlen = *((unsigned short*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (unsigned short);\n }\n else\n {\n *strlen = *((size_t*) str_pool_addr);\n str_pool_addr = str_pool_addr + sizeof (size_t);\n }\n // size_t tmp = *strlen;\n return str_pool_addr;\n}", "/*\n * array\n */", "static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t nNumOfElements, long flag)\n{\n //Initialize zend array\n zend_ulong h, nIndex, max_index = 0;\n uint32_t size = cp_zend_hash_check_size(nNumOfElements);", " CHECK_STEP;", " if (!size)\n {\n return NULL;\n }\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n ZVAL_NEW_ARR(zvalue);\n //Initialize buckets\n zend_array *ht = Z_ARR_P(zvalue);\n ht->nTableSize = size;\n ht->nNumUsed = nNumOfElements;\n ht->nNumOfElements = nNumOfElements;\n ht->nNextFreeElement = 0;\n#ifdef HASH_FLAG_APPLY_PROTECTION\n ht->u.flags = HASH_FLAG_APPLY_PROTECTION;\n#endif\n ht->nTableMask = -(ht->nTableSize);\n ht->pDestructor = ZVAL_PTR_DTOR;", " GC_SET_REFCOUNT(ht, 1);\n GC_TYPE_INFO(ht) = IS_ARRAY;\n // if (ht->nNumUsed)\n //{\n // void *arData = ecalloc(1, len);\n HT_SET_DATA_ADDR(ht, emalloc(HT_SIZE(ht)));\n ht->u.flags |= HASH_FLAG_INITIALIZED;\n int ht_hash_size = HT_HASH_SIZE((ht)->nTableMask);\n if (ht_hash_size <= 0)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n HT_HASH_RESET(ht);\n //}", "\n int idx;\n Bucket *p;\n for(idx = 0; idx < nNumOfElements; idx++)\n {\n if (!buffer)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal array unserialize data\");\n return NULL;\n }\n SBucketType type = *((SBucketType*) buffer);\n buffer += sizeof (SBucketType);\n p = ht->arData + idx;\n /* Initialize key */\n if (type.key_type == KEY_TYPE_STRING)\n {\n size_t key_len;\n if (type.key_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &key_len);\n p->key = zend_string_init((char*) str_pool_addr, key_len, 0);\n h = zend_inline_hash_func((char*) str_pool_addr, key_len);\n p->key->h = p->h = h;\n }\n else\n {//move step\n if (type.key_len == 1)\n {\n key_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n key_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n key_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }", " CHECK_STEP;", " p->key = zend_string_init((char*) buffer, key_len, 0);\n // h = zend_inline_hash_func((char*) buffer, key_len);\n h = zend_inline_hash_func((char*) buffer, key_len);\n buffer += key_len;\n p->key->h = p->h = h;\n }\n }\n else\n {\n if (type.key_len == 0)\n {\n //means pack\n h = p->h = idx;\n p->key = NULL;\n max_index = p->h + 1;\n // ht->u.flags |= HASH_FLAG_PACKED;\n }\n else\n {\n if (type.key_len == 1)\n {\n h = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.key_len == 2)\n {\n h = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n h = *((zend_ulong*) buffer);\n buffer += sizeof (zend_ulong);\n }\n p->h = h;\n p->key = NULL;\n if (h >= max_index)\n {\n max_index = h + 1;\n }\n }\n }\n /* Initialize hash */\n nIndex = h | ht->nTableMask;\n Z_NEXT(p->val) = HT_HASH(ht, nIndex);\n HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(idx);", " /* Initialize data type */\n p->val.u1.v.type = type.data_type;\n Z_TYPE_FLAGS(p->val) = 0;", " /* Initialize data */\n if (type.data_type == IS_STRING)\n {\n size_t data_len;\n if (type.data_len == 3)\n {//read the same mem\n void *str_pool_addr = get_pack_string_len_addr(&buffer, &data_len);\n p->val.value.str = zend_string_init((char*) str_pool_addr, data_len, 0);\n }\n else\n {\n if (type.data_len == 1)\n {\n data_len = *((zend_uchar*) buffer);\n buffer += sizeof (zend_uchar);\n }\n else if (type.data_len == 2)\n {\n data_len = *((unsigned short*) buffer);\n buffer += sizeof (unsigned short);\n }\n else\n {\n data_len = *((size_t*) buffer);\n buffer += sizeof (size_t);\n }", " CHECK_STEP;", " p->val.value.str = zend_string_init((char*) buffer, data_len, 0);\n buffer += data_len;\n }\n Z_TYPE_INFO(p->val) = IS_STRING_EX;\n }\n else if (type.data_type == IS_ARRAY)\n {\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n buffer = swoole_unserialize_arr(buffer, &p->val, num, flag);\n }\n else if (type.data_type == IS_LONG)\n {\n buffer = swoole_unserialize_long(buffer, &p->val, type);\n }\n else if (type.data_type == IS_DOUBLE)\n {\n p->val.value = *((zend_value*) buffer);\n buffer += sizeof (zend_value);\n }\n else if (type.data_type == IS_UNDEF)\n {\n buffer = swoole_unserialize_object(buffer, &p->val, type.data_len, NULL, flag);\n Z_TYPE_INFO(p->val) = IS_OBJECT_EX;\n }", " }\n ht->nNextFreeElement = max_index;", " CHECK_STEP;", "\n return buffer;", "}", "/*\n * arr layout\n * type|key?|bucketlen|buckets\n */\nstatic void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)\n{\n zval *data;\n zend_string *key;\n zend_ulong index;\n swPoolstr *swStr = NULL;\n zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;", " ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)\n {\n SBucketType type = {0};\n type.data_type = Z_TYPE_P(data);\n //start point\n size_t p = buffer->offset;", " if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)\n {\n type.key_type = KEY_TYPE_INDEX;\n type.key_len = 0;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n }\n else\n {\n //seria key\n if (key)\n {\n type.key_type = KEY_TYPE_STRING;\n if ((swStr = swoole_mini_filter_find(key)))\n {\n type.key_len = 3; //means use same string\n SERIA_SET_ENTRY_TYPE(buffer, type);\n if (swStr->offset & 4)\n {\n SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n }\n }\n else\n {\n if (key->len <= 0xff)\n {\n type.key_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 1);\n SERIA_SET_ENTRY_TYPE(buffer, key->len);\n swoole_string_cpy(buffer, key->val, key->len);\n }\n else if (key->len <= 0xffff)\n {//if more than this don't need optimize\n type.key_len = 2;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 2);\n SERIA_SET_ENTRY_SHORT(buffer, key->len);\n swoole_string_cpy(buffer, key->val, key->len);\n }\n else\n {\n type.key_len = 0;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n swoole_mini_filter_add(key, buffer->offset, 3);\n swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);\n }\n }\n }\n else\n {\n type.key_type = KEY_TYPE_INDEX;\n if (index <= 0xff)\n {\n type.key_len = 1;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_TYPE(buffer, index);\n }\n else if (index <= 0xffff)\n {\n type.key_len = 2;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_SHORT(buffer, index);\n }\n else\n {\n type.key_len = 3;\n SERIA_SET_ENTRY_TYPE(buffer, type);\n SERIA_SET_ENTRY_ULONG(buffer, index);\n }", " }\n }\n //seria data\ntry_again:\n switch (Z_TYPE_P(data))\n {\n case IS_STRING:\n {\n if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string\n if (swStr->offset & 4)\n {\n SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);\n }\n }\n else\n {\n if (Z_STRLEN_P(data) <= 0xff)\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 1;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);\n SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));\n swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n }\n else if (Z_STRLEN_P(data) <= 0xffff)\n {\n ((SBucketType*) (buffer->buffer + p))->data_len = 2;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);\n SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));\n swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));\n }\n else\n {//if more than this don't need optimize\n ((SBucketType*) (buffer->buffer + p))->data_len = 0;\n swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);\n swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));\n }\n }\n break;\n }\n case IS_LONG:\n {\n SBucketType* long_type = (SBucketType*) (buffer->buffer + p);\n swoole_serialize_long(buffer, data, long_type);\n break;\n }\n case IS_DOUBLE:\n swoole_set_zend_value(buffer, &(data->value));\n break;\n case IS_REFERENCE:\n data = Z_REFVAL_P(data);\n ((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);\n goto try_again;\n break;\n case IS_ARRAY:\n {\n zend_array *ht = Z_ARRVAL_P(data);", " if (GC_IS_RECURSIVE(ht))\n {", " ((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL; //reset type null", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the array has cycle ref\");\n }\n else\n {\n seria_array_type(ht, buffer, p, buffer->offset);\n if (ZEND_HASH_APPLY_PROTECTION(ht))\n {\n GC_PROTECT_RECURSION(ht);\n swoole_serialize_arr(buffer, ht);\n GC_UNPROTECT_RECURSION(ht);\n }\n else\n {\n swoole_serialize_arr(buffer, ht);\n }", " }\n break;\n }\n //object propterty table is this type\n case IS_INDIRECT:\n data = Z_INDIRECT_P(data);\n zend_uchar type = Z_TYPE_P(data);\n ((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);\n goto try_again;\n break;\n case IS_OBJECT:\n {\n /*\n * layout\n * type | key | namelen | name | bucket len |buckets\n */\n ((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;", " if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))\n {\n GC_PROTECT_RECURSION(Z_OBJPROP_P(data));\n swoole_serialize_object(buffer, data, p);\n GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));\n }\n else\n {\n swoole_serialize_object(buffer, data, p);\n }", " break;\n }\n default://\n break;", " }", " }\n ZEND_HASH_FOREACH_END();\n}", "/*\n * string\n */\nstatic CPINLINE void swoole_serialize_string(seriaString *buffer, zval *zvalue)\n{", " swoole_string_cpy(buffer, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue));\n}", "static CPINLINE zend_string* swoole_unserialize_string(void *buffer, size_t len)\n{", " return zend_string_init(buffer, len, 0);\n}", "/*\n * raw\n */\nstatic CPINLINE void swoole_unserialize_raw(void *buffer, zval *zvalue)\n{", " memcpy(&zvalue->value, buffer, sizeof (zend_value));\n}", "#if 0", "", "/*\n * null\n */\nstatic CPINLINE void swoole_unserialize_null(void *buffer, zval *zvalue)\n{", " memcpy(&zvalue->value, buffer, sizeof (zend_value));\n}\n#endif", "static CPINLINE void swoole_serialize_raw(seriaString *buffer, zval *zvalue)\n{", " swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));\n}", "/*\n * obj layout\n * type|bucket key|name len| name| buket len |buckets\n */\nstatic void swoole_serialize_object(seriaString *buffer, zval *obj, size_t start)\n{\n zend_string *name = Z_OBJCE_P(obj)->name;\n if (GC_IS_RECURSIVE(Z_OBJPROP_P(obj)))\n {\n zend_throw_exception_ex(NULL, 0, \"the object %s has cycle ref.\", name->val);\n return;\n }\n if (name->len > 0xffff)\n {//so long?\n zend_throw_exception_ex(NULL, 0, \"the object name is too long.\");\n }\n else\n {\n SERIA_SET_ENTRY_SHORT(buffer, name->len);\n swoole_string_cpy(buffer, name->val, name->len);\n }", " zend_class_entry *ce = Z_OBJ_P(obj)->ce;\n if (ce && zend_hash_exists(&ce->function_table, Z_STR(swSeriaG.sleep_fname)))\n {\n zval retval;\n if (call_user_function_ex(NULL, obj, &swSeriaG.sleep_fname, &retval, 0, 0, 1, NULL) == SUCCESS)\n {\n if (EG(exception))\n {\n zval_dtor(&retval);\n return;\n }\n if (Z_TYPE(retval) == IS_ARRAY)\n {\n zend_string *prop_key;\n zval *prop_value, *sleep_value;\n const char *prop_name, *class_name;\n size_t prop_key_len;\n int got_num = 0;", " //for the zero malloc\n zend_array tmp_arr;\n zend_array *ht = (zend_array *) & tmp_arr;\n#if PHP_VERSION_ID >= 70300\n _zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0);\n#else\n _zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_CC);\n#endif\n ht->nTableMask = -(ht)->nTableSize;\n ALLOCA_FLAG(use_heap);\n void *ht_addr = do_alloca(HT_SIZE(ht), use_heap);\n HT_SET_DATA_ADDR(ht, ht_addr);\n ht->u.flags |= HASH_FLAG_INITIALIZED;\n HT_HASH_RESET(ht);", " //just clean property do not add null when does not exist\n //we double for each, cause we do not malloc and release it", " ZEND_HASH_FOREACH_STR_KEY_VAL(Z_OBJPROP_P(obj), prop_key, prop_value)\n {\n //get origin property name\n zend_unmangle_property_name_ex(prop_key, &class_name, &prop_name, &prop_key_len);", " ZEND_HASH_FOREACH_VAL(Z_ARRVAL(retval), sleep_value)\n {\n if (Z_TYPE_P(sleep_value) == IS_STRING &&\n Z_STRLEN_P(sleep_value) == prop_key_len &&\n memcmp(Z_STRVAL_P(sleep_value), prop_name, prop_key_len) == 0)\n {\n got_num++;\n //add mangle key,unmangle in unseria\n _zend_hash_add_or_update(ht, prop_key, prop_value, HASH_UPDATE ZEND_FILE_LINE_CC);", " break;\n }", " }\n ZEND_HASH_FOREACH_END();", " }\n ZEND_HASH_FOREACH_END();", " //there some member not in property\n if (zend_hash_num_elements(Z_ARRVAL(retval)) > got_num)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"__sleep() retrun a member but does not exist in property\");", " }\n seria_array_type(ht, buffer, start, buffer->offset);\n swoole_serialize_arr(buffer, ht);\n ZSTR_ALLOCA_FREE(ht_addr, use_heap);\n zval_dtor(&retval);\n return;", " }\n else\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \" __sleep should return an array only containing the \"\n \"names of instance-variables to serialize\");\n zval_dtor(&retval);\n }", " }\n }\n seria_array_type(Z_OBJPROP_P(obj), buffer, start, buffer->offset);\n swoole_serialize_arr(buffer, Z_OBJPROP_P(obj));\n // printf(\"hash2 %u\\n\",ce->properties_info.arData[0].key->h);\n}", "/*\n * for the zero malloc\n */\nstatic CPINLINE zend_string * swoole_string_init(const char *str, size_t len)\n{\n#ifdef ZEND_DEBUG\n return zend_string_init(str, len, 0);\n#else\n ALLOCA_FLAG(use_heap);\n zend_string *ret;\n ZSTR_ALLOCA_INIT(ret, str, len, use_heap);", " return ret;\n#endif\n}", "/*\n * for the zero malloc\n */\nstatic CPINLINE void swoole_string_release(zend_string *str)\n{\n#ifdef ZEND_DEBUG\n zend_string_release(str);\n#else\n //if dont support alloc 0 will ignore\n //if support alloc size is definitely < ZEND_ALLOCA_MAX_SIZE\n ZSTR_ALLOCA_FREE(str, 0);\n#endif\n}", "static CPINLINE zend_class_entry* swoole_try_get_ce(zend_string *class_name)\n{\n //user class , do not support incomplete class now\n zend_class_entry *ce = zend_lookup_class(class_name);\n if (ce)\n {\n return ce;\n }\n // try call unserialize callback and retry lookup\n zval user_func, args[1], retval;", " /* Check for unserialize callback */\n if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\\0'))\n {\n zend_throw_exception_ex(NULL, 0, \"can not find class %s\", class_name->val TSRMLS_CC);\n return NULL;\n }", "", " zend_string *fname = swoole_string_init(ZEND_STRL(PG(unserialize_callback_func)));\n Z_STR(user_func) = fname;\n Z_TYPE_INFO(user_func) = IS_STRING_EX;\n ZVAL_STR(&args[0], class_name);", " call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL);", " swoole_string_release(fname);", " //user class , do not support incomplete class now\n ce = zend_lookup_class(class_name);\n if (!ce)\n {\n zend_throw_exception_ex(NULL, 0, \"can not find class %s\", class_name->val TSRMLS_CC);\n return NULL;\n }\n else\n {\n return ce;\n }\n}", "/*\n * obj layout\n * type| key[0|1] |name len| name| buket len |buckets\n */\nstatic void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag)\n{\n zval property;\n uint32_t arr_num = 0;\n size_t name_len = *((unsigned short*) buffer);", " CHECK_STEP;", " if (!name_len)\n {\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"illegal unserialize data\");\n return NULL;\n }\n buffer += 2;\n zend_string *class_name;", " if (flag == UNSERIALIZE_OBJECT_TO_STDCLASS)", " {\n class_name = swoole_string_init(ZEND_STRL(\"StdClass\"));", " }\n else", " {\n class_name = swoole_string_init((char*) buffer, name_len);\n }\n buffer += name_len;\n zend_class_entry *ce = swoole_try_get_ce(class_name);\n swoole_string_release(class_name);", " CHECK_STEP;", "\n if (!ce)\n {\n return NULL;\n }", " buffer = get_array_real_len(buffer, bucket_len, &arr_num);\n buffer = swoole_unserialize_arr(buffer, &property, arr_num, flag);", " object_init_ex(return_value, ce);\n", " zval *data, *d;", " zend_string *key;\n zend_ulong index;\n", "", " ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(property), index, key, data)\n {\n const char *prop_name, *tmp;\n size_t prop_len;\n if (key)\n {", " if ((d = zend_hash_find(Z_OBJPROP_P(return_value), key)) != NULL)\n {\n if (Z_TYPE_P(d) == IS_INDIRECT)\n {\n d = Z_INDIRECT_P(d);\n }\n zval_dtor(d);\n ZVAL_COPY(d, data);\n }\n else\n {\n zend_unmangle_property_name_ex(key, &tmp, &prop_name, &prop_len);\n zend_update_property(ce, return_value, prop_name, prop_len, data);\n }", " // zend_hash_update(Z_OBJPROP_P(return_value),key,data);\n // zend_update_property(ce, return_value, ZSTR_VAL(key), ZSTR_LEN(key), data);", " }\n else\n {\n zend_hash_next_index_insert(Z_OBJPROP_P(return_value), data);\n }\n }\n ZEND_HASH_FOREACH_END();\n zval_dtor(&property);", " if (ce->constructor)\n {\n // zend_fcall_info fci = {0};\n // zend_fcall_info_cache fcc = {0};\n // fci.size = sizeof (zend_fcall_info);\n // zval retval;\n // ZVAL_UNDEF(&fci.function_name);\n // fci.retval = &retval;\n // fci.param_count = 0;\n // fci.params = NULL;\n // fci.no_separation = 1;\n // fci.object = Z_OBJ_P(return_value);\n //\n // zend_fcall_info_args_ex(&fci, ce->constructor, args);\n //\n // fcc.initialized = 1;\n // fcc.function_handler = ce->constructor;\n // // fcc.calling_scope = EG(scope);\n // fcc.called_scope = Z_OBJCE_P(return_value);\n // fcc.object = Z_OBJ_P(return_value);\n //\n // if (zend_call_function(&fci, &fcc) == FAILURE)\n // {\n // zend_throw_exception_ex(NULL, 0, \"could not call class constructor\");\n // }\n // zend_fcall_info_args_clear(&fci, 1);\n }", "\n //call object __wakeup\n if (zend_hash_str_exists(&ce->function_table, ZEND_STRL(\"__wakeup\")))\n {\n zval ret, wakeup;\n zend_string *fname = swoole_string_init(ZEND_STRL(\"__wakeup\"));\n Z_STR(wakeup) = fname;\n Z_TYPE_INFO(wakeup) = IS_STRING_EX;\n call_user_function_ex(CG(function_table), return_value, &wakeup, &ret, 0, NULL, 1, NULL);\n swoole_string_release(fname);\n zval_ptr_dtor(&ret);\n }", " CHECK_STEP;", " return buffer;", "}", "/*\n * dispatch\n */", "static CPINLINE void swoole_seria_dispatch(seriaString *buffer, zval *zvalue)\n{\nagain:\n switch (Z_TYPE_P(zvalue))\n {\n case IS_NULL:\n case IS_TRUE:\n case IS_FALSE:\n break;\n case IS_LONG:\n {\n SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);\n swoole_serialize_long(buffer, zvalue, type);\n break;\n }\n case IS_DOUBLE:\n swoole_serialize_raw(buffer, zvalue);\n break;\n case IS_STRING:\n swoole_serialize_string(buffer, zvalue);\n break;\n case IS_ARRAY:\n {\n seria_array_type(Z_ARRVAL_P(zvalue), buffer, _STR_HEADER_SIZE, _STR_HEADER_SIZE + 1);\n swoole_serialize_arr(buffer, Z_ARRVAL_P(zvalue));\n swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);\n swoole_mini_filter_clear();\n break;\n }\n case IS_REFERENCE:\n zvalue = Z_REFVAL_P(zvalue);\n goto again;\n break;\n case IS_OBJECT:\n {\n SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);\n type->data_type = IS_UNDEF;\n swoole_serialize_object(buffer, zvalue, _STR_HEADER_SIZE);\n swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);\n swoole_mini_filter_clear();\n break;\n }\n default:\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the type is not supported by swoole serialize.\");", " break;\n }\n}", "PHPAPI zend_string* php_swoole_serialize(zval *zvalue)\n{", " seriaString str;\n swoole_string_new(SERIA_SIZE, &str, Z_TYPE_P(zvalue));\n swoole_seria_dispatch(&str, zvalue); //serialize into a string\n zend_string *z_str = (zend_string *) str.buffer;", " z_str->len = str.offset - _STR_HEADER_SIZE;\n z_str->val[z_str->len] = '\\0';\n z_str->h = 0;\n GC_SET_REFCOUNT(z_str, 1);\n GC_TYPE_INFO(z_str) = IS_STRING_EX;", " return z_str;\n}", "static CPINLINE int swoole_seria_check_eof(void *buffer, size_t len)\n{\n void *eof_str = buffer - sizeof (SBucketType) + len - 3;\n if (memcmp(eof_str, SWOOLE_SERI_EOF, 3) == 0)\n {\n return 0;\n }\n else\n {\n return -1;\n }\n}", "/*\n * buffer is seria string buffer\n * len is string len\n * return_value is unseria bucket\n * args is for the object ctor (can be NULL)\n */\nPHPAPI int php_swoole_unserialize(void *buffer, size_t len, zval *return_value, zval *object_args, long flag)\n{\n SBucketType type = *(SBucketType*) (buffer);\n zend_uchar real_type = type.data_type;", " unseri_buffer_end = buffer + len;", " buffer += sizeof (SBucketType);\n switch (real_type)\n {\n case IS_NULL:\n case IS_TRUE:\n case IS_FALSE:\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_LONG:\n swoole_unserialize_long(buffer, return_value, type);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_DOUBLE:\n swoole_unserialize_raw(buffer, return_value);\n Z_TYPE_INFO_P(return_value) = real_type;\n break;\n case IS_STRING:\n len -= sizeof (SBucketType);\n zend_string *str = swoole_unserialize_string(buffer, len);\n ZVAL_STR(return_value, str);\n break;\n case IS_ARRAY:\n {\n if (swoole_seria_check_eof(buffer, len) < 0)\n {", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;", " }\n unser_start = buffer - sizeof (SBucketType);\n uint32_t num = 0;\n buffer = get_array_real_len(buffer, type.data_len, &num);\n if (!swoole_unserialize_arr(buffer, return_value, num, flag))\n {\n return SW_FALSE;\n }\n break;\n }\n case IS_UNDEF:\n if (swoole_seria_check_eof(buffer, len) < 0)\n {", " php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"detect the error eof\");\n return SW_FALSE;", " }\n unser_start = buffer - sizeof (SBucketType);\n if (!swoole_unserialize_object(buffer, return_value, type.data_len, object_args, flag))\n {\n return SW_FALSE;\n }\n break;\n default:\n php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"the type is not supported by swoole serialize.\");\n return SW_FALSE;\n }", " return SW_TRUE;\n}", "static PHP_METHOD(swoole_serialize, pack)\n{\n zval *zvalue;\n zend_size_t is_fast = 0;", " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z|l\", &zvalue, &is_fast) == FAILURE)\n {\n RETURN_FALSE;\n }\n swSeriaG.pack_string = !is_fast;\n zend_string *z_str = php_swoole_serialize(zvalue);", " RETURN_STR(z_str);\n}", "static PHP_METHOD(swoole_serialize, unpack)\n{\n char *buffer = NULL;\n size_t arg_len;\n zval *args = NULL; //for object\n long flag = 0;", " if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|la\", &buffer, &arg_len, &flag, &args) == FAILURE)\n {\n RETURN_FALSE;\n }\n if (!php_swoole_unserialize(buffer, arg_len, return_value, args, flag))\n {\n RETURN_FALSE;\n }\n}", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1531], "buggy_code_start_loc": [54], "filenames": ["swoole_serialize.c"], "fixing_code_end_loc": [1541], "fixing_code_start_loc": [55], "message": "The unpack implementation in Swoole version 4.0.4 lacks correct size checks in the deserialization process. An attacker can craft a serialized object to exploit this vulnerability and cause a SEGV.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:swoole:swoole:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "93EF17F5-CCB3-4CB8-AFE3-706C531F3B1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The unpack implementation in Swoole version 4.0.4 lacks correct size checks in the deserialization process. An attacker can craft a serialized object to exploit this vulnerability and cause a SEGV."}, {"lang": "es", "value": "La implementaci\u00f3n de desempaquetado en la versi\u00f3n 4.0.4 de Swoole carece de controles de tama\u00f1o correctos en el proceso de deserializaci\u00f3n. Un atacante puede crear un objeto serializado para explotar esta vulnerabilidad y provocar un SEGV."}], "evaluatorComment": null, "id": "CVE-2018-15503", "lastModified": "2018-11-08T20:49:48.653", "metrics": {"cvssMetricV2": [{"acInsufInfo": true, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-18T02:29:01.903", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/swoole/swoole-src/commit/4cdbce5d9bf2fe596bb6acd7d6611f9e8c253a76"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Vendor Advisory"], "url": "https://github.com/swoole/swoole-src/issues/1882"}, {"source": "cve@mitre.org", "tags": ["Technical Description", "Third Party Advisory"], "url": "https://x-c3ll.github.io/posts/swoole-deserialization-cve-2018-15503/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-502"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/swoole/swoole-src/commit/4cdbce5d9bf2fe596bb6acd7d6611f9e8c253a76"}, "type": "CWE-502"}
119
Determine whether the {function_name} code is vulnerable or not.
[ "#include <config.h>", "#include \"ftpd.h\"\n#include \"utils.h\"", "#ifdef WITH_DMALLOC\n# include <dmalloc.h>\n#endif", "#ifdef HAVE_LIBSODIUM\n# if !defined(pure_memzero) || !defined(pure_memcmp)\n# error pure_memzero/pure_memcmp not defined\n# endif\n#else", "void pure_memzero(void * const pnt, const size_t len)\n{\n# ifdef HAVE_EXPLICIT_BZERO\n explicit_bzero(pnt, len);\n# else\n volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;\n size_t i = (size_t) 0U;", " while (i < len) {\n pnt_[i++] = 0U;\n }\n# endif\n}", "int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)\n{\n const unsigned char *b1 = (const unsigned char *) b1_;\n const unsigned char *b2 = (const unsigned char *) b2_;\n size_t i;\n unsigned char d = (unsigned char) 0U;", " for (i = 0U; i < len; i++) {\n d |= b1[i] ^ b2[i];\n }\n return (int) ((1 & ((d - 1) >> 8)) - 1);\n}", "#endif", "int pure_strcmp(const char * const s1, const char * const s2)\n{", " return pure_memcmp(s1, s2, strlen(s1) + 1U);", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [49], "buggy_code_start_loc": [48], "filenames": ["src/utils.c"], "fixing_code_end_loc": [55], "fixing_code_start_loc": [48], "message": "An issue was discovered in Pure-FTPd 1.0.49. An out-of-bounds (OOB) read has been detected in the pure_strcmp function in utils.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pureftpd:pure-ftpd:1.0.49:*:*:*:*:*:*:*", "matchCriteriaId": "E3D4D55C-F61A-4B98-BB70-D459F7195CD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in Pure-FTPd 1.0.49. An out-of-bounds (OOB) read has been detected in the pure_strcmp function in utils.c."}, {"lang": "es", "value": "Se detect\u00f3 un problema en Pure-FTPd versi\u00f3n 1.0.49. Ha sido detectado una lectura fuera de l\u00edmites (OOB) en la funci\u00f3n pure_strcmp en el archivo utils.c."}], "evaluatorComment": null, "id": "CVE-2020-9365", "lastModified": "2020-11-16T19:32:39.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-02-24T16:15:13.313", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jedisct1/pure-ftpd/commit/bf6fcd4935e95128cf22af5924cdc8fe5c0579da"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/22P44PECZWNDP7CMBL7NRBMNFS73C5Z2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/B5NSUDWXZVWUCL6R2PTX3KBB42Z62CA5/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U5DBVHJCXWRSJPNJQCJQCKZF6ZDPZCKA/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202003-54"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e"}, "type": "CWE-125"}
120
Determine whether the {function_name} code is vulnerable or not.
[ "#include <config.h>", "#include \"ftpd.h\"\n#include \"utils.h\"", "#ifdef WITH_DMALLOC\n# include <dmalloc.h>\n#endif", "#ifdef HAVE_LIBSODIUM\n# if !defined(pure_memzero) || !defined(pure_memcmp)\n# error pure_memzero/pure_memcmp not defined\n# endif\n#else", "void pure_memzero(void * const pnt, const size_t len)\n{\n# ifdef HAVE_EXPLICIT_BZERO\n explicit_bzero(pnt, len);\n# else\n volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;\n size_t i = (size_t) 0U;", " while (i < len) {\n pnt_[i++] = 0U;\n }\n# endif\n}", "int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)\n{\n const unsigned char *b1 = (const unsigned char *) b1_;\n const unsigned char *b2 = (const unsigned char *) b2_;\n size_t i;\n unsigned char d = (unsigned char) 0U;", " for (i = 0U; i < len; i++) {\n d |= b1[i] ^ b2[i];\n }\n return (int) ((1 & ((d - 1) >> 8)) - 1);\n}", "#endif", "int pure_strcmp(const char * const s1, const char * const s2)\n{", " const size_t s1_len = strlen(s1);\n const size_t s2_len = strlen(s2);", " if (s1_len != s2_len) {\n return -1;\n }\n return pure_memcmp(s1, s2, s1_len);", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [49], "buggy_code_start_loc": [48], "filenames": ["src/utils.c"], "fixing_code_end_loc": [55], "fixing_code_start_loc": [48], "message": "An issue was discovered in Pure-FTPd 1.0.49. An out-of-bounds (OOB) read has been detected in the pure_strcmp function in utils.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pureftpd:pure-ftpd:1.0.49:*:*:*:*:*:*:*", "matchCriteriaId": "E3D4D55C-F61A-4B98-BB70-D459F7195CD6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:32:*:*:*:*:*:*:*", "matchCriteriaId": "36D96259-24BD-44E2-96D9-78CE1D41F956", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in Pure-FTPd 1.0.49. An out-of-bounds (OOB) read has been detected in the pure_strcmp function in utils.c."}, {"lang": "es", "value": "Se detect\u00f3 un problema en Pure-FTPd versi\u00f3n 1.0.49. Ha sido detectado una lectura fuera de l\u00edmites (OOB) en la funci\u00f3n pure_strcmp en el archivo utils.c."}], "evaluatorComment": null, "id": "CVE-2020-9365", "lastModified": "2020-11-16T19:32:39.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-02-24T16:15:13.313", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jedisct1/pure-ftpd/commit/bf6fcd4935e95128cf22af5924cdc8fe5c0579da"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/22P44PECZWNDP7CMBL7NRBMNFS73C5Z2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/B5NSUDWXZVWUCL6R2PTX3KBB42Z62CA5/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U5DBVHJCXWRSJPNJQCJQCKZF6ZDPZCKA/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202003-54"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jedisct1/pure-ftpd/commit/36c6d268cb190282a2c17106acfd31863121b58e"}, "type": "CWE-125"}
120
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2018 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#ifndef __FLATPAK_BWRAP_H__\n#define __FLATPAK_BWRAP_H__", "typedef struct\n{\n GPtrArray *argv;\n GArray *noinherit_fds; /* Just keep these open while the bwrap lives */\n GArray *fds;\n GStrv envp;\n} FlatpakBwrap;", "extern char *flatpak_bwrap_empty_env[1];", "FlatpakBwrap *flatpak_bwrap_new (char **env);\nvoid flatpak_bwrap_free (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_set_env (FlatpakBwrap *bwrap,\n const char *variable,\n const char *value,\n gboolean overwrite);\ngboolean flatpak_bwrap_is_empty (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_finish (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable);\nvoid flatpak_bwrap_add_arg (FlatpakBwrap *bwrap,\n const char *arg);", "", "void flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd);\nvoid flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n int fd);\nvoid flatpak_bwrap_add_args (FlatpakBwrap *bwrap,\n ...) G_GNUC_NULL_TERMINATED;\nvoid flatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap,\n const char *format,\n ...) G_GNUC_PRINTF (2, 3);\nvoid flatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,\n char **args,\n int len);\nvoid flatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,\n FlatpakBwrap *other); /* Steals the fds */\nvoid flatpak_bwrap_append_args (FlatpakBwrap *bwrap,\n GPtrArray *other_array);\nvoid flatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,\n const char *op,\n int fd,\n const char *path_optional);\ngboolean flatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,\n const char *name,\n const char *content,\n gssize content_size,\n const char *path,\n GError **error);\nvoid flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest);", "", "gboolean flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,\n gboolean one_arg,\n GError **error);", "void flatpak_bwrap_child_setup_cb (gpointer user_data);\nvoid flatpak_bwrap_child_setup (GArray *fd_array,\n gboolean close_fd_workaround);", "G_DEFINE_AUTOPTR_CLEANUP_FUNC (FlatpakBwrap, flatpak_bwrap_free)", "\n#endif /* __FLATPAK_BWRAP_H__ */" ]
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2018 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#ifndef __FLATPAK_BWRAP_H__\n#define __FLATPAK_BWRAP_H__", "typedef struct\n{\n GPtrArray *argv;\n GArray *noinherit_fds; /* Just keep these open while the bwrap lives */\n GArray *fds;\n GStrv envp;\n} FlatpakBwrap;", "extern char *flatpak_bwrap_empty_env[1];", "FlatpakBwrap *flatpak_bwrap_new (char **env);\nvoid flatpak_bwrap_free (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_set_env (FlatpakBwrap *bwrap,\n const char *variable,\n const char *value,\n gboolean overwrite);\ngboolean flatpak_bwrap_is_empty (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_finish (FlatpakBwrap *bwrap);\nvoid flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable);\nvoid flatpak_bwrap_add_arg (FlatpakBwrap *bwrap,\n const char *arg);", "void flatpak_bwrap_take_arg (FlatpakBwrap *bwrap,\n char *arg);", "void flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd);\nvoid flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n int fd);\nvoid flatpak_bwrap_add_args (FlatpakBwrap *bwrap,\n ...) G_GNUC_NULL_TERMINATED;\nvoid flatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap,\n const char *format,\n ...) G_GNUC_PRINTF (2, 3);\nvoid flatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,\n char **args,\n int len);\nvoid flatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,\n FlatpakBwrap *other); /* Steals the fds */\nvoid flatpak_bwrap_append_args (FlatpakBwrap *bwrap,\n GPtrArray *other_array);\nvoid flatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,\n const char *op,\n int fd,\n const char *path_optional);\ngboolean flatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,\n const char *name,\n const char *content,\n gssize content_size,\n const char *path,\n GError **error);\nvoid flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest);", "void flatpak_bwrap_envp_to_args (FlatpakBwrap *bwrap);", "gboolean flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,\n gboolean one_arg,\n GError **error);", "void flatpak_bwrap_child_setup_cb (gpointer user_data);\nvoid flatpak_bwrap_child_setup (GArray *fd_array,\n gboolean close_fd_workaround);", "G_DEFINE_AUTOPTR_CLEANUP_FUNC (FlatpakBwrap, flatpak_bwrap_free)", "\n#endif /* __FLATPAK_BWRAP_H__ */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2018 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#include \"config.h\"", "#include <string.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/utsname.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/personality.h>\n#include <grp.h>\n#include <unistd.h>\n#include <gio/gunixfdlist.h>", "#include <glib/gi18n-lib.h>", "#include <gio/gio.h>\n#include \"libglnx/libglnx.h\"", "#include \"flatpak-bwrap-private.h\"\n#include \"flatpak-utils-private.h\"\n#include \"flatpak-utils-base-private.h\"", "static void\nclear_fd (gpointer data)\n{\n int *fd_p = data;", " if (fd_p != NULL && *fd_p != -1)\n close (*fd_p);\n}", "char *flatpak_bwrap_empty_env[] = { NULL };", "FlatpakBwrap *\nflatpak_bwrap_new (char **env)\n{\n FlatpakBwrap *bwrap = g_new0 (FlatpakBwrap, 1);", " bwrap->argv = g_ptr_array_new_with_free_func (g_free);\n bwrap->noinherit_fds = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_set_clear_func (bwrap->noinherit_fds, clear_fd);\n bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_set_clear_func (bwrap->fds, clear_fd);", " if (env)\n bwrap->envp = g_strdupv (env);\n else\n bwrap->envp = g_get_environ ();", " return bwrap;\n}", "void\nflatpak_bwrap_free (FlatpakBwrap *bwrap)\n{\n g_ptr_array_unref (bwrap->argv);\n g_array_unref (bwrap->noinherit_fds);\n g_array_unref (bwrap->fds);\n g_strfreev (bwrap->envp);\n g_free (bwrap);\n}", "gboolean\nflatpak_bwrap_is_empty (FlatpakBwrap *bwrap)\n{\n return bwrap->argv->len == 0;\n}", "void\nflatpak_bwrap_set_env (FlatpakBwrap *bwrap,\n const char *variable,\n const char *value,\n gboolean overwrite)\n{\n bwrap->envp = g_environ_setenv (bwrap->envp, variable, value, overwrite);\n}", "void\nflatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable)\n{\n bwrap->envp = g_environ_unsetenv (bwrap->envp, variable);\n}", "void\nflatpak_bwrap_add_arg (FlatpakBwrap *bwrap, const char *arg)\n{\n g_ptr_array_add (bwrap->argv, g_strdup (arg));\n}\n", "", "void\nflatpak_bwrap_finish (FlatpakBwrap *bwrap)\n{\n g_ptr_array_add (bwrap->argv, NULL);\n}", "void\nflatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd)\n{\n g_array_append_val (bwrap->noinherit_fds, fd);\n}", "void\nflatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n int fd)\n{\n g_array_append_val (bwrap->fds, fd);\n}", "void\nflatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap, const char *format, ...)\n{\n va_list args;", " va_start (args, format);\n g_ptr_array_add (bwrap->argv, g_strdup_vprintf (format, args));\n va_end (args);\n}\nvoid\nflatpak_bwrap_add_args (FlatpakBwrap *bwrap, ...)\n{\n va_list args;\n const gchar *arg;", " va_start (args, bwrap);\n while ((arg = va_arg (args, const gchar *)))\n flatpak_bwrap_add_arg (bwrap, arg);\n va_end (args);\n}", "void\nflatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,\n char **args,\n int len)\n{\n int i;", " if (len < 0)\n len = g_strv_length (args);", " for (i = 0; i < len; i++)\n g_ptr_array_add (bwrap->argv, g_strdup (args[i]));\n}", "void\nflatpak_bwrap_append_args (FlatpakBwrap *bwrap,\n GPtrArray *other_array)\n{\n flatpak_bwrap_append_argsv (bwrap,\n (char **) other_array->pdata,\n other_array->len);\n}", "static int *\nflatpak_bwrap_steal_fds (FlatpakBwrap *bwrap,\n gsize *len_out)\n{\n gsize len = bwrap->fds->len;\n int *res = (int *) g_array_free (bwrap->fds, FALSE);", " bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));\n *len_out = len;\n return res;\n}", "void\nflatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,\n FlatpakBwrap *other)\n{\n g_autofree int *fds = NULL;\n gsize n_fds, i;", " fds = flatpak_bwrap_steal_fds (other, &n_fds);\n for (i = 0; i < n_fds; i++)\n flatpak_bwrap_add_fd (bwrap, fds[i]);", " flatpak_bwrap_append_argsv (bwrap,\n (char **) other->argv->pdata,\n other->argv->len);", " for (i = 0; other->envp[i] != NULL; i++)\n {\n char *key_val = other->envp[i];\n char *eq = strchr (key_val, '=');\n if (eq)\n {\n g_autofree char *key = g_strndup (key_val, eq - key_val);\n flatpak_bwrap_set_env (bwrap,\n key, eq + 1, TRUE);\n }\n }\n}", "void\nflatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,\n const char *op,\n int fd,\n const char *path_optional)\n{\n g_autofree char *fd_str = g_strdup_printf (\"%d\", fd);", " flatpak_bwrap_add_fd (bwrap, fd);\n flatpak_bwrap_add_args (bwrap,\n op, fd_str, path_optional,\n NULL);\n}", "\n/* Given a buffer @content of size @content_size, generate a fd (memfd if available)\n * of the data. The @name parameter is used by memfd_create() as a debugging aid;\n * it has no semantic meaning. The bwrap command line will inject it into the target\n * container as @path.\n */\ngboolean\nflatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,\n const char *name,\n const char *content,\n gssize content_size,\n const char *path,\n GError **error)\n{\n g_auto(GLnxTmpfile) args_tmpf = { 0, };", " if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, name, content, content_size, error))\n return FALSE;", " flatpak_bwrap_add_args_data_fd (bwrap, \"--ro-bind-data\", glnx_steal_fd (&args_tmpf.fd), path);\n return TRUE;\n}", "/* This resolves the target here rather than in bwrap, because it may\n * not resolve in bwrap setup due to absolute symlinks conflicting\n * with /newroot root. For example, dest could be inside\n * ~/.var/app/XXX where XXX is an absolute symlink. However, in the\n * usecases here the destination file often doesn't exist, so we\n * only resolve the directory part.\n */\nvoid\nflatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest)\n{\n g_autofree char *dest_dirname = g_path_get_dirname (dest);\n g_autofree char *dest_dirname_real = realpath (dest_dirname, NULL);", " if (dest_dirname_real)\n {\n g_autofree char *dest_basename = g_path_get_basename (dest);\n g_autofree char *dest_real = g_build_filename (dest_dirname_real, dest_basename, NULL);\n flatpak_bwrap_add_args (bwrap, type, src, dest_real, NULL);\n }\n}\n", "", "gboolean\nflatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,\n gboolean one_arg,\n GError **error)\n{\n g_autofree gchar *data = NULL;\n gchar *ptr;\n gint i;\n gsize data_len = 0;\n int fd;\n g_auto(GLnxTmpfile) args_tmpf = { 0, };", " if (end == -1)\n end = bwrap->argv->len;", " for (i = start; i < end; i++)\n data_len += strlen (bwrap->argv->pdata[i]) + 1;", " data = g_new (gchar, data_len);\n ptr = data;\n for (i = start; i < end; i++)\n ptr = g_stpcpy (ptr, bwrap->argv->pdata[i]) + 1;", " if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, \"bwrap-args\", data, data_len, error))\n return FALSE;", " fd = glnx_steal_fd (&args_tmpf.fd);", " {\n g_autofree char *commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata + start, end - start);\n flatpak_debug2 (\"bwrap --args %d = %s\", fd, commandline);\n }", " flatpak_bwrap_add_fd (bwrap, fd);\n g_ptr_array_remove_range (bwrap->argv, start, end - start);\n if (one_arg)\n {\n g_ptr_array_insert (bwrap->argv, start, g_strdup_printf (\"--args=%d\", fd));\n }\n else\n {\n g_ptr_array_insert (bwrap->argv, start, g_strdup (\"--args\"));\n g_ptr_array_insert (bwrap->argv, start + 1, g_strdup_printf (\"%d\", fd));\n }", " return TRUE;\n}", "void\nflatpak_bwrap_child_setup (GArray *fd_array,\n gboolean close_fd_workaround)\n{\n int i;", " if (close_fd_workaround)\n flatpak_close_fds_workaround (3);", " /* If no fd_array was specified, don't care. */\n if (fd_array == NULL)\n return;", " /* Otherwise, mark not - close-on-exec all the fds in the array */\n for (i = 0; i < fd_array->len; i++)\n {\n int fd = g_array_index (fd_array, int, i);", " /* We also seek all fds to the start, because this lets\n us use the same fd_array multiple times */\n if (lseek (fd, 0, SEEK_SET) < 0)\n {\n /* Ignore the error, this happens on e.g. pipe fds */\n }", " fcntl (fd, F_SETFD, 0);\n }\n}", "/* Unset FD_CLOEXEC on the array of fds passed in @user_data */\nvoid\nflatpak_bwrap_child_setup_cb (gpointer user_data)\n{\n GArray *fd_array = user_data;", " flatpak_bwrap_child_setup (fd_array, TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2018 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#include \"config.h\"", "#include <string.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/utsname.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/personality.h>\n#include <grp.h>\n#include <unistd.h>\n#include <gio/gunixfdlist.h>", "#include <glib/gi18n-lib.h>", "#include <gio/gio.h>\n#include \"libglnx/libglnx.h\"", "#include \"flatpak-bwrap-private.h\"\n#include \"flatpak-utils-private.h\"\n#include \"flatpak-utils-base-private.h\"", "static void\nclear_fd (gpointer data)\n{\n int *fd_p = data;", " if (fd_p != NULL && *fd_p != -1)\n close (*fd_p);\n}", "char *flatpak_bwrap_empty_env[] = { NULL };", "FlatpakBwrap *\nflatpak_bwrap_new (char **env)\n{\n FlatpakBwrap *bwrap = g_new0 (FlatpakBwrap, 1);", " bwrap->argv = g_ptr_array_new_with_free_func (g_free);\n bwrap->noinherit_fds = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_set_clear_func (bwrap->noinherit_fds, clear_fd);\n bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_set_clear_func (bwrap->fds, clear_fd);", " if (env)\n bwrap->envp = g_strdupv (env);\n else\n bwrap->envp = g_get_environ ();", " return bwrap;\n}", "void\nflatpak_bwrap_free (FlatpakBwrap *bwrap)\n{\n g_ptr_array_unref (bwrap->argv);\n g_array_unref (bwrap->noinherit_fds);\n g_array_unref (bwrap->fds);\n g_strfreev (bwrap->envp);\n g_free (bwrap);\n}", "gboolean\nflatpak_bwrap_is_empty (FlatpakBwrap *bwrap)\n{\n return bwrap->argv->len == 0;\n}", "void\nflatpak_bwrap_set_env (FlatpakBwrap *bwrap,\n const char *variable,\n const char *value,\n gboolean overwrite)\n{\n bwrap->envp = g_environ_setenv (bwrap->envp, variable, value, overwrite);\n}", "void\nflatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable)\n{\n bwrap->envp = g_environ_unsetenv (bwrap->envp, variable);\n}", "void\nflatpak_bwrap_add_arg (FlatpakBwrap *bwrap, const char *arg)\n{\n g_ptr_array_add (bwrap->argv, g_strdup (arg));\n}\n", "/*\n * flatpak_bwrap_take_arg:\n * @arg: (transfer full): Take ownership of this argument\n *\n * Add @arg to @bwrap's argv, taking ownership of the pointer.\n */\nvoid\nflatpak_bwrap_take_arg (FlatpakBwrap *bwrap, char *arg)\n{\n g_ptr_array_add (bwrap->argv, arg);\n}\n", "void\nflatpak_bwrap_finish (FlatpakBwrap *bwrap)\n{\n g_ptr_array_add (bwrap->argv, NULL);\n}", "void\nflatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd)\n{\n g_array_append_val (bwrap->noinherit_fds, fd);\n}", "void\nflatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n int fd)\n{\n g_array_append_val (bwrap->fds, fd);\n}", "void\nflatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap, const char *format, ...)\n{\n va_list args;", " va_start (args, format);\n g_ptr_array_add (bwrap->argv, g_strdup_vprintf (format, args));\n va_end (args);\n}\nvoid\nflatpak_bwrap_add_args (FlatpakBwrap *bwrap, ...)\n{\n va_list args;\n const gchar *arg;", " va_start (args, bwrap);\n while ((arg = va_arg (args, const gchar *)))\n flatpak_bwrap_add_arg (bwrap, arg);\n va_end (args);\n}", "void\nflatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,\n char **args,\n int len)\n{\n int i;", " if (len < 0)\n len = g_strv_length (args);", " for (i = 0; i < len; i++)\n g_ptr_array_add (bwrap->argv, g_strdup (args[i]));\n}", "void\nflatpak_bwrap_append_args (FlatpakBwrap *bwrap,\n GPtrArray *other_array)\n{\n flatpak_bwrap_append_argsv (bwrap,\n (char **) other_array->pdata,\n other_array->len);\n}", "static int *\nflatpak_bwrap_steal_fds (FlatpakBwrap *bwrap,\n gsize *len_out)\n{\n gsize len = bwrap->fds->len;\n int *res = (int *) g_array_free (bwrap->fds, FALSE);", " bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));\n *len_out = len;\n return res;\n}", "void\nflatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,\n FlatpakBwrap *other)\n{\n g_autofree int *fds = NULL;\n gsize n_fds, i;", " fds = flatpak_bwrap_steal_fds (other, &n_fds);\n for (i = 0; i < n_fds; i++)\n flatpak_bwrap_add_fd (bwrap, fds[i]);", " flatpak_bwrap_append_argsv (bwrap,\n (char **) other->argv->pdata,\n other->argv->len);", " for (i = 0; other->envp[i] != NULL; i++)\n {\n char *key_val = other->envp[i];\n char *eq = strchr (key_val, '=');\n if (eq)\n {\n g_autofree char *key = g_strndup (key_val, eq - key_val);\n flatpak_bwrap_set_env (bwrap,\n key, eq + 1, TRUE);\n }\n }\n}", "void\nflatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,\n const char *op,\n int fd,\n const char *path_optional)\n{\n g_autofree char *fd_str = g_strdup_printf (\"%d\", fd);", " flatpak_bwrap_add_fd (bwrap, fd);\n flatpak_bwrap_add_args (bwrap,\n op, fd_str, path_optional,\n NULL);\n}", "\n/* Given a buffer @content of size @content_size, generate a fd (memfd if available)\n * of the data. The @name parameter is used by memfd_create() as a debugging aid;\n * it has no semantic meaning. The bwrap command line will inject it into the target\n * container as @path.\n */\ngboolean\nflatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,\n const char *name,\n const char *content,\n gssize content_size,\n const char *path,\n GError **error)\n{\n g_auto(GLnxTmpfile) args_tmpf = { 0, };", " if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, name, content, content_size, error))\n return FALSE;", " flatpak_bwrap_add_args_data_fd (bwrap, \"--ro-bind-data\", glnx_steal_fd (&args_tmpf.fd), path);\n return TRUE;\n}", "/* This resolves the target here rather than in bwrap, because it may\n * not resolve in bwrap setup due to absolute symlinks conflicting\n * with /newroot root. For example, dest could be inside\n * ~/.var/app/XXX where XXX is an absolute symlink. However, in the\n * usecases here the destination file often doesn't exist, so we\n * only resolve the directory part.\n */\nvoid\nflatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest)\n{\n g_autofree char *dest_dirname = g_path_get_dirname (dest);\n g_autofree char *dest_dirname_real = realpath (dest_dirname, NULL);", " if (dest_dirname_real)\n {\n g_autofree char *dest_basename = g_path_get_basename (dest);\n g_autofree char *dest_real = g_build_filename (dest_dirname_real, dest_basename, NULL);\n flatpak_bwrap_add_args (bwrap, type, src, dest_real, NULL);\n }\n}\n", "/*\n * Convert bwrap->envp into a series of --setenv arguments for bwrap(1),\n * assumed to be applied to an empty environment. Reset envp to be an\n * empty environment.\n */\nvoid\nflatpak_bwrap_envp_to_args (FlatpakBwrap *bwrap)\n{\n gsize i;", " for (i = 0; bwrap->envp[i] != NULL; i++)\n {\n char *key_val = bwrap->envp[i];\n char *eq = strchr (key_val, '=');", " if (eq)\n {\n flatpak_bwrap_add_arg (bwrap, \"--setenv\");\n flatpak_bwrap_take_arg (bwrap, g_strndup (key_val, eq - key_val));\n flatpak_bwrap_add_arg (bwrap, eq + 1);\n }\n else\n {\n g_warn_if_reached ();\n }\n }", " g_strfreev (g_steal_pointer (&bwrap->envp));\n bwrap->envp = g_strdupv (flatpak_bwrap_empty_env);\n}\n", "gboolean\nflatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,\n gboolean one_arg,\n GError **error)\n{\n g_autofree gchar *data = NULL;\n gchar *ptr;\n gint i;\n gsize data_len = 0;\n int fd;\n g_auto(GLnxTmpfile) args_tmpf = { 0, };", " if (end == -1)\n end = bwrap->argv->len;", " for (i = start; i < end; i++)\n data_len += strlen (bwrap->argv->pdata[i]) + 1;", " data = g_new (gchar, data_len);\n ptr = data;\n for (i = start; i < end; i++)\n ptr = g_stpcpy (ptr, bwrap->argv->pdata[i]) + 1;", " if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, \"bwrap-args\", data, data_len, error))\n return FALSE;", " fd = glnx_steal_fd (&args_tmpf.fd);", " {\n g_autofree char *commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata + start, end - start);\n flatpak_debug2 (\"bwrap --args %d = %s\", fd, commandline);\n }", " flatpak_bwrap_add_fd (bwrap, fd);\n g_ptr_array_remove_range (bwrap->argv, start, end - start);\n if (one_arg)\n {\n g_ptr_array_insert (bwrap->argv, start, g_strdup_printf (\"--args=%d\", fd));\n }\n else\n {\n g_ptr_array_insert (bwrap->argv, start, g_strdup (\"--args\"));\n g_ptr_array_insert (bwrap->argv, start + 1, g_strdup_printf (\"%d\", fd));\n }", " return TRUE;\n}", "void\nflatpak_bwrap_child_setup (GArray *fd_array,\n gboolean close_fd_workaround)\n{\n int i;", " if (close_fd_workaround)\n flatpak_close_fds_workaround (3);", " /* If no fd_array was specified, don't care. */\n if (fd_array == NULL)\n return;", " /* Otherwise, mark not - close-on-exec all the fds in the array */\n for (i = 0; i < fd_array->len; i++)\n {\n int fd = g_array_index (fd_array, int, i);", " /* We also seek all fds to the start, because this lets\n us use the same fd_array multiple times */\n if (lseek (fd, 0, SEEK_SET) < 0)\n {\n /* Ignore the error, this happens on e.g. pipe fds */\n }", " fcntl (fd, F_SETFD, 0);\n }\n}", "/* Unset FD_CLOEXEC on the array of fds passed in @user_data */\nvoid\nflatpak_bwrap_child_setup_cb (gpointer user_data)\n{\n GArray *fd_array = user_data;", " flatpak_bwrap_child_setup (fd_array, TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2019 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#include \"config.h\"", "#include <string.h>\n#include <ctype.h>\n#include <fcntl.h>\n#include <gio/gdesktopappinfo.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/utsname.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/vfs.h>\n#include <sys/personality.h>\n#include <grp.h>\n#include <unistd.h>\n#include <gio/gunixfdlist.h>\n#ifdef HAVE_DCONF\n#include <dconf/dconf.h>\n#endif\n#ifdef HAVE_LIBMALCONTENT\n#include <libmalcontent/malcontent.h>\n#endif", "#ifdef ENABLE_SECCOMP\n#include <seccomp.h>\n#endif", "#ifdef ENABLE_XAUTH\n#include <X11/Xauth.h>\n#endif", "#include <glib/gi18n-lib.h>", "#include <gio/gio.h>\n#include \"libglnx/libglnx.h\"", "#include \"flatpak-run-private.h\"\n#include \"flatpak-proxy.h\"\n#include \"flatpak-utils-base-private.h\"\n#include \"flatpak-dir-private.h\"\n#include \"flatpak-instance-private.h\"\n#include \"flatpak-systemd-dbus-generated.h\"\n#include \"flatpak-document-dbus-generated.h\"\n#include \"flatpak-error.h\"", "#define DEFAULT_SHELL \"/bin/sh\"", "const char * const abs_usrmerged_dirs[] =\n{\n \"/bin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/sbin\",\n NULL\n};\nconst char * const *flatpak_abs_usrmerged_dirs = abs_usrmerged_dirs;", "static char *\nextract_unix_path_from_dbus_address (const char *address)\n{\n const char *path, *path_end;", " if (address == NULL)\n return NULL;", " if (!g_str_has_prefix (address, \"unix:\"))\n return NULL;", " path = strstr (address, \"path=\");\n if (path == NULL)\n return NULL;\n path += strlen (\"path=\");\n path_end = path;\n while (*path_end != 0 && *path_end != ',')\n path_end++;", " return g_strndup (path, path_end - path);\n}", "#ifdef ENABLE_XAUTH\nstatic gboolean\nauth_streq (char *str,\n char *au_str,\n int au_len)\n{\n return au_len == strlen (str) && memcmp (str, au_str, au_len) == 0;\n}", "static gboolean\nxauth_entry_should_propagate (Xauth *xa,\n char *hostname,\n char *number)\n{\n /* ensure entry isn't for remote access */\n if (xa->family != FamilyLocal && xa->family != FamilyWild)\n return FALSE;", " /* ensure entry is for this machine */\n if (xa->family == FamilyLocal && !auth_streq (hostname, xa->address, xa->address_length))\n return FALSE;", " /* ensure entry is for this session */\n if (xa->number != NULL && !auth_streq (number, xa->number, xa->number_length))\n return FALSE;", " return TRUE;\n}", "static void\nwrite_xauth (char *number, FILE *output)\n{\n Xauth *xa, local_xa;\n char *filename;\n FILE *f;\n struct utsname unames;", " if (uname (&unames))\n {\n g_warning (\"uname failed\");\n return;\n }", " filename = XauFileName ();\n f = fopen (filename, \"rb\");\n if (f == NULL)\n return;", " while (TRUE)\n {\n xa = XauReadAuth (f);\n if (xa == NULL)\n break;\n if (xauth_entry_should_propagate (xa, unames.nodename, number))\n {\n local_xa = *xa;\n if (local_xa.number)\n {\n local_xa.number = \"99\";\n local_xa.number_length = 2;\n }", " if (!XauWriteAuth (output, &local_xa))\n g_warning (\"xauth write error\");\n }", " XauDisposeAuth (xa);\n }", " fclose (f);\n}\n#endif /* ENABLE_XAUTH */", "static void\nflatpak_run_add_x11_args (FlatpakBwrap *bwrap,\n gboolean allowed)\n{\n g_autofree char *x11_socket = NULL;\n const char *display;", " /* Always cover /tmp/.X11-unix, that way we never see the host one in case\n * we have access to the host /tmp. If you request X access we'll put the right\n * thing in this anyway.\n */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/tmp/.X11-unix\",\n NULL);", " if (!allowed)\n {\n flatpak_bwrap_unset_env (bwrap, \"DISPLAY\");\n return;\n }", " g_debug (\"Allowing x11 access\");", " display = g_getenv (\"DISPLAY\");\n if (display && display[0] == ':' && g_ascii_isdigit (display[1]))\n {\n const char *display_nr = &display[1];\n const char *display_nr_end = display_nr;\n g_autofree char *d = NULL;", " while (g_ascii_isdigit (*display_nr_end))\n display_nr_end++;", " d = g_strndup (display_nr, display_nr_end - display_nr);\n x11_socket = g_strdup_printf (\"/tmp/.X11-unix/X%s\", d);", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", x11_socket, \"/tmp/.X11-unix/X99\",\n NULL);\n flatpak_bwrap_set_env (bwrap, \"DISPLAY\", \":99.0\", TRUE);", "#ifdef ENABLE_XAUTH\n g_auto(GLnxTmpfile) xauth_tmpf = { 0, };", " if (glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &xauth_tmpf, NULL))\n {\n FILE *output = fdopen (xauth_tmpf.fd, \"wb\");\n if (output != NULL)\n {\n /* fd is now owned by output, steal it from the tmpfile */\n int tmp_fd = dup (glnx_steal_fd (&xauth_tmpf.fd));\n if (tmp_fd != -1)\n {\n g_autofree char *dest = g_strdup_printf (\"/run/user/%d/Xauthority\", getuid ());", " write_xauth (d, output);\n flatpak_bwrap_add_args_data_fd (bwrap, \"--ro-bind-data\", tmp_fd, dest);", " flatpak_bwrap_set_env (bwrap, \"XAUTHORITY\", dest, TRUE);\n }", " fclose (output);", " if (tmp_fd != -1)\n lseek (tmp_fd, 0, SEEK_SET);\n }\n }\n#endif\n }\n else\n {\n flatpak_bwrap_unset_env (bwrap, \"DISPLAY\");\n }\n}", "static gboolean\nflatpak_run_add_wayland_args (FlatpakBwrap *bwrap)\n{\n const char *wayland_display;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *wayland_socket = NULL;\n g_autofree char *sandbox_wayland_socket = NULL;\n gboolean res = FALSE;\n struct stat statbuf;", " wayland_display = g_getenv (\"WAYLAND_DISPLAY\");\n if (!wayland_display)\n wayland_display = \"wayland-0\";", " wayland_socket = g_build_filename (user_runtime_dir, wayland_display, NULL);\n sandbox_wayland_socket = g_strdup_printf (\"/run/user/%d/%s\", getuid (), wayland_display);", " if (stat (wayland_socket, &statbuf) == 0 &&\n (statbuf.st_mode & S_IFMT) == S_IFSOCK)\n {\n res = TRUE;\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", wayland_socket, sandbox_wayland_socket,\n NULL);\n }\n return res;\n}", "static void\nflatpak_run_add_ssh_args (FlatpakBwrap *bwrap)\n{\n const char * auth_socket;\n g_autofree char * sandbox_auth_socket = NULL;", " auth_socket = g_getenv (\"SSH_AUTH_SOCK\");", " if (!auth_socket)\n return; /* ssh agent not present */", " if (!g_file_test (auth_socket, G_FILE_TEST_EXISTS))\n {\n /* Let's clean it up, so that the application will not try to connect */\n flatpak_bwrap_unset_env (bwrap, \"SSH_AUTH_SOCK\");\n return;\n }", " sandbox_auth_socket = g_strdup_printf (\"/run/user/%d/ssh-auth\", getuid ());", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", auth_socket, sandbox_auth_socket,\n NULL);\n flatpak_bwrap_set_env (bwrap, \"SSH_AUTH_SOCK\", sandbox_auth_socket, TRUE);\n}", "static void\nflatpak_run_add_pcsc_args (FlatpakBwrap *bwrap)\n{\n const char * pcsc_socket;\n const char * sandbox_pcsc_socket = \"/run/pcscd/pcscd.comm\";", " pcsc_socket = g_getenv (\"PCSCLITE_CSOCK_NAME\");\n if (pcsc_socket)\n {\n if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_unset_env (bwrap, \"PCSCLITE_CSOCK_NAME\");\n return;\n }\n }\n else\n {\n pcsc_socket = \"/run/pcscd/pcscd.comm\";\n if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))\n return;\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pcsc_socket, sandbox_pcsc_socket,\n NULL);\n flatpak_bwrap_set_env (bwrap, \"PCSCLITE_CSOCK_NAME\", sandbox_pcsc_socket, TRUE);\n}", "static gboolean\nflatpak_run_cups_check_server_is_socket (const char *server)\n{\n if (g_str_has_prefix (server, \"/\") && strstr (server, \":\") == NULL)\n return TRUE;", " return FALSE;\n}", "/* Try to find a default server from a cups confguration file */\nstatic char *\nflatpak_run_get_cups_server_name_config (const char *path)\n{\n g_autoptr(GFile) file = g_file_new_for_path (path);\n g_autoptr(GError) my_error = NULL;\n g_autoptr(GFileInputStream) input_stream = NULL;\n g_autoptr(GDataInputStream) data_stream = NULL;\n size_t len;", " input_stream = g_file_read (file, NULL, &my_error);\n if (my_error)\n {\n g_debug (\"CUPS configuration file '%s': %s\", path, my_error->message);\n return NULL;\n }", " data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));", " while (TRUE)\n {\n g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);\n if (line == NULL)\n break;", " g_strchug (line);", " if ((*line == '\\0') || (*line == '#'))\n continue;", " g_auto(GStrv) tokens = g_strsplit (line, \" \", 2);", " if ((tokens[0] != NULL) && (tokens[1] != NULL))\n {\n if (strcmp (\"ServerName\", tokens[0]) == 0)\n {\n g_strchug (tokens[1]);", " if (flatpak_run_cups_check_server_is_socket (tokens[1]))\n return g_strdup (tokens[1]);\n }\n }\n }", " return NULL;\n}", "static char *\nflatpak_run_get_cups_server_name (void)\n{\n g_autofree char * cups_server = NULL;\n g_autofree char * cups_config_path = NULL;", " /* TODO\n * we don't currently support cups servers located on the network, if such\n * server is detected, we simply ignore it and in the worst case we fallback\n * to the default socket\n */\n cups_server = g_strdup (g_getenv (\"CUPS_SERVER\"));\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);\n g_clear_pointer (&cups_server, g_free);", " cups_config_path = g_build_filename (g_get_home_dir (), \".cups/client.conf\", NULL);\n cups_server = flatpak_run_get_cups_server_name_config (cups_config_path);\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);\n g_clear_pointer (&cups_server, g_free);", " cups_server = flatpak_run_get_cups_server_name_config (\"/etc/cups/client.conf\");\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);", " // Fallback to default socket\n return g_strdup (\"/var/run/cups/cups.sock\");\n}", "static void\nflatpak_run_add_cups_args (FlatpakBwrap *bwrap)\n{\n g_autofree char * sandbox_server_name = g_strdup (\"/var/run/cups/cups.sock\");\n g_autofree char * cups_server_name = flatpak_run_get_cups_server_name ();", " if (!g_file_test (cups_server_name, G_FILE_TEST_EXISTS))\n {\n g_debug (\"Could not find CUPS server\");\n return;\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", cups_server_name, sandbox_server_name,\n NULL);\n}", "/* Try to find a default server from a pulseaudio confguration file */\nstatic char *\nflatpak_run_get_pulseaudio_server_user_config (const char *path)\n{\n g_autoptr(GFile) file = g_file_new_for_path (path);\n g_autoptr(GError) my_error = NULL;\n g_autoptr(GFileInputStream) input_stream = NULL;\n g_autoptr(GDataInputStream) data_stream = NULL;\n size_t len;", " input_stream = g_file_read (file, NULL, &my_error);\n if (my_error)\n {\n g_debug (\"Pulseaudio user configuration file '%s': %s\", path, my_error->message);\n return NULL;\n }", " data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));", " while (TRUE)\n {\n g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);\n if (line == NULL)\n break;", " g_strchug (line);", " if ((*line == '\\0') || (*line == ';') || (*line == '#'))\n continue;", " if (g_str_has_prefix (line, \".include \"))\n {\n g_autofree char *rec_path = g_strdup (line + 9);\n g_strstrip (rec_path);\n char *found = flatpak_run_get_pulseaudio_server_user_config (rec_path);\n if (found)\n return found;\n }\n else if (g_str_has_prefix (line, \"[\"))\n {\n return NULL;\n }\n else\n {\n g_auto(GStrv) tokens = g_strsplit (line, \"=\", 2);", " if ((tokens[0] != NULL) && (tokens[1] != NULL))\n {\n g_strchomp (tokens[0]);\n if (strcmp (\"default-server\", tokens[0]) == 0)\n {\n g_strstrip (tokens[1]);\n g_debug (\"Found pulseaudio socket from configuration file '%s': %s\", path, tokens[1]);\n return g_strdup (tokens[1]);\n }\n }\n }\n }", " return NULL;\n}", "static char *\nflatpak_run_get_pulseaudio_server (void)\n{\n const char * pulse_clientconfig;\n char *pulse_server;\n g_autofree char *pulse_user_config = NULL;", " pulse_server = g_strdup (g_getenv (\"PULSE_SERVER\"));\n if (pulse_server)\n return pulse_server;", " pulse_clientconfig = g_getenv (\"PULSE_CLIENTCONFIG\");\n if (pulse_clientconfig)\n return flatpak_run_get_pulseaudio_server_user_config (pulse_clientconfig);", " pulse_user_config = g_build_filename (g_get_user_config_dir (), \"pulse/client.conf\", NULL);\n pulse_server = flatpak_run_get_pulseaudio_server_user_config (pulse_user_config);\n if (pulse_server)\n return pulse_server;", " pulse_server = flatpak_run_get_pulseaudio_server_user_config (\"/etc/pulse/client.conf\");\n if (pulse_server)\n return pulse_server;", " return NULL;\n}", "static char *\nflatpak_run_parse_pulse_server (const char *value)\n{\n g_auto(GStrv) servers = g_strsplit (value, \" \", 0);\n gsize i;", " for (i = 0; servers[i] != NULL; i++)\n {\n const char *server = servers[i];\n if (g_str_has_prefix (server, \"{\"))\n {\n const char * closing = strstr (server, \"}\");\n if (closing == NULL)\n continue;\n server = closing + 1;\n }\n if (g_str_has_prefix (server, \"unix:\"))\n return g_strdup (server + 5);\n }", " return NULL;\n}", "/*\n * Get the machine ID as used by PulseAudio. This is the systemd/D-Bus\n * machine ID, or failing that, the hostname.\n */\nstatic char *\nflatpak_run_get_pulse_machine_id (void)\n{\n static const char * const machine_ids[] =\n {\n \"/etc/machine-id\",\n \"/var/lib/dbus/machine-id\",\n };\n gsize i;", " for (i = 0; i < G_N_ELEMENTS (machine_ids); i++)\n {\n g_autofree char *ret = NULL;", " if (g_file_get_contents (machine_ids[i], &ret, NULL, NULL))\n {\n gsize j;", " g_strstrip (ret);", " for (j = 0; ret[j] != '\\0'; j++)\n {\n if (!g_ascii_isxdigit (ret[j]))\n break;\n }", " if (ret[0] != '\\0' && ret[j] == '\\0')\n return g_steal_pointer (&ret);\n }\n }", " return g_strdup (g_get_host_name ());\n}", "/*\n * Get the directory used by PulseAudio for its configuration.\n */\nstatic char *\nflatpak_run_get_pulse_home (void)\n{\n /* Legacy path ~/.pulse is tried first, for compatibility */\n {\n const char *parent = g_get_home_dir ();\n g_autofree char *ret = g_build_filename (parent, \".pulse\", NULL);", " if (g_file_test (ret, G_FILE_TEST_IS_DIR))\n return g_steal_pointer (&ret);\n }", " /* The more modern path, usually ~/.config/pulse */\n {\n const char *parent = g_get_user_config_dir ();\n /* Usually ~/.config/pulse */\n g_autofree char *ret = g_build_filename (parent, \"pulse\", NULL);", " if (g_file_test (ret, G_FILE_TEST_IS_DIR))\n return g_steal_pointer (&ret);\n }", " return NULL;\n}", "/*\n * Get the runtime directory used by PulseAudio for its socket.\n */\nstatic char *\nflatpak_run_get_pulse_runtime_dir (void)\n{\n const char *val = NULL;", " val = g_getenv (\"PULSE_RUNTIME_PATH\");", " if (val != NULL)\n return realpath (val, NULL);", " {\n const char *user_runtime_dir = g_get_user_runtime_dir ();", " if (user_runtime_dir != NULL)\n {\n g_autofree char *dir = g_build_filename (user_runtime_dir, \"pulse\", NULL);", " if (g_file_test (dir, G_FILE_TEST_IS_DIR))\n return realpath (dir, NULL);\n }\n }", " {\n g_autofree char *pulse_home = flatpak_run_get_pulse_home ();\n g_autofree char *machine_id = flatpak_run_get_pulse_machine_id ();", " if (pulse_home != NULL && machine_id != NULL)\n {\n /* This is usually a symlink, but we take its realpath() anyway */\n g_autofree char *dir = g_strdup_printf (\"%s/%s-runtime\", pulse_home, machine_id);", " if (g_file_test (dir, G_FILE_TEST_IS_DIR))\n return realpath (dir, NULL);\n }\n }", " return NULL;\n}", "static void\nflatpak_run_add_pulseaudio_args (FlatpakBwrap *bwrap)\n{\n g_autofree char *pulseaudio_server = flatpak_run_get_pulseaudio_server ();\n g_autofree char *pulseaudio_socket = NULL;\n g_autofree char *pulse_runtime_dir = flatpak_run_get_pulse_runtime_dir ();", " if (pulseaudio_server)\n pulseaudio_socket = flatpak_run_parse_pulse_server (pulseaudio_server);", " if (!pulseaudio_socket)\n {\n pulseaudio_socket = g_build_filename (pulse_runtime_dir, \"native\", NULL);", " if (!g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n g_clear_pointer (&pulseaudio_socket, g_free);\n }", " if (!pulseaudio_socket)\n {\n pulseaudio_socket = realpath (\"/var/run/pulse/native\", NULL);", " if (pulseaudio_socket && !g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n g_clear_pointer (&pulseaudio_socket, g_free);\n }", " flatpak_bwrap_unset_env (bwrap, \"PULSE_SERVER\");", " if (pulseaudio_socket && g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n {\n gboolean share_shm = FALSE; /* TODO: When do we add this? */\n g_autofree char *client_config = g_strdup_printf (\"enable-shm=%s\\n\", share_shm ? \"yes\" : \"no\");\n g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/pulse/native\", getuid ());\n g_autofree char *pulse_server = g_strdup_printf (\"unix:/run/user/%d/pulse/native\", getuid ());\n g_autofree char *config_path = g_strdup_printf (\"/run/user/%d/pulse/config\", getuid ());", " /* FIXME - error handling */\n if (!flatpak_bwrap_add_args_data (bwrap, \"pulseaudio\", client_config, -1, config_path, NULL))\n return;", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pulseaudio_socket, sandbox_socket_path,\n NULL);", " flatpak_bwrap_set_env (bwrap, \"PULSE_SERVER\", pulse_server, TRUE);\n flatpak_bwrap_set_env (bwrap, \"PULSE_CLIENTCONFIG\", config_path, TRUE);\n }\n else\n g_debug (\"Could not find pulseaudio socket\");", " /* Also allow ALSA access. This was added in 1.8, and is not ideally named. However,\n * since the practical permission of ALSA and PulseAudio are essentially the same, and\n * since we don't want to add more permissions for something we plan to replace with\n * portals/pipewire going forward we reinterpret pulseaudio to also mean ALSA.\n */\n if (g_file_test (\"/dev/snd\", G_FILE_TEST_IS_DIR))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", \"/dev/snd\", \"/dev/snd\", NULL);\n}", "static void\nflatpak_run_add_resolved_args (FlatpakBwrap *bwrap)\n{\n const char *resolved_socket = \"/run/systemd/resolve/io.systemd.Resolve\";", " if (g_file_test (resolved_socket, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--bind\", resolved_socket, resolved_socket, NULL);\n}", "static void\nflatpak_run_add_journal_args (FlatpakBwrap *bwrap)\n{\n g_autofree char *journal_socket_socket = g_strdup (\"/run/systemd/journal/socket\");\n g_autofree char *journal_stdout_socket = g_strdup (\"/run/systemd/journal/stdout\");", " if (g_file_test (journal_socket_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", journal_socket_socket, journal_socket_socket,\n NULL);\n }\n if (g_file_test (journal_stdout_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", journal_stdout_socket, journal_stdout_socket,\n NULL);\n }\n}", "static char *\ncreate_proxy_socket (char *template)\n{\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, \".dbus-proxy\", NULL);\n g_autofree char *proxy_socket = g_build_filename (proxy_socket_dir, template, NULL);\n int fd;", " if (!glnx_shutil_mkdir_p_at (AT_FDCWD, proxy_socket_dir, 0755, NULL, NULL))\n return NULL;", " fd = g_mkstemp (proxy_socket);\n if (fd == -1)\n return NULL;", " close (fd);", " return g_steal_pointer (&proxy_socket);\n}", "static gboolean\nflatpak_run_add_system_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags)\n{\n gboolean unrestricted, no_proxy;\n const char *dbus_address = g_getenv (\"DBUS_SYSTEM_BUS_ADDRESS\");\n g_autofree char *real_dbus_address = NULL;\n g_autofree char *dbus_system_socket = NULL;", " unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) != 0;\n if (unrestricted)\n g_debug (\"Allowing system-dbus access\");", " no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY) != 0;", " if (dbus_address != NULL)\n dbus_system_socket = extract_unix_path_from_dbus_address (dbus_address);\n else if (g_file_test (\"/var/run/dbus/system_bus_socket\", G_FILE_TEST_EXISTS))\n dbus_system_socket = g_strdup (\"/var/run/dbus/system_bus_socket\");", " if (dbus_system_socket != NULL && unrestricted)\n {\n flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", dbus_system_socket, \"/run/dbus/system_bus_socket\",\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SYSTEM_BUS_ADDRESS\", \"unix:path=/run/dbus/system_bus_socket\", TRUE);", " return TRUE;\n }\n else if (!no_proxy && flatpak_context_get_needs_system_bus_proxy (context))\n {\n g_autofree char *proxy_socket = create_proxy_socket (\"system-bus-proxy-XXXXXX\");", " if (proxy_socket == NULL)\n return FALSE;", " if (dbus_address)\n real_dbus_address = g_strdup (dbus_address);\n else\n real_dbus_address = g_strdup_printf (\"unix:path=%s\", dbus_system_socket);", " flatpak_bwrap_add_args (proxy_arg_bwrap, real_dbus_address, proxy_socket, NULL);", " if (!unrestricted)\n flatpak_context_add_bus_filters (context, NULL, FALSE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);", " if ((flags & FLATPAK_RUN_FLAG_LOG_SYSTEM_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, \"/run/dbus/system_bus_socket\",\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SYSTEM_BUS_ADDRESS\", \"unix:path=/run/dbus/system_bus_socket\", TRUE);", " return TRUE;\n }\n return FALSE;\n}", "static gboolean\nflatpak_run_add_session_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags,\n const char *app_id)\n{\n gboolean unrestricted, no_proxy;\n const char *dbus_address = g_getenv (\"DBUS_SESSION_BUS_ADDRESS\");\n g_autofree char *dbus_session_socket = NULL;\n g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/bus\", getuid ());\n g_autofree char *sandbox_dbus_address = g_strdup_printf (\"unix:path=/run/user/%d/bus\", getuid ());", " unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) != 0;", " if (dbus_address != NULL)\n {\n dbus_session_socket = extract_unix_path_from_dbus_address (dbus_address);\n }\n else\n {\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n struct stat statbuf;", " dbus_session_socket = g_build_filename (user_runtime_dir, \"bus\", NULL);", " if (stat (dbus_session_socket, &statbuf) < 0\n || (statbuf.st_mode & S_IFMT) != S_IFSOCK\n || statbuf.st_uid != getuid ())\n return FALSE;\n }", " if (unrestricted)\n g_debug (\"Allowing session-dbus access\");", " no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY) != 0;", " if (dbus_session_socket != NULL && unrestricted)\n {\n flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", dbus_session_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SESSION_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n }\n else if (!no_proxy && dbus_address != NULL)\n {\n g_autofree char *proxy_socket = create_proxy_socket (\"session-bus-proxy-XXXXXX\");", " if (proxy_socket == NULL)\n return FALSE;", " flatpak_bwrap_add_args (proxy_arg_bwrap, dbus_address, proxy_socket, NULL);", " if (!unrestricted)\n {\n flatpak_context_add_bus_filters (context, app_id, TRUE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);", " /* Allow calling any interface+method on all portals, but only receive broadcasts under /org/desktop/portal */\n flatpak_bwrap_add_arg (proxy_arg_bwrap,\n \"--call=org.freedesktop.portal.*=*\");\n flatpak_bwrap_add_arg (proxy_arg_bwrap,\n \"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*\");\n }", " if ((flags & FLATPAK_RUN_FLAG_LOG_SESSION_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SESSION_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n }", " return FALSE;\n}", "static gboolean\nflatpak_run_add_a11y_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags)\n{\n g_autoptr(GDBusConnection) session_bus = NULL;\n g_autofree char *a11y_address = NULL;\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDBusMessage) reply = NULL;\n g_autoptr(GDBusMessage) msg = NULL;\n g_autofree char *proxy_socket = NULL;", " if ((flags & FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY) != 0)\n return FALSE;", " session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);\n if (session_bus == NULL)\n return FALSE;", " msg = g_dbus_message_new_method_call (\"org.a11y.Bus\", \"/org/a11y/bus\", \"org.a11y.Bus\", \"GetAddress\");\n g_dbus_message_set_body (msg, g_variant_new (\"()\"));\n reply =\n g_dbus_connection_send_message_with_reply_sync (session_bus, msg,\n G_DBUS_SEND_MESSAGE_FLAGS_NONE,\n 30000,\n NULL,\n NULL,\n NULL);\n if (reply)\n {\n if (g_dbus_message_to_gerror (reply, &local_error))\n {\n if (!g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))\n g_message (\"Can't find a11y bus: %s\", local_error->message);\n }\n else\n {\n g_variant_get (g_dbus_message_get_body (reply),\n \"(s)\", &a11y_address);\n }\n }", " if (!a11y_address)\n return FALSE;", " proxy_socket = create_proxy_socket (\"a11y-bus-proxy-XXXXXX\");\n if (proxy_socket == NULL)\n return FALSE;", " g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/at-spi-bus\", getuid ());\n g_autofree char *sandbox_dbus_address = g_strdup_printf (\"unix:path=/run/user/%d/at-spi-bus\", getuid ());", " flatpak_bwrap_add_args (proxy_arg_bwrap,\n a11y_address,\n proxy_socket, \"--filter\", \"--sloppy-names\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Embed@/org/a11y/atspi/accessible/root\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Unembed@/org/a11y/atspi/accessible/root\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Registry.GetRegisteredEvents@/org/a11y/atspi/registry\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetKeystrokeListeners@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetDeviceEventListeners@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersSync@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersAsync@/org/a11y/atspi/registry/deviceeventcontroller\",\n NULL);", " if ((flags & FLATPAK_RUN_FLAG_LOG_A11Y_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"AT_SPI_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n}", "/* This wraps the argv in a bwrap call, primary to allow the\n command to be run with a proper /.flatpak-info with data\n taken from app_info_path */\nstatic gboolean\nadd_bwrap_wrapper (FlatpakBwrap *bwrap,\n const char *app_info_path,\n GError **error)\n{\n glnx_autofd int app_info_fd = -1;\n g_auto(GLnxDirFdIterator) dir_iter = { 0 };\n struct dirent *dent;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, \".dbus-proxy/\", NULL);", " app_info_fd = open (app_info_path, O_RDONLY | O_CLOEXEC);\n if (app_info_fd == -1)\n return glnx_throw_errno_prefix (error, _(\"Failed to open app info file\"));", " if (!glnx_dirfd_iterator_init_at (AT_FDCWD, \"/\", FALSE, &dir_iter, error))\n return FALSE;", " flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());", " while (TRUE)\n {\n glnx_autofd int o_path_fd = -1;\n struct statfs stfs;", " if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dir_iter, &dent, NULL, error))\n return FALSE;", " if (dent == NULL)\n break;", " if (strcmp (dent->d_name, \".flatpak-info\") == 0)\n continue;", " /* O_PATH + fstatfs is the magic that we need to statfs without automounting the target */\n o_path_fd = openat (dir_iter.fd, dent->d_name, O_PATH | O_NOFOLLOW | O_CLOEXEC);\n if (o_path_fd == -1 || fstatfs (o_path_fd, &stfs) != 0 || stfs.f_type == AUTOFS_SUPER_MAGIC)\n continue; /* AUTOFS mounts are risky and can cause us to block (see issue #1633), so ignore it. Its unlikely the proxy needs such a directory. */", " if (dent->d_type == DT_DIR)\n {\n if (strcmp (dent->d_name, \"tmp\") == 0 ||\n strcmp (dent->d_name, \"var\") == 0 ||\n strcmp (dent->d_name, \"run\") == 0)\n flatpak_bwrap_add_arg (bwrap, \"--bind\");\n else\n flatpak_bwrap_add_arg (bwrap, \"--ro-bind\");", " flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n }\n else if (dent->d_type == DT_LNK)\n {\n g_autofree gchar *target = NULL;", " target = glnx_readlinkat_malloc (dir_iter.fd, dent->d_name,\n NULL, error);\n if (target == NULL)\n return FALSE;\n flatpak_bwrap_add_args (bwrap, \"--symlink\", target, NULL);\n flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n }\n }", " flatpak_bwrap_add_args (bwrap, \"--bind\", proxy_socket_dir, proxy_socket_dir, NULL);", " /* This is a file rather than a bind mount, because it will then\n not be unmounted from the namespace when the namespace dies. */\n flatpak_bwrap_add_args_data_fd (bwrap, \"--file\", glnx_steal_fd (&app_info_fd), \"/.flatpak-info\");", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return FALSE;", " return TRUE;\n}", "static gboolean\nstart_dbus_proxy (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n const char *app_info_path,\n GError **error)\n{\n char x = 'x';\n const char *proxy;\n g_autofree char *commandline = NULL;\n g_autoptr(FlatpakBwrap) proxy_bwrap = NULL;\n int sync_fds[2] = {-1, -1};\n int proxy_start_index;\n g_auto(GStrv) minimal_envp = NULL;", " minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);\n proxy_bwrap = flatpak_bwrap_new (NULL);", " if (!add_bwrap_wrapper (proxy_bwrap, app_info_path, error))\n return FALSE;", " proxy = g_getenv (\"FLATPAK_DBUSPROXY\");\n if (proxy == NULL)\n proxy = DBUSPROXY;", " flatpak_bwrap_add_arg (proxy_bwrap, proxy);", " proxy_start_index = proxy_bwrap->argv->len;", " if (pipe2 (sync_fds, O_CLOEXEC) < 0)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Unable to create sync pipe\"));\n return FALSE;\n }", " /* read end goes to app */\n flatpak_bwrap_add_args_data_fd (app_bwrap, \"--sync-fd\", sync_fds[0], NULL);", " /* write end goes to proxy */\n flatpak_bwrap_add_fd (proxy_bwrap, sync_fds[1]);\n flatpak_bwrap_add_arg_printf (proxy_bwrap, \"--fd=%d\", sync_fds[1]);", " /* Note: This steals the fds from proxy_arg_bwrap */\n flatpak_bwrap_append_bwrap (proxy_bwrap, proxy_arg_bwrap);", " if (!flatpak_bwrap_bundle_args (proxy_bwrap, proxy_start_index, -1, TRUE, error))\n return FALSE;", " flatpak_bwrap_finish (proxy_bwrap);", " commandline = flatpak_quote_argv ((const char **) proxy_bwrap->argv->pdata, -1);\n g_debug (\"Running '%s'\", commandline);", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async (NULL,\n (char **) proxy_bwrap->argv->pdata,\n NULL,\n G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n flatpak_bwrap_child_setup_cb, proxy_bwrap->fds,\n NULL, error))\n return FALSE;", " /* The write end can be closed now, otherwise the read below will hang of xdg-dbus-proxy\n fails to start. */\n g_clear_pointer (&proxy_bwrap, flatpak_bwrap_free);", " /* Sync with proxy, i.e. wait until its listening on the sockets */\n if (read (sync_fds[0], &x, 1) != 1)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Failed to sync with dbus proxy\"));\n return FALSE;\n }", " return TRUE;\n}", "static int\nflatpak_extension_compare_by_path (gconstpointer _a,\n gconstpointer _b)\n{\n const FlatpakExtension *a = _a;\n const FlatpakExtension *b = _b;", " return g_strcmp0 (a->directory, b->directory);\n}", "gboolean\nflatpak_run_add_extension_args (FlatpakBwrap *bwrap,\n GKeyFile *metakey,\n FlatpakDecomposed *ref,\n gboolean use_ld_so_cache,\n char **extensions_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GString) used_extensions = g_string_new (\"\");\n GList *extensions, *path_sorted_extensions, *l;\n g_autoptr(GString) ld_library_path = g_string_new (\"\");\n int count = 0;\n g_autoptr(GHashTable) mounted_tmpfs =\n g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n g_autoptr(GHashTable) created_symlink =\n g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n g_autofree char *arch = flatpak_decomposed_dup_arch (ref);\n const char *branch = flatpak_decomposed_get_branch (ref);\n gboolean is_app = flatpak_decomposed_is_app (ref);", " extensions = flatpak_list_extensions (metakey, arch, branch);", " /* First we apply all the bindings, they are sorted alphabetically in order for parent directory\n to be mounted before child directories */\n path_sorted_extensions = g_list_copy (extensions);\n path_sorted_extensions = g_list_sort (path_sorted_extensions, flatpak_extension_compare_by_path);", " for (l = path_sorted_extensions; l != NULL; l = l->next)\n {\n FlatpakExtension *ext = l->data;\n g_autofree char *directory = g_build_filename (is_app ? \"/app\" : \"/usr\", ext->directory, NULL);\n g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);\n g_autofree char *ref_file = g_build_filename (full_directory, \".ref\", NULL);\n g_autofree char *real_ref = g_build_filename (ext->files_path, ext->directory, \".ref\", NULL);", " if (ext->needs_tmpfs)\n {\n g_autofree char *parent = g_path_get_dirname (directory);", " if (g_hash_table_lookup (mounted_tmpfs, parent) == NULL)\n {\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", parent,\n NULL);\n g_hash_table_insert (mounted_tmpfs, g_steal_pointer (&parent), \"mounted\");\n }\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", ext->files_path, full_directory,\n NULL);", " if (g_file_test (real_ref, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--lock-file\", ref_file,\n NULL);\n }", " g_list_free (path_sorted_extensions);", " /* Then apply library directories and file merging, in extension prio order */", " for (l = extensions; l != NULL; l = l->next)\n {\n FlatpakExtension *ext = l->data;\n g_autofree char *directory = g_build_filename (is_app ? \"/app\" : \"/usr\", ext->directory, NULL);\n g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);\n int i;", " if (used_extensions->len > 0)\n g_string_append (used_extensions, \";\");\n g_string_append (used_extensions, ext->installed_id);\n g_string_append (used_extensions, \"=\");\n if (ext->commit != NULL)\n g_string_append (used_extensions, ext->commit);\n else\n g_string_append (used_extensions, \"local\");", " if (ext->add_ld_path)\n {\n g_autofree char *ld_path = g_build_filename (full_directory, ext->add_ld_path, NULL);", " if (use_ld_so_cache)\n {\n g_autofree char *contents = g_strconcat (ld_path, \"\\n\", NULL);\n /* We prepend app or runtime and a counter in order to get the include order correct for the conf files */\n g_autofree char *ld_so_conf_file = g_strdup_printf (\"%s-%03d-%s.conf\", flatpak_decomposed_get_kind_str (ref), ++count, ext->installed_id);\n g_autofree char *ld_so_conf_file_path = g_build_filename (\"/run/flatpak/ld.so.conf.d\", ld_so_conf_file, NULL);", " if (!flatpak_bwrap_add_args_data (bwrap, \"ld-so-conf\",\n contents, -1, ld_so_conf_file_path, error))\n return FALSE;\n }\n else\n {\n if (ld_library_path->len != 0)\n g_string_append (ld_library_path, \":\");\n g_string_append (ld_library_path, ld_path);\n }\n }", " for (i = 0; ext->merge_dirs != NULL && ext->merge_dirs[i] != NULL; i++)\n {\n g_autofree char *parent = g_path_get_dirname (directory);\n g_autofree char *merge_dir = g_build_filename (parent, ext->merge_dirs[i], NULL);\n g_autofree char *source_dir = g_build_filename (ext->files_path, ext->merge_dirs[i], NULL);\n g_auto(GLnxDirFdIterator) source_iter = { 0 };\n struct dirent *dent;", " if (glnx_dirfd_iterator_init_at (AT_FDCWD, source_dir, TRUE, &source_iter, NULL))\n {\n while (glnx_dirfd_iterator_next_dent (&source_iter, &dent, NULL, NULL) && dent != NULL)\n {\n g_autofree char *symlink_path = g_build_filename (merge_dir, dent->d_name, NULL);\n /* Only create the first, because extensions are listed in prio order */\n if (g_hash_table_lookup (created_symlink, symlink_path) == NULL)\n {\n g_autofree char *symlink = g_build_filename (directory, ext->merge_dirs[i], dent->d_name, NULL);\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", symlink, symlink_path,\n NULL);\n g_hash_table_insert (created_symlink, g_steal_pointer (&symlink_path), \"created\");\n }\n }\n }\n }\n }", " g_list_free_full (extensions, (GDestroyNotify) flatpak_extension_free);", " if (ld_library_path->len != 0)\n {\n const gchar *old_ld_path = g_environ_getenv (bwrap->envp, \"LD_LIBRARY_PATH\");", " if (old_ld_path != NULL && *old_ld_path != 0)\n {\n if (is_app)\n {\n g_string_append (ld_library_path, \":\");\n g_string_append (ld_library_path, old_ld_path);\n }\n else\n {\n g_string_prepend (ld_library_path, \":\");\n g_string_prepend (ld_library_path, old_ld_path);\n }\n }", " flatpak_bwrap_set_env (bwrap, \"LD_LIBRARY_PATH\", ld_library_path->str, TRUE);\n }", " if (extensions_out)\n *extensions_out = g_string_free (g_steal_pointer (&used_extensions), FALSE);", " return TRUE;\n}", "gboolean\nflatpak_run_add_environment_args (FlatpakBwrap *bwrap,\n const char *app_info_path,\n FlatpakRunFlags flags,\n const char *app_id,\n FlatpakContext *context,\n GFile *app_id_dir,\n GPtrArray *previous_app_id_dirs,\n FlatpakExports **exports_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GError) my_error = NULL;\n g_autoptr(FlatpakExports) exports = NULL;\n g_autoptr(FlatpakBwrap) proxy_arg_bwrap = flatpak_bwrap_new (flatpak_bwrap_empty_env);\n gboolean has_wayland = FALSE;\n gboolean allow_x11 = FALSE;", " if ((context->shares & FLATPAK_CONTEXT_SHARED_IPC) == 0)\n {\n g_debug (\"Disallowing ipc access\");\n flatpak_bwrap_add_args (bwrap, \"--unshare-ipc\", NULL);\n }", " if ((context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) == 0)\n {\n g_debug (\"Disallowing network access\");\n flatpak_bwrap_add_args (bwrap, \"--unshare-net\", NULL);\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_ALL)\n {\n flatpak_bwrap_add_args (bwrap,\n \"--dev-bind\", \"/dev\", \"/dev\",\n NULL);\n /* Don't expose the host /dev/shm, just the device nodes, unless explicitly allowed */\n if (g_file_test (\"/dev/shm\", G_FILE_TEST_IS_DIR))\n {\n if ((context->devices & FLATPAK_CONTEXT_DEVICE_SHM) == 0)\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/dev/shm\",\n NULL);\n }\n else if (g_file_test (\"/dev/shm\", G_FILE_TEST_IS_SYMLINK))\n {\n g_autofree char *link = flatpak_readlink (\"/dev/shm\", NULL);", " /* On debian (with sysv init) the host /dev/shm is a symlink to /run/shm, so we can't\n mount on top of it. */\n if (g_strcmp0 (link, \"/run/shm\") == 0)\n {\n if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM &&\n g_file_test (\"/run/shm\", G_FILE_TEST_IS_DIR))\n flatpak_bwrap_add_args (bwrap,\n \"--bind\", \"/run/shm\", \"/run/shm\",\n NULL);\n else\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/run/shm\",\n NULL);\n }\n else\n g_warning (\"Unexpected /dev/shm symlink %s\", link);\n }\n }\n else\n {\n flatpak_bwrap_add_args (bwrap,\n \"--dev\", \"/dev\",\n NULL);\n if (context->devices & FLATPAK_CONTEXT_DEVICE_DRI)\n {\n g_debug (\"Allowing dri access\");\n int i;\n char *dri_devices[] = {\n \"/dev/dri\",\n /* mali */\n \"/dev/mali\",\n \"/dev/mali0\",\n \"/dev/umplock\",\n /* nvidia */\n \"/dev/nvidiactl\",\n \"/dev/nvidia-modeset\",\n /* nvidia OpenCL/CUDA */\n \"/dev/nvidia-uvm\",\n \"/dev/nvidia-uvm-tools\",\n };", " for (i = 0; i < G_N_ELEMENTS (dri_devices); i++)\n {\n if (g_file_test (dri_devices[i], G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", dri_devices[i], dri_devices[i], NULL);\n }", " /* Each Nvidia card gets its own device.\n This is a fairly arbitrary limit but ASUS sells mining boards supporting 20 in theory. */\n char nvidia_dev[14]; /* /dev/nvidia plus up to 2 digits */\n for (i = 0; i < 20; i++)\n {\n g_snprintf (nvidia_dev, sizeof (nvidia_dev), \"/dev/nvidia%d\", i);\n if (g_file_test (nvidia_dev, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", nvidia_dev, nvidia_dev, NULL);\n }\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_KVM)\n {\n g_debug (\"Allowing kvm access\");\n if (g_file_test (\"/dev/kvm\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", \"/dev/kvm\", \"/dev/kvm\", NULL);\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM)\n {\n /* This is a symlink to /run/shm on debian, so bind to real target */\n g_autofree char *real_dev_shm = realpath (\"/dev/shm\", NULL);", " g_debug (\"Allowing /dev/shm access (as %s)\", real_dev_shm);\n if (real_dev_shm != NULL)\n flatpak_bwrap_add_args (bwrap, \"--bind\", real_dev_shm, \"/dev/shm\", NULL);\n }\n }", " flatpak_context_append_bwrap_filesystem (context, bwrap, app_id, app_id_dir, previous_app_id_dirs, &exports);", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_WAYLAND)\n {\n g_debug (\"Allowing wayland access\");\n has_wayland = flatpak_run_add_wayland_args (bwrap);\n }", " if ((context->sockets & FLATPAK_CONTEXT_SOCKET_FALLBACK_X11) != 0)\n allow_x11 = !has_wayland;\n else\n allow_x11 = (context->sockets & FLATPAK_CONTEXT_SOCKET_X11) != 0;", " flatpak_run_add_x11_args (bwrap, allow_x11);", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_SSH_AUTH)\n {\n flatpak_run_add_ssh_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_PULSEAUDIO)\n {\n g_debug (\"Allowing pulseaudio access\");\n flatpak_run_add_pulseaudio_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_PCSC)\n {\n flatpak_run_add_pcsc_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_CUPS)\n {\n flatpak_run_add_cups_args (bwrap);\n }", " flatpak_run_add_session_dbus_args (bwrap, proxy_arg_bwrap, context, flags, app_id);\n flatpak_run_add_system_dbus_args (bwrap, proxy_arg_bwrap, context, flags);\n flatpak_run_add_a11y_dbus_args (bwrap, proxy_arg_bwrap, context, flags);", "\n if (g_environ_getenv (bwrap->envp, \"LD_LIBRARY_PATH\") != NULL)\n {\n /* LD_LIBRARY_PATH is overridden for setuid helper, so pass it as cmdline arg */\n flatpak_bwrap_add_args (bwrap,\n \"--setenv\", \"LD_LIBRARY_PATH\", g_environ_getenv (bwrap->envp, \"LD_LIBRARY_PATH\"),\n NULL);\n flatpak_bwrap_unset_env (bwrap, \"LD_LIBRARY_PATH\");\n }", " if (g_environ_getenv (bwrap->envp, \"TMPDIR\") != NULL)\n {\n /* TMPDIR is overridden for setuid helper, so pass it as cmdline arg */\n flatpak_bwrap_add_args (bwrap,\n \"--setenv\", \"TMPDIR\", g_environ_getenv (bwrap->envp, \"TMPDIR\"),\n NULL);\n flatpak_bwrap_unset_env (bwrap, \"TMPDIR\");\n }", "\n /* Must run this before spawning the dbus proxy, to ensure it\n ends up in the app cgroup */\n if (!flatpak_run_in_transient_unit (app_id, &my_error))\n {\n /* We still run along even if we don't get a cgroup, as nothing\n really depends on it. Its just nice to have */\n g_debug (\"Failed to run in transient scope: %s\", my_error->message);\n g_clear_error (&my_error);\n }", " if (!flatpak_bwrap_is_empty (proxy_arg_bwrap) &&\n !start_dbus_proxy (bwrap, proxy_arg_bwrap, app_info_path, error))\n return FALSE;", " if (exports_out)\n *exports_out = g_steal_pointer (&exports);", " return TRUE;\n}", "typedef struct\n{\n const char *env;\n const char *val;\n} ExportData;", "static const ExportData default_exports[] = {\n {\"PATH\", \"/app/bin:/usr/bin\"},\n /* We always want to unset LD_LIBRARY_PATH to avoid inheriting weird\n * dependencies from the host. But if not using ld.so.cache this is\n * later set. */\n {\"LD_LIBRARY_PATH\", NULL},\n {\"XDG_CONFIG_DIRS\", \"/app/etc/xdg:/etc/xdg\"},\n {\"XDG_DATA_DIRS\", \"/app/share:/usr/share\"},\n {\"SHELL\", \"/bin/sh\"},\n {\"TMPDIR\", NULL}, /* Unset TMPDIR as it may not exist in the sandbox */", " /* Some env vars are common enough and will affect the sandbox badly\n if set on the host. We clear these always. */\n {\"PYTHONPATH\", NULL},\n {\"PERLLIB\", NULL},\n {\"PERL5LIB\", NULL},\n {\"XCURSOR_PATH\", NULL},\n};", "static const ExportData no_ld_so_cache_exports[] = {\n {\"LD_LIBRARY_PATH\", \"/app/lib\"},\n};", "static const ExportData devel_exports[] = {\n {\"ACLOCAL_PATH\", \"/app/share/aclocal\"},\n {\"C_INCLUDE_PATH\", \"/app/include\"},\n {\"CPLUS_INCLUDE_PATH\", \"/app/include\"},\n {\"LDFLAGS\", \"-L/app/lib \"},\n {\"PKG_CONFIG_PATH\", \"/app/lib/pkgconfig:/app/share/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig\"},\n {\"LC_ALL\", \"en_US.utf8\"},\n};", "static void\nadd_exports (GPtrArray *env_array,\n const ExportData *exports,\n gsize n_exports)\n{\n int i;", " for (i = 0; i < n_exports; i++)\n {\n if (exports[i].val)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", exports[i].env, exports[i].val));\n }\n}", "char **\nflatpak_run_get_minimal_env (gboolean devel, gboolean use_ld_so_cache)\n{\n GPtrArray *env_array;\n static const char * const copy[] = {\n \"PWD\",\n \"GDMSESSION\",\n \"XDG_CURRENT_DESKTOP\",\n \"XDG_SESSION_DESKTOP\",\n \"DESKTOP_SESSION\",\n \"EMAIL_ADDRESS\",\n \"HOME\",\n \"HOSTNAME\",\n \"LOGNAME\",\n \"REAL_NAME\",\n \"TERM\",\n \"USER\",\n \"USERNAME\",\n };\n static const char * const copy_nodevel[] = {\n \"LANG\",\n \"LANGUAGE\",\n \"LC_ALL\",\n \"LC_ADDRESS\",\n \"LC_COLLATE\",\n \"LC_CTYPE\",\n \"LC_IDENTIFICATION\",\n \"LC_MEASUREMENT\",\n \"LC_MESSAGES\",\n \"LC_MONETARY\",\n \"LC_NAME\",\n \"LC_NUMERIC\",\n \"LC_PAPER\",\n \"LC_TELEPHONE\",\n \"LC_TIME\",\n };\n int i;", " env_array = g_ptr_array_new_with_free_func (g_free);", " add_exports (env_array, default_exports, G_N_ELEMENTS (default_exports));", " if (!use_ld_so_cache)\n add_exports (env_array, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));", " if (devel)\n add_exports (env_array, devel_exports, G_N_ELEMENTS (devel_exports));", " for (i = 0; i < G_N_ELEMENTS (copy); i++)\n {\n const char *current = g_getenv (copy[i]);\n if (current)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", copy[i], current));\n }", " if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (copy_nodevel); i++)\n {\n const char *current = g_getenv (copy_nodevel[i]);\n if (current)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", copy_nodevel[i], current));\n }\n }", " g_ptr_array_add (env_array, NULL);\n return (char **) g_ptr_array_free (env_array, FALSE);\n}", "static char **\napply_exports (char **envp,\n const ExportData *exports,\n gsize n_exports)\n{\n int i;", " for (i = 0; i < n_exports; i++)\n {\n const char *value = exports[i].val;", " if (value)\n envp = g_environ_setenv (envp, exports[i].env, value, TRUE);\n else\n envp = g_environ_unsetenv (envp, exports[i].env);\n }", " return envp;\n}", "void\nflatpak_run_apply_env_default (FlatpakBwrap *bwrap, gboolean use_ld_so_cache)\n{\n bwrap->envp = apply_exports (bwrap->envp, default_exports, G_N_ELEMENTS (default_exports));", " if (!use_ld_so_cache)\n bwrap->envp = apply_exports (bwrap->envp, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));\n}", "static void\nflatpak_run_apply_env_prompt (FlatpakBwrap *bwrap, const char *app_id)\n{\n /* A custom shell prompt. FLATPAK_ID is always set.\n * PS1 can be overwritten by runtime metadata or by --env overrides\n */\n flatpak_bwrap_set_env (bwrap, \"FLATPAK_ID\", app_id, TRUE);\n flatpak_bwrap_set_env (bwrap, \"PS1\", \"[📦 $FLATPAK_ID \\\\W]\\\\$ \", FALSE);\n}", "void\nflatpak_run_apply_env_appid (FlatpakBwrap *bwrap,\n GFile *app_dir)\n{\n g_autoptr(GFile) app_dir_data = NULL;\n g_autoptr(GFile) app_dir_config = NULL;\n g_autoptr(GFile) app_dir_cache = NULL;", " app_dir_data = g_file_get_child (app_dir, \"data\");\n app_dir_config = g_file_get_child (app_dir, \"config\");\n app_dir_cache = g_file_get_child (app_dir, \"cache\");\n flatpak_bwrap_set_env (bwrap, \"XDG_DATA_HOME\", flatpak_file_get_path_cached (app_dir_data), TRUE);\n flatpak_bwrap_set_env (bwrap, \"XDG_CONFIG_HOME\", flatpak_file_get_path_cached (app_dir_config), TRUE);\n flatpak_bwrap_set_env (bwrap, \"XDG_CACHE_HOME\", flatpak_file_get_path_cached (app_dir_cache), TRUE);", " if (g_getenv (\"XDG_DATA_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_DATA_HOME\", g_getenv (\"XDG_DATA_HOME\"), TRUE);\n if (g_getenv (\"XDG_CONFIG_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_CONFIG_HOME\", g_getenv (\"XDG_CONFIG_HOME\"), TRUE);\n if (g_getenv (\"XDG_CACHE_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_CACHE_HOME\", g_getenv (\"XDG_CACHE_HOME\"), TRUE);\n}", "void\nflatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context)\n{\n GHashTableIter iter;\n gpointer key, value;", " g_hash_table_iter_init (&iter, context->env_vars);\n while (g_hash_table_iter_next (&iter, &key, &value))\n {\n const char *var = key;\n const char *val = value;", " if (val && val[0] != 0)\n flatpak_bwrap_set_env (bwrap, var, val, TRUE);\n else\n flatpak_bwrap_unset_env (bwrap, var);\n }\n}", "GFile *\nflatpak_get_data_dir (const char *app_id)\n{\n g_autoptr(GFile) home = g_file_new_for_path (g_get_home_dir ());\n g_autoptr(GFile) var_app = g_file_resolve_relative_path (home, \".var/app\");", " return g_file_get_child (var_app, app_id);\n}", "gboolean\nflatpak_ensure_data_dir (GFile *app_id_dir,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GFile) data_dir = g_file_get_child (app_id_dir, \"data\");\n g_autoptr(GFile) cache_dir = g_file_get_child (app_id_dir, \"cache\");\n g_autoptr(GFile) fontconfig_cache_dir = g_file_get_child (cache_dir, \"fontconfig\");\n g_autoptr(GFile) tmp_dir = g_file_get_child (cache_dir, \"tmp\");\n g_autoptr(GFile) config_dir = g_file_get_child (app_id_dir, \"config\");", " if (!flatpak_mkdir_p (data_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (cache_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (fontconfig_cache_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (tmp_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (config_dir, cancellable, error))\n return FALSE;", " return TRUE;\n}", "struct JobData\n{\n char *job;\n GMainLoop *main_loop;\n};", "static void\njob_removed_cb (SystemdManager *manager,\n guint32 id,\n char *job,\n char *unit,\n char *result,\n struct JobData *data)\n{\n if (strcmp (job, data->job) == 0)\n g_main_loop_quit (data->main_loop);\n}", "static gchar *\nsystemd_unit_name_escape (const gchar *in)\n{\n /* Adapted from systemd source */\n GString * const str = g_string_sized_new (strlen (in));", " for (; *in; in++)\n {\n if (g_ascii_isalnum (*in) || *in == ':' || *in == '_' || *in == '.')\n g_string_append_c (str, *in);\n else\n g_string_append_printf (str, \"\\\\x%02x\", *in);\n }\n return g_string_free (str, FALSE);\n}", "gboolean\nflatpak_run_in_transient_unit (const char *appid, GError **error)\n{\n g_autoptr(GDBusConnection) conn = NULL;\n g_autofree char *path = NULL;\n g_autofree char *address = NULL;\n g_autofree char *name = NULL;\n g_autofree char *appid_escaped = NULL;\n g_autofree char *job = NULL;\n SystemdManager *manager = NULL;\n GVariantBuilder builder;\n GVariant *properties = NULL;\n GVariant *aux = NULL;\n guint32 pid;\n GMainLoop *main_loop = NULL;\n struct JobData data;\n gboolean res = FALSE;\n g_autoptr(GMainContextPopDefault) main_context = NULL;", " path = g_strdup_printf (\"/run/user/%d/systemd/private\", getuid ());", " if (!g_file_test (path, G_FILE_TEST_EXISTS))\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,\n _(\"No systemd user session available, cgroups not available\"));", " main_context = flatpak_main_context_new_default ();\n main_loop = g_main_loop_new (main_context, FALSE);", " address = g_strconcat (\"unix:path=\", path, NULL);", " conn = g_dbus_connection_new_for_address_sync (address,\n G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,\n NULL,\n NULL, error);\n if (!conn)\n goto out;", " manager = systemd_manager_proxy_new_sync (conn,\n G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,\n NULL,\n \"/org/freedesktop/systemd1\",\n NULL, error);\n if (!manager)\n goto out;", " appid_escaped = systemd_unit_name_escape (appid);\n name = g_strdup_printf (\"app-flatpak-%s-%d.scope\", appid_escaped, getpid ());", " g_variant_builder_init (&builder, G_VARIANT_TYPE (\"a(sv)\"));", " pid = getpid ();\n g_variant_builder_add (&builder, \"(sv)\",\n \"PIDs\",\n g_variant_new_fixed_array (G_VARIANT_TYPE (\"u\"),\n &pid, 1, sizeof (guint32))\n );", " properties = g_variant_builder_end (&builder);", " aux = g_variant_new_array (G_VARIANT_TYPE (\"(sa(sv))\"), NULL, 0);", " if (!systemd_manager_call_start_transient_unit_sync (manager,\n name,\n \"fail\",\n properties,\n aux,\n &job,\n NULL,\n error))\n goto out;", " data.job = job;\n data.main_loop = main_loop;\n g_signal_connect (manager, \"job-removed\", G_CALLBACK (job_removed_cb), &data);", " g_main_loop_run (main_loop);", " res = TRUE;", "out:\n if (main_loop)\n g_main_loop_unref (main_loop);\n if (manager)\n g_object_unref (manager);", " return res;\n}", "static void\nadd_font_path_args (FlatpakBwrap *bwrap)\n{\n g_autoptr(GString) xml_snippet = g_string_new (\"\");\n gchar *path_build_tmp = NULL;\n g_autoptr(GFile) user_font1 = NULL;\n g_autoptr(GFile) user_font2 = NULL;\n g_autoptr(GFile) user_font_cache = NULL;\n g_auto(GStrv) system_cache_dirs = NULL;\n gboolean found_cache = FALSE;\n int i;", "\n g_string_append (xml_snippet,\n \"<?xml version=\\\"1.0\\\"?>\\n\"\n \"<!DOCTYPE fontconfig SYSTEM \\\"fonts.dtd\\\">\\n\"\n \"<fontconfig>\\n\");", " if (g_file_test (SYSTEM_FONTS_DIR, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", SYSTEM_FONTS_DIR, \"/run/host/fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/fonts</remap-dir>\\n\",\n SYSTEM_FONTS_DIR);\n }", " if (g_file_test (\"/usr/local/share/fonts\", G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/local/share/fonts\", \"/run/host/local-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/local-fonts</remap-dir>\\n\",\n \"/usr/local/share/fonts\");\n }", " system_cache_dirs = g_strsplit (SYSTEM_FONT_CACHE_DIRS, \":\", 0);\n for (i = 0; system_cache_dirs[i] != NULL; i++)\n {\n if (g_file_test (system_cache_dirs[i], G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", system_cache_dirs[i], \"/run/host/fonts-cache\",\n NULL);\n found_cache = TRUE;\n break;\n }\n }", " if (!found_cache)\n {\n /* We ensure these directories are never writable, or fontconfig\n will use them to write the default cache */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/run/host/fonts-cache\",\n \"--remount-ro\", \"/run/host/fonts-cache\",\n NULL);\n }", " path_build_tmp = g_build_filename (g_get_user_data_dir (), \"fonts\", NULL);\n user_font1 = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " path_build_tmp = g_build_filename (g_get_home_dir (), \".fonts\", NULL);\n user_font2 = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " if (g_file_query_exists (user_font1, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font1), \"/run/host/user-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/user-fonts</remap-dir>\\n\",\n flatpak_file_get_path_cached (user_font1));\n }\n else if (g_file_query_exists (user_font2, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font2), \"/run/host/user-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/user-fonts</remap-dir>\\n\",\n flatpak_file_get_path_cached (user_font2));\n }", " path_build_tmp = g_build_filename (g_get_user_cache_dir (), \"fontconfig\", NULL);\n user_font_cache = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " if (g_file_query_exists (user_font_cache, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font_cache), \"/run/host/user-fonts-cache\",\n NULL);\n }\n else\n {\n /* We ensure these directories are never writable, or fontconfig\n will use them to write the default cache */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/run/host/user-fonts-cache\",\n \"--remount-ro\", \"/run/host/user-fonts-cache\",\n NULL);\n }", " g_string_append (xml_snippet,\n \"</fontconfig>\\n\");", " if (!flatpak_bwrap_add_args_data (bwrap, \"font-dirs.xml\", xml_snippet->str, xml_snippet->len, \"/run/host/font-dirs.xml\", NULL))\n g_warning (\"Unable to add fontconfig data snippet\");\n}", "static void\nadd_icon_path_args (FlatpakBwrap *bwrap)\n{\n g_autofree gchar *user_icons_path = NULL;\n g_autoptr(GFile) user_icons = NULL;", " if (g_file_test (\"/usr/share/icons\", G_FILE_TEST_IS_DIR))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/share/icons\", \"/run/host/share/icons\",\n NULL);\n }", " user_icons_path = g_build_filename (g_get_user_data_dir (), \"icons\", NULL);\n user_icons = g_file_new_for_path (user_icons_path);\n if (g_file_query_exists (user_icons, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_icons), \"/run/host/user-share/icons\",\n NULL);\n }\n}", "FlatpakContext *\nflatpak_app_compute_permissions (GKeyFile *app_metadata,\n GKeyFile *runtime_metadata,\n GError **error)\n{\n g_autoptr(FlatpakContext) app_context = NULL;", " app_context = flatpak_context_new ();", " if (runtime_metadata != NULL)\n {\n if (!flatpak_context_load_metadata (app_context, runtime_metadata, error))\n return NULL;", " /* Don't inherit any permissions from the runtime, only things like env vars. */\n flatpak_context_reset_permissions (app_context);\n }", " if (app_metadata != NULL &&\n !flatpak_context_load_metadata (app_context, app_metadata, error))\n return NULL;", " return g_steal_pointer (&app_context);\n}", "static void\nflatpak_run_gc_ids (void)\n{\n flatpak_instance_iterate_all_and_gc (NULL);\n}", "static char *\nflatpak_run_allocate_id (int *lock_fd_out)\n{\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *base_dir = g_build_filename (user_runtime_dir, \".flatpak\", NULL);\n int count;", " g_mkdir_with_parents (base_dir, 0755);", " flatpak_run_gc_ids ();", " for (count = 0; count < 1000; count++)\n {\n g_autofree char *instance_id = NULL;\n g_autofree char *instance_dir = NULL;", " instance_id = g_strdup_printf (\"%u\", g_random_int ());", " instance_dir = g_build_filename (base_dir, instance_id, NULL);", " /* We use an atomic mkdir to ensure the instance id is unique */\n if (mkdir (instance_dir, 0755) == 0)\n {\n g_autofree char *lock_file = g_build_filename (instance_dir, \".ref\", NULL);\n glnx_autofd int lock_fd = -1;\n struct flock l = {\n .l_type = F_RDLCK,\n .l_whence = SEEK_SET,\n .l_start = 0,\n .l_len = 0\n };", " /* Then we take a file lock inside the dir, hold that during\n * setup and in bwrap. Anyone trying to clean up unused\n * directories need to first verify that there is a .ref\n * file and take a write lock on .ref to ensure its not in\n * use. */\n lock_fd = open (lock_file, O_RDWR | O_CREAT | O_CLOEXEC, 0644);\n /* There is a tiny race here between the open creating the file and the lock succeeding.\n We work around that by only gc:ing \"old\" .ref files */\n if (lock_fd != -1 && fcntl (lock_fd, F_SETLK, &l) == 0)\n {\n *lock_fd_out = glnx_steal_fd (&lock_fd);\n g_debug (\"Allocated instance id %s\", instance_id);\n return g_steal_pointer (&instance_id);\n }\n }\n }", " return NULL;\n}", "#ifdef HAVE_DCONF", "static void\nadd_dconf_key_to_keyfile (GKeyFile *keyfile,\n DConfClient *client,\n const char *key,\n DConfReadFlags flags)\n{\n g_autofree char *group = g_path_get_dirname (key);\n g_autofree char *k = g_path_get_basename (key);\n GVariant *value = dconf_client_read_full (client, key, flags, NULL);", " if (value)\n {\n g_autofree char *val = g_variant_print (value, TRUE);\n g_key_file_set_value (keyfile, group + 1, k, val);\n }\n}", "static void\nadd_dconf_dir_to_keyfile (GKeyFile *keyfile,\n DConfClient *client,\n const char *dir,\n DConfReadFlags flags)\n{\n g_auto(GStrv) keys = NULL;\n int i;", " keys = dconf_client_list (client, dir, NULL);\n for (i = 0; keys[i]; i++)\n {\n g_autofree char *k = g_strconcat (dir, keys[i], NULL);\n if (dconf_is_dir (k, NULL))\n add_dconf_dir_to_keyfile (keyfile, client, k, flags);\n else if (dconf_is_key (k, NULL))\n add_dconf_key_to_keyfile (keyfile, client, k, flags);\n }\n}", "static void\nadd_dconf_locks_to_list (GString *s,\n DConfClient *client,\n const char *dir)\n{\n g_auto(GStrv) locks = NULL;\n int i;", " locks = dconf_client_list_locks (client, dir, NULL);\n for (i = 0; locks[i]; i++)\n {\n g_string_append (s, locks[i]);\n g_string_append_c (s, '\\n');\n }\n}", "#endif /* HAVE_DCONF */", "static void\nget_dconf_data (const char *app_id,\n const char **paths,\n const char *migrate_path,\n char **defaults,\n gsize *defaults_size,\n char **values,\n gsize *values_size,\n char **locks,\n gsize *locks_size)\n{\n#ifdef HAVE_DCONF\n DConfClient *client = NULL;\n g_autofree char *prefix = NULL;\n#endif\n g_autoptr(GKeyFile) defaults_data = NULL;\n g_autoptr(GKeyFile) values_data = NULL;\n g_autoptr(GString) locks_data = NULL;", " defaults_data = g_key_file_new ();\n values_data = g_key_file_new ();\n locks_data = g_string_new (\"\");", "#ifdef HAVE_DCONF", " client = dconf_client_new ();", " prefix = flatpak_dconf_path_for_app_id (app_id);", " if (migrate_path)\n {\n g_debug (\"Add values in dir '%s', prefix is '%s'\", migrate_path, prefix);\n if (flatpak_dconf_path_is_similar (migrate_path, prefix))\n add_dconf_dir_to_keyfile (values_data, client, migrate_path, DCONF_READ_USER_VALUE);\n else\n g_warning (\"Ignoring D-Conf migrate-path setting %s\", migrate_path);\n }", " g_debug (\"Add defaults in dir %s\", prefix);\n add_dconf_dir_to_keyfile (defaults_data, client, prefix, DCONF_READ_DEFAULT_VALUE);", " g_debug (\"Add locks in dir %s\", prefix);\n add_dconf_locks_to_list (locks_data, client, prefix);", " /* We allow extra paths for defaults and locks, but not for user values */\n if (paths)\n {\n int i;\n for (i = 0; paths[i]; i++)\n {\n if (dconf_is_dir (paths[i], NULL))\n {\n g_debug (\"Add defaults in dir %s\", paths[i]);\n add_dconf_dir_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);", " g_debug (\"Add locks in dir %s\", paths[i]);\n add_dconf_locks_to_list (locks_data, client, paths[i]);\n }\n else if (dconf_is_key (paths[i], NULL))\n {\n g_debug (\"Add individual key %s\", paths[i]);\n add_dconf_key_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);\n add_dconf_key_to_keyfile (values_data, client, paths[i], DCONF_READ_USER_VALUE);\n }\n else\n {\n g_warning (\"Ignoring settings path '%s': neither dir nor key\", paths[i]);\n }\n }\n }\n#endif", " *defaults = g_key_file_to_data (defaults_data, defaults_size, NULL);\n *values = g_key_file_to_data (values_data, values_size, NULL);\n *locks_size = locks_data->len;\n *locks = g_string_free (g_steal_pointer (&locks_data), FALSE);", "#ifdef HAVE_DCONF\n g_object_unref (client);\n#endif\n}", "static gboolean\nflatpak_run_add_dconf_args (FlatpakBwrap *bwrap,\n const char *app_id,\n GKeyFile *metakey,\n GError **error)\n{\n g_auto(GStrv) paths = NULL;\n g_autofree char *migrate_path = NULL;\n g_autofree char *defaults = NULL;\n g_autofree char *values = NULL;\n g_autofree char *locks = NULL;\n gsize defaults_size;\n gsize values_size;\n gsize locks_size;", " if (metakey)\n {\n paths = g_key_file_get_string_list (metakey,\n FLATPAK_METADATA_GROUP_DCONF,\n FLATPAK_METADATA_KEY_DCONF_PATHS,\n NULL, NULL);\n migrate_path = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_DCONF,\n FLATPAK_METADATA_KEY_DCONF_MIGRATE_PATH,\n NULL);\n }", " get_dconf_data (app_id,\n (const char **) paths,\n migrate_path,\n &defaults, &defaults_size,\n &values, &values_size,\n &locks, &locks_size);", " if (defaults_size != 0 &&\n !flatpak_bwrap_add_args_data (bwrap,\n \"dconf-defaults\",\n defaults, defaults_size,\n \"/etc/glib-2.0/settings/defaults\",\n error))\n return FALSE;", " if (locks_size != 0 &&\n !flatpak_bwrap_add_args_data (bwrap,\n \"dconf-locks\",\n locks, locks_size,\n \"/etc/glib-2.0/settings/locks\",\n error))\n return FALSE;", " /* We do a one-time conversion of existing dconf settings to a keyfile.\n * Only do that once the app stops requesting dconf access.\n */\n if (migrate_path)\n {\n g_autofree char *filename = NULL;", " filename = g_build_filename (g_get_home_dir (),\n \".var/app\", app_id,\n \"config/glib-2.0/settings/keyfile\",\n NULL);", " g_debug (\"writing D-Conf values to %s\", filename);", " if (values_size != 0 && !g_file_test (filename, G_FILE_TEST_EXISTS))\n {\n g_autofree char *dir = g_path_get_dirname (filename);", " if (g_mkdir_with_parents (dir, 0700) == -1)\n {\n g_warning (\"failed creating dirs for %s\", filename);\n return FALSE;\n }", " if (!g_file_set_contents (filename, values, values_size, error))\n {\n g_warning (\"failed writing %s\", filename);\n return FALSE;\n }\n }\n }", " return TRUE;\n}", "gboolean\nflatpak_run_add_app_info_args (FlatpakBwrap *bwrap,\n GFile *app_files,\n GBytes *app_deploy_data,\n const char *app_extensions,\n GFile *runtime_files,\n GBytes *runtime_deploy_data,\n const char *runtime_extensions,\n const char *app_id,\n const char *app_branch,\n FlatpakDecomposed *runtime_ref,\n GFile *app_id_dir,\n FlatpakContext *final_app_context,\n FlatpakContext *cmdline_context,\n gboolean sandbox,\n gboolean build,\n gboolean devel,\n char **app_info_path_out,\n int instance_id_fd,\n char **instance_id_host_dir_out,\n GError **error)\n{\n g_autofree char *info_path = NULL;\n g_autofree char *bwrapinfo_path = NULL;\n int fd, fd2, fd3;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree char *runtime_path = NULL;\n g_autofree char *old_dest = g_strdup_printf (\"/run/user/%d/flatpak-info\", getuid ());\n const char *group;\n g_autofree char *instance_id = NULL;\n glnx_autofd int lock_fd = -1;\n g_autofree char *instance_id_host_dir = NULL;\n g_autofree char *instance_id_sandbox_dir = NULL;\n g_autofree char *instance_id_lock_file = NULL;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *arch = flatpak_decomposed_dup_arch (runtime_ref);", " instance_id = flatpak_run_allocate_id (&lock_fd);\n if (instance_id == NULL)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Unable to allocate instance id\"));", " instance_id_host_dir = g_build_filename (user_runtime_dir, \".flatpak\", instance_id, NULL);\n instance_id_sandbox_dir = g_strdup_printf (\"/run/user/%d/.flatpak/%s\", getuid (), instance_id);\n instance_id_lock_file = g_build_filename (instance_id_sandbox_dir, \".ref\", NULL);", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\",\n instance_id_host_dir,\n instance_id_sandbox_dir,\n \"--lock-file\",\n instance_id_lock_file,\n NULL);\n /* Keep the .ref lock held until we've started bwrap to avoid races */\n flatpak_bwrap_add_noinherit_fd (bwrap, glnx_steal_fd (&lock_fd));", " info_path = g_build_filename (instance_id_host_dir, \"info\", NULL);", " keyfile = g_key_file_new ();", " if (app_files)\n group = FLATPAK_METADATA_GROUP_APPLICATION;\n else\n group = FLATPAK_METADATA_GROUP_RUNTIME;", " g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_NAME, app_id);\n g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_RUNTIME,\n flatpak_decomposed_get_ref (runtime_ref));", " g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, instance_id);\n if (app_id_dir)\n {\n g_autofree char *instance_path = g_file_get_path (app_id_dir);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, instance_path);\n }", " if (app_files)\n {\n g_autofree char *app_path = g_file_get_path (app_files);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_PATH, app_path);\n }\n if (app_deploy_data)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, flatpak_deploy_data_get_commit (app_deploy_data));\n if (app_extensions && *app_extensions != 0)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_EXTENSIONS, app_extensions);\n runtime_path = g_file_get_path (runtime_files);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_PATH, runtime_path);\n if (runtime_deploy_data)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, flatpak_deploy_data_get_commit (runtime_deploy_data));\n if (runtime_extensions && *runtime_extensions != 0)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_EXTENSIONS, runtime_extensions);\n if (app_branch != NULL)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, app_branch);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, arch);", " g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_FLATPAK_VERSION, PACKAGE_VERSION);", " if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) == 0)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SESSION_BUS_PROXY, TRUE);", " if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) == 0)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SYSTEM_BUS_PROXY, TRUE);", " if (sandbox)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SANDBOX, TRUE);\n if (build)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BUILD, TRUE);\n if (devel)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, TRUE);", " if (cmdline_context)\n {\n g_autoptr(GPtrArray) cmdline_args = g_ptr_array_new_with_free_func (g_free);\n flatpak_context_to_args (cmdline_context, cmdline_args);\n if (cmdline_args->len > 0)\n {\n g_key_file_set_string_list (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS,\n (const char * const *) cmdline_args->pdata,\n cmdline_args->len);\n }\n }", " flatpak_context_save_metadata (final_app_context, TRUE, keyfile);", " if (!g_key_file_save_to_file (keyfile, info_path, error))\n return FALSE;", " /* We want to create a file on /.flatpak-info that the app cannot modify, which\n we do by creating a read-only bind mount. This way one can openat()\n /proc/$pid/root, and if that succeeds use openat via that to find the\n unfakable .flatpak-info file. However, there is a tiny race in that if\n you manage to open /proc/$pid/root, but then the pid dies, then\n every mount but the root is unmounted in the namespace, so the\n .flatpak-info will be empty. We fix this by first creating a real file\n with the real info in, then bind-mounting on top of that, the same info.\n This way even if the bind-mount is unmounted we can find the real data.\n */", " fd = open (info_path, O_RDONLY);\n if (fd == -1)\n {\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open flatpak-info file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " fd2 = open (info_path, O_RDONLY);\n if (fd2 == -1)\n {\n close (fd);\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open flatpak-info file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " flatpak_bwrap_add_args_data_fd (bwrap,\n \"--file\", fd, \"/.flatpak-info\");\n flatpak_bwrap_add_args_data_fd (bwrap,\n \"--ro-bind-data\", fd2, \"/.flatpak-info\");\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", \"../../../.flatpak-info\", old_dest,\n NULL);", " /* Tell the application that it's running under Flatpak in a generic way. */\n flatpak_bwrap_add_args (bwrap,\n \"--setenv\", \"container\", \"flatpak\",\n NULL);\n if (!flatpak_bwrap_add_args_data (bwrap,\n \"container-manager\",\n \"flatpak\\n\", -1,\n \"/run/host/container-manager\",\n error))\n return FALSE;", " bwrapinfo_path = g_build_filename (instance_id_host_dir, \"bwrapinfo.json\", NULL);\n fd3 = open (bwrapinfo_path, O_RDWR | O_CREAT, 0644);\n if (fd3 == -1)\n {\n close (fd);\n close (fd2);\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open bwrapinfo.json file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " /* NOTE: It is important that this takes place after bwrapinfo.json is created,\n otherwise start notifications in the portal may not work. */\n if (instance_id_fd != -1)\n {\n gsize instance_id_position = 0;\n gsize instance_id_size = strlen (instance_id);", " while (instance_id_size > 0)\n {\n gssize bytes_written = write (instance_id_fd, instance_id + instance_id_position, instance_id_size);\n if (G_UNLIKELY (bytes_written <= 0))\n {\n int errsv = bytes_written == -1 ? errno : ENOSPC;\n if (errsv == EINTR)\n continue;", " close (fd);\n close (fd2);\n close (fd3);", " g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to write to instance id fd: %s\"), g_strerror (errsv));\n return FALSE;\n }", " instance_id_position += bytes_written;\n instance_id_size -= bytes_written;\n }", " close (instance_id_fd);\n }", " flatpak_bwrap_add_args_data_fd (bwrap, \"--info-fd\", fd3, NULL);", " if (app_info_path_out != NULL)\n *app_info_path_out = g_strdup_printf (\"/proc/self/fd/%d\", fd);", " if (instance_id_host_dir_out != NULL)\n *instance_id_host_dir_out = g_steal_pointer (&instance_id_host_dir);", " return TRUE;\n}", "static void\nadd_tzdata_args (FlatpakBwrap *bwrap,\n GFile *runtime_files)\n{\n g_autofree char *raw_timezone = flatpak_get_timezone ();\n g_autofree char *timezone_content = g_strdup_printf (\"%s\\n\", raw_timezone);\n g_autofree char *localtime_content = g_strconcat (\"../usr/share/zoneinfo/\", raw_timezone, NULL);\n g_autoptr(GFile) runtime_zoneinfo = NULL;", " if (runtime_files)\n runtime_zoneinfo = g_file_resolve_relative_path (runtime_files, \"share/zoneinfo\");", " /* Check for runtime /usr/share/zoneinfo */\n if (runtime_zoneinfo != NULL && g_file_query_exists (runtime_zoneinfo, NULL))\n {\n /* Check for host /usr/share/zoneinfo */\n if (g_file_test (\"/usr/share/zoneinfo\", G_FILE_TEST_IS_DIR))\n {\n /* Here we assume the host timezone file exist in the host data */\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/share/zoneinfo\", \"/usr/share/zoneinfo\",\n \"--symlink\", localtime_content, \"/etc/localtime\",\n NULL);\n }\n else\n {\n g_autoptr(GFile) runtime_tzfile = g_file_resolve_relative_path (runtime_zoneinfo, raw_timezone);", " /* Check if host timezone file exist in the runtime tzdata */\n if (g_file_query_exists (runtime_tzfile, NULL))\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", localtime_content, \"/etc/localtime\",\n NULL);\n }\n }", " flatpak_bwrap_add_args_data (bwrap, \"timezone\",\n timezone_content, -1, \"/etc/timezone\",\n NULL);\n}", "static void\nadd_monitor_path_args (gboolean use_session_helper,\n FlatpakBwrap *bwrap)\n{\n g_autoptr(AutoFlatpakSessionHelper) session_helper = NULL;\n g_autofree char *monitor_path = NULL;\n g_autofree char *pkcs11_socket_path = NULL;\n g_autoptr(GVariant) session_data = NULL;", " if (use_session_helper)\n {\n session_helper =\n flatpak_session_helper_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,\n G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,\n \"org.freedesktop.Flatpak\",\n \"/org/freedesktop/Flatpak/SessionHelper\",\n NULL, NULL);\n }", " if (session_helper &&\n flatpak_session_helper_call_request_session_sync (session_helper,\n &session_data,\n NULL, NULL))\n {\n if (g_variant_lookup (session_data, \"path\", \"s\", &monitor_path))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", monitor_path, \"/run/host/monitor\",\n \"--symlink\", \"/run/host/monitor/resolv.conf\", \"/etc/resolv.conf\",\n \"--symlink\", \"/run/host/monitor/host.conf\", \"/etc/host.conf\",\n \"--symlink\", \"/run/host/monitor/hosts\", \"/etc/hosts\",\n NULL);", " if (g_variant_lookup (session_data, \"pkcs11-socket\", \"s\", &pkcs11_socket_path))\n {\n g_autofree char *sandbox_pkcs11_socket_path = g_strdup_printf (\"/run/user/%d/p11-kit/pkcs11\", getuid ());\n const char *trusted_module_contents =\n \"# This overrides the runtime p11-kit-trusted module with a client one talking to the trust module on the host\\n\"\n \"module: p11-kit-client.so\\n\";", " if (flatpak_bwrap_add_args_data (bwrap, \"p11-kit-trust.module\",\n trusted_module_contents, -1,\n \"/etc/pkcs11/modules/p11-kit-trust.module\", NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pkcs11_socket_path, sandbox_pkcs11_socket_path,\n NULL);\n flatpak_bwrap_unset_env (bwrap, \"P11_KIT_SERVER_ADDRESS\");\n }\n }\n }\n else\n {\n if (g_file_test (\"/etc/resolv.conf\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/resolv.conf\", \"/etc/resolv.conf\",\n NULL);\n if (g_file_test (\"/etc/host.conf\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/host.conf\", \"/etc/host.conf\",\n NULL);\n if (g_file_test (\"/etc/hosts\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/hosts\", \"/etc/hosts\",\n NULL);\n }\n}", "static void\nadd_document_portal_args (FlatpakBwrap *bwrap,\n const char *app_id,\n char **out_mount_path)\n{\n g_autoptr(GDBusConnection) session_bus = NULL;\n g_autofree char *doc_mount_path = NULL;", " session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);\n if (session_bus)\n {\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDBusMessage) reply = NULL;\n g_autoptr(GDBusMessage) msg =\n g_dbus_message_new_method_call (\"org.freedesktop.portal.Documents\",\n \"/org/freedesktop/portal/documents\",\n \"org.freedesktop.portal.Documents\",\n \"GetMountPoint\");\n g_dbus_message_set_body (msg, g_variant_new (\"()\"));\n reply =\n g_dbus_connection_send_message_with_reply_sync (session_bus, msg,\n G_DBUS_SEND_MESSAGE_FLAGS_NONE,\n 30000,\n NULL,\n NULL,\n NULL);\n if (reply)\n {\n if (g_dbus_message_to_gerror (reply, &local_error))\n {\n if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))\n g_debug (\"Document portal not available, not mounting /run/user/%d/doc\", getuid ());\n else\n g_message (\"Can't get document portal: %s\", local_error->message);\n }\n else\n {\n g_autofree char *src_path = NULL;\n g_autofree char *dst_path = NULL;\n g_variant_get (g_dbus_message_get_body (reply),\n \"(^ay)\", &doc_mount_path);", " src_path = g_strdup_printf (\"%s/by-app/%s\",\n doc_mount_path, app_id);\n dst_path = g_strdup_printf (\"/run/user/%d/doc\", getuid ());\n flatpak_bwrap_add_args (bwrap, \"--bind\", src_path, dst_path, NULL);\n }\n }\n }", " *out_mount_path = g_steal_pointer (&doc_mount_path);\n}", "#ifdef ENABLE_SECCOMP\nstatic const uint32_t seccomp_x86_64_extra_arches[] = { SCMP_ARCH_X86, 0, };", "#ifdef SCMP_ARCH_AARCH64\nstatic const uint32_t seccomp_aarch64_extra_arches[] = { SCMP_ARCH_ARM, 0 };\n#endif", "static inline void\ncleanup_seccomp (void *p)\n{\n scmp_filter_ctx *pp = (scmp_filter_ctx *) p;", " if (*pp)\n seccomp_release (*pp);\n}", "static gboolean\nsetup_seccomp (FlatpakBwrap *bwrap,\n const char *arch,\n gulong allowed_personality,\n FlatpakRunFlags run_flags,\n GError **error)\n{\n gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;\n gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;", " __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;", " /**** BEGIN NOTE ON CODE SHARING\n *\n * There are today a number of different Linux container\n * implementations. That will likely continue for long into the\n * future. But we can still try to share code, and it's important\n * to do so because it affects what library and application writers\n * can do, and we should support code portability between different\n * container tools.\n *\n * This syscall blocklist is copied from linux-user-chroot, which was in turn\n * clearly influenced by the Sandstorm.io blocklist.\n *\n * If you make any changes here, I suggest sending the changes along\n * to other sandbox maintainers. Using the libseccomp list is also\n * an appropriate venue:\n * https://groups.google.com/forum/#!forum/libseccomp\n *\n * A non-exhaustive list of links to container tooling that might\n * want to share this blocklist:\n *\n * https://github.com/sandstorm-io/sandstorm\n * in src/sandstorm/supervisor.c++\n * https://github.com/flatpak/flatpak.git\n * in common/flatpak-run.c\n * https://git.gnome.org/browse/linux-user-chroot\n * in src/setup-seccomp.c\n *\n **** END NOTE ON CODE SHARING\n */\n struct\n {\n int scall;\n struct scmp_arg_cmp *arg;\n } syscall_blocklist[] = {\n /* Block dmesg */\n {SCMP_SYS (syslog)},\n /* Useless old syscall */\n {SCMP_SYS (uselib)},\n /* Don't allow disabling accounting */\n {SCMP_SYS (acct)},\n /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a\n historic source of interesting information leaks. */\n {SCMP_SYS (modify_ldt)},\n /* Don't allow reading current quota use */\n {SCMP_SYS (quotactl)},", " /* Don't allow access to the kernel keyring */\n {SCMP_SYS (add_key)},\n {SCMP_SYS (keyctl)},\n {SCMP_SYS (request_key)},", " /* Scary VM/NUMA ops */\n {SCMP_SYS (move_pages)},\n {SCMP_SYS (mbind)},\n {SCMP_SYS (get_mempolicy)},\n {SCMP_SYS (set_mempolicy)},\n {SCMP_SYS (migrate_pages)},", " /* Don't allow subnamespace setups: */\n {SCMP_SYS (unshare)},\n {SCMP_SYS (mount)},\n {SCMP_SYS (pivot_root)},\n#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack\n * and flags arguments are reversed so the flags come second */\n {SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#else\n /* Normally the flags come first */\n {SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#endif", " /* Don't allow faking input to the controlling tty (CVE-2017-5226) */\n {SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},\n };", " struct\n {\n int scall;\n struct scmp_arg_cmp *arg;\n } syscall_nondevel_blocklist[] = {\n /* Profiling operations; we expect these to be done by tools from outside\n * the sandbox. In particular perf has been the source of many CVEs.\n */\n {SCMP_SYS (perf_event_open)},\n /* Don't allow you to switch to bsd emulation or whatnot */\n {SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},\n {SCMP_SYS (ptrace)}\n };\n /* Blocklist all but unix, inet, inet6 and netlink */\n struct\n {\n int family;\n FlatpakRunFlags flags_mask;\n } socket_family_allowlist[] = {\n /* NOTE: Keep in numerical order */\n { AF_UNSPEC, 0 },\n { AF_LOCAL, 0 },\n { AF_INET, 0 },\n { AF_INET6, 0 },\n { AF_NETLINK, 0 },\n { AF_CAN, FLATPAK_RUN_FLAG_CANBUS },\n { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },\n };\n int last_allowed_family;\n int i, r;\n g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };", " seccomp = seccomp_init (SCMP_ACT_ALLOW);\n if (!seccomp)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Initialize seccomp failed\"));", " if (arch != NULL)\n {\n uint32_t arch_id = 0;\n const uint32_t *extra_arches = NULL;", " if (strcmp (arch, \"i386\") == 0)\n {\n arch_id = SCMP_ARCH_X86;\n }\n else if (strcmp (arch, \"x86_64\") == 0)\n {\n arch_id = SCMP_ARCH_X86_64;\n extra_arches = seccomp_x86_64_extra_arches;\n }\n else if (strcmp (arch, \"arm\") == 0)\n {\n arch_id = SCMP_ARCH_ARM;\n }\n#ifdef SCMP_ARCH_AARCH64\n else if (strcmp (arch, \"aarch64\") == 0)\n {\n arch_id = SCMP_ARCH_AARCH64;\n extra_arches = seccomp_aarch64_extra_arches;\n }\n#endif", " /* We only really need to handle arches on multiarch systems.\n * If only one arch is supported the default is fine */\n if (arch_id != 0)\n {\n /* This *adds* the target arch, instead of replacing the\n native one. This is not ideal, because we'd like to only\n allow the target arch, but we can't really disallow the\n native arch at this point, because then bubblewrap\n couldn't continue running. */\n r = seccomp_arch_add (seccomp, arch_id);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add architecture to seccomp filter\"));", " if (multiarch && extra_arches != NULL)\n {\n for (i = 0; extra_arches[i] != 0; i++)\n {\n r = seccomp_arch_add (seccomp, extra_arches[i]);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add multiarch architecture to seccomp filter\"));\n }\n }\n }\n }", " /* TODO: Should we filter the kernel keyring syscalls in some way?\n * We do want them to be used by desktop apps, but they could also perhaps\n * leak system stuff or secrets from other apps.\n */", " for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)\n {\n int scall = syscall_blocklist[i].scall;\n if (syscall_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }", " if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)\n {\n int scall = syscall_nondevel_blocklist[i].scall;\n if (syscall_nondevel_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);", " if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n }", " /* Socket filtering doesn't work on e.g. i386, so ignore failures here\n * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing\n * something else: https://github.com/seccomp/libseccomp/issues/8 */\n last_allowed_family = -1;\n for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)\n {\n int family = socket_family_allowlist[i].family;\n int disallowed;", " if (socket_family_allowlist[i].flags_mask != 0 &&\n (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)\n continue;", " for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)\n {\n /* Blocklist the in-between valid families */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));\n }\n last_allowed_family = family;\n }\n /* Blocklist the rest */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));", " if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &seccomp_tmpf, error))\n return FALSE;", " if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to export bpf\"));", " lseek (seccomp_tmpf.fd, 0, SEEK_SET);", " flatpak_bwrap_add_args_data_fd (bwrap,\n \"--seccomp\", glnx_steal_fd (&seccomp_tmpf.fd), NULL);", " return TRUE;\n}\n#endif", "static void\nflatpak_run_setup_usr_links (FlatpakBwrap *bwrap,\n GFile *runtime_files)\n{\n int i;", " if (runtime_files == NULL)\n return;", " for (i = 0; flatpak_abs_usrmerged_dirs[i] != NULL; i++)\n {\n const char *subdir = flatpak_abs_usrmerged_dirs[i];\n g_autoptr(GFile) runtime_subdir = NULL;", " g_assert (subdir[0] == '/');\n /* Skip the '/' when using as a subdirectory of the runtime */\n runtime_subdir = g_file_get_child (runtime_files, subdir + 1);", " if (g_file_query_exists (runtime_subdir, NULL))\n {\n g_autofree char *link = g_strconcat (\"usr\", subdir, NULL);\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", link, subdir,\n NULL);\n }\n }\n}", "gboolean\nflatpak_run_setup_base_argv (FlatpakBwrap *bwrap,\n GFile *runtime_files,\n GFile *app_id_dir,\n const char *arch,\n FlatpakRunFlags flags,\n GError **error)\n{\n g_autofree char *run_dir = NULL;\n g_autofree char *passwd_contents = NULL;\n g_autoptr(GString) group_contents = NULL;\n const char *pkcs11_conf_contents = NULL;\n struct group *g;\n gulong pers;\n gid_t gid = getgid ();\n g_autoptr(GFile) etc = NULL;", " run_dir = g_strdup_printf (\"/run/user/%d\", getuid ());", " passwd_contents = g_strdup_printf (\"%s:x:%d:%d:%s:%s:%s\\n\"\n \"nfsnobody:x:65534:65534:Unmapped user:/:/sbin/nologin\\n\",\n g_get_user_name (),\n getuid (), gid,\n g_get_real_name (),\n g_get_home_dir (),\n DEFAULT_SHELL);", " group_contents = g_string_new (\"\");\n g = getgrgid (gid);\n /* if NULL, the primary group is not known outside the container, so\n * it might as well stay unknown inside the container... */\n if (g != NULL)\n g_string_append_printf (group_contents, \"%s:x:%d:%s\\n\",\n g->gr_name, gid, g_get_user_name ());\n g_string_append (group_contents, \"nfsnobody:x:65534:\\n\");", " pkcs11_conf_contents =\n \"# Disable user pkcs11 config, because the host modules don't work in the runtime\\n\"\n \"user-config: none\\n\";", " if ((flags & FLATPAK_RUN_FLAG_NO_PROC) == 0)\n flatpak_bwrap_add_args (bwrap,\n \"--proc\", \"/proc\",\n NULL);", " if (!(flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS))\n flatpak_bwrap_add_arg (bwrap, \"--unshare-pid\");", " flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/tmp\",\n \"--dir\", \"/var/tmp\",\n \"--dir\", \"/run/host\",\n \"--dir\", run_dir,\n \"--setenv\", \"XDG_RUNTIME_DIR\", run_dir,\n \"--symlink\", \"../run\", \"/var/run\",\n \"--ro-bind\", \"/sys/block\", \"/sys/block\",\n \"--ro-bind\", \"/sys/bus\", \"/sys/bus\",\n \"--ro-bind\", \"/sys/class\", \"/sys/class\",\n \"--ro-bind\", \"/sys/dev\", \"/sys/dev\",\n \"--ro-bind\", \"/sys/devices\", \"/sys/devices\",\n \"--ro-bind-try\", \"/proc/self/ns/user\", \"/run/.userns\",\n /* glib uses this like /etc/timezone */\n \"--symlink\", \"/etc/timezone\", \"/var/db/zoneinfo\",\n NULL);", " if (flags & FLATPAK_RUN_FLAG_DIE_WITH_PARENT)\n flatpak_bwrap_add_args (bwrap,\n \"--die-with-parent\",\n NULL);", " if (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC)\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/usr/etc\",\n \"--symlink\", \"usr/etc\", \"/etc\",\n NULL);", " if (!flatpak_bwrap_add_args_data (bwrap, \"passwd\", passwd_contents, -1, \"/etc/passwd\", error))\n return FALSE;", " if (!flatpak_bwrap_add_args_data (bwrap, \"group\", group_contents->str, -1, \"/etc/group\", error))\n return FALSE;", " if (!flatpak_bwrap_add_args_data (bwrap, \"pkcs11.conf\", pkcs11_conf_contents, -1, \"/etc/pkcs11/pkcs11.conf\", error))\n return FALSE;", " if (g_file_test (\"/etc/machine-id\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", \"/etc/machine-id\", \"/etc/machine-id\", NULL);\n else if (g_file_test (\"/var/lib/dbus/machine-id\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", \"/var/lib/dbus/machine-id\", \"/etc/machine-id\", NULL);", " if (runtime_files)\n etc = g_file_get_child (runtime_files, \"etc\");\n if (etc != NULL &&\n (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0 &&\n g_file_query_exists (etc, NULL))\n {\n g_auto(GLnxDirFdIterator) dfd_iter = { 0, };\n struct dirent *dent;\n gboolean inited;", " inited = glnx_dirfd_iterator_init_at (AT_FDCWD, flatpak_file_get_path_cached (etc), FALSE, &dfd_iter, NULL);", " while (inited)\n {\n g_autofree char *src = NULL;\n g_autofree char *dest = NULL;", " if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, NULL, NULL) || dent == NULL)\n break;", " if (strcmp (dent->d_name, \"passwd\") == 0 ||\n strcmp (dent->d_name, \"group\") == 0 ||\n strcmp (dent->d_name, \"machine-id\") == 0 ||\n strcmp (dent->d_name, \"resolv.conf\") == 0 ||\n strcmp (dent->d_name, \"host.conf\") == 0 ||\n strcmp (dent->d_name, \"hosts\") == 0 ||\n strcmp (dent->d_name, \"localtime\") == 0 ||\n strcmp (dent->d_name, \"timezone\") == 0 ||\n strcmp (dent->d_name, \"pkcs11\") == 0)\n continue;", " src = g_build_filename (flatpak_file_get_path_cached (etc), dent->d_name, NULL);\n dest = g_build_filename (\"/etc\", dent->d_name, NULL);\n if (dent->d_type == DT_LNK)\n {\n g_autofree char *target = NULL;", " target = glnx_readlinkat_malloc (dfd_iter.fd, dent->d_name,\n NULL, error);\n if (target == NULL)\n return FALSE;", " flatpak_bwrap_add_args (bwrap, \"--symlink\", target, dest, NULL);\n }\n else\n {\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", src, dest, NULL);\n }\n }\n }", " if (app_id_dir != NULL)\n {\n g_autoptr(GFile) app_cache_dir = g_file_get_child (app_id_dir, \"cache\");\n g_autoptr(GFile) app_tmp_dir = g_file_get_child (app_cache_dir, \"tmp\");\n g_autoptr(GFile) app_data_dir = g_file_get_child (app_id_dir, \"data\");\n g_autoptr(GFile) app_config_dir = g_file_get_child (app_id_dir, \"config\");", " flatpak_bwrap_add_args (bwrap,\n /* These are nice to have as a fixed path */\n \"--bind\", flatpak_file_get_path_cached (app_cache_dir), \"/var/cache\",\n \"--bind\", flatpak_file_get_path_cached (app_data_dir), \"/var/data\",\n \"--bind\", flatpak_file_get_path_cached (app_config_dir), \"/var/config\",\n \"--bind\", flatpak_file_get_path_cached (app_tmp_dir), \"/var/tmp\",\n NULL);\n }", " flatpak_run_setup_usr_links (bwrap, runtime_files);", " add_tzdata_args (bwrap, runtime_files);", " pers = PER_LINUX;", " if ((flags & FLATPAK_RUN_FLAG_SET_PERSONALITY) &&\n flatpak_is_linux32_arch (arch))\n {\n g_debug (\"Setting personality linux32\");\n pers = PER_LINUX32;\n }", " /* Always set the personallity, and clear all weird flags */\n personality (pers);", "#ifdef ENABLE_SECCOMP\n if (!setup_seccomp (bwrap, arch, pers, flags, error))\n return FALSE;\n#endif", " if ((flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0)\n add_monitor_path_args ((flags & FLATPAK_RUN_FLAG_NO_SESSION_HELPER) == 0, bwrap);", " return TRUE;\n}", "static gboolean\nforward_file (XdpDbusDocuments *documents,\n const char *app_id,\n const char *file,\n char **out_doc_id,\n GError **error)\n{\n int fd, fd_id;\n g_autofree char *doc_id = NULL;\n g_autoptr(GUnixFDList) fd_list = NULL;\n const char *perms[] = { \"read\", \"write\", NULL };", " fd = open (file, O_PATH | O_CLOEXEC);\n if (fd == -1)\n return flatpak_fail (error, _(\"Failed to open ‘%s’\"), file);", " fd_list = g_unix_fd_list_new ();\n fd_id = g_unix_fd_list_append (fd_list, fd, error);\n close (fd);", " if (!xdp_dbus_documents_call_add_sync (documents,\n g_variant_new (\"h\", fd_id),\n TRUE, /* reuse */\n FALSE, /* not persistent */\n fd_list,\n &doc_id,\n NULL,\n NULL,\n error))\n {\n if (error)\n g_dbus_error_strip_remote_error (*error);\n return FALSE;\n }", " if (!xdp_dbus_documents_call_grant_permissions_sync (documents,\n doc_id,\n app_id,\n perms,\n NULL,\n error))\n {\n if (error)\n g_dbus_error_strip_remote_error (*error);\n return FALSE;\n }", " *out_doc_id = g_steal_pointer (&doc_id);", " return TRUE;\n}", "static gboolean\nadd_rest_args (FlatpakBwrap *bwrap,\n const char *app_id,\n FlatpakExports *exports,\n gboolean file_forwarding,\n const char *doc_mount_path,\n char *args[],\n int n_args,\n GError **error)\n{\n g_autoptr(XdpDbusDocuments) documents = NULL;\n gboolean forwarding = FALSE;\n gboolean forwarding_uri = FALSE;\n gboolean can_forward = TRUE;\n int i;", " if (file_forwarding && doc_mount_path == NULL)\n {\n g_message (\"Can't get document portal mount path\");\n can_forward = FALSE;\n }\n else if (file_forwarding)\n {\n g_autoptr(GError) local_error = NULL;", " documents = xdp_dbus_documents_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, 0,\n \"org.freedesktop.portal.Documents\",\n \"/org/freedesktop/portal/documents\",\n NULL,\n &local_error);\n if (documents == NULL)\n {\n g_message (\"Can't get document portal: %s\", local_error->message);\n can_forward = FALSE;\n }\n }", " for (i = 0; i < n_args; i++)\n {\n g_autoptr(GFile) file = NULL;", " if (file_forwarding &&\n (strcmp (args[i], \"@@\") == 0 ||\n strcmp (args[i], \"@@u\") == 0))\n {\n forwarding_uri = strcmp (args[i], \"@@u\") == 0;\n forwarding = !forwarding;\n continue;\n }", " if (can_forward && forwarding)\n {\n if (forwarding_uri)\n {\n if (g_str_has_prefix (args[i], \"file:\"))\n file = g_file_new_for_uri (args[i]);\n else if (G_IS_DIR_SEPARATOR (args[i][0]))\n file = g_file_new_for_path (args[i]);\n }\n else\n file = g_file_new_for_path (args[i]);\n }", " if (file && !flatpak_exports_path_is_visible (exports,\n flatpak_file_get_path_cached (file)))\n {\n g_autofree char *doc_id = NULL;\n g_autofree char *basename = NULL;\n g_autofree char *doc_path = NULL;\n if (!forward_file (documents, app_id, flatpak_file_get_path_cached (file),\n &doc_id, error))\n return FALSE;", " basename = g_file_get_basename (file);\n doc_path = g_build_filename (doc_mount_path, doc_id, basename, NULL);", " if (forwarding_uri)\n {\n g_autofree char *path = doc_path;\n doc_path = g_filename_to_uri (path, NULL, NULL);\n /* This should never fail */\n g_assert (doc_path != NULL);\n }", " g_debug (\"Forwarding file '%s' as '%s' to %s\", args[i], doc_path, app_id);\n flatpak_bwrap_add_arg (bwrap, doc_path);\n }\n else\n flatpak_bwrap_add_arg (bwrap, args[i]);\n }", " return TRUE;\n}", "FlatpakContext *\nflatpak_context_load_for_deploy (FlatpakDeploy *deploy,\n GError **error)\n{\n g_autoptr(FlatpakContext) context = NULL;\n g_autoptr(FlatpakContext) overrides = NULL;\n g_autoptr(GKeyFile) metakey = NULL;", " metakey = flatpak_deploy_get_metadata (deploy);\n context = flatpak_app_compute_permissions (metakey, NULL, error);\n if (context == NULL)\n return NULL;", " overrides = flatpak_deploy_get_overrides (deploy);\n flatpak_context_merge (context, overrides);", " return g_steal_pointer (&context);\n}", "static char *\ncalculate_ld_cache_checksum (GBytes *app_deploy_data,\n GBytes *runtime_deploy_data,\n const char *app_extensions,\n const char *runtime_extensions)\n{\n g_autoptr(GChecksum) ld_so_checksum = g_checksum_new (G_CHECKSUM_SHA256);\n if (app_deploy_data)\n g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (app_deploy_data), -1);\n g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (runtime_deploy_data), -1);\n if (app_extensions)\n g_checksum_update (ld_so_checksum, (guchar *) app_extensions, -1);\n if (runtime_extensions)\n g_checksum_update (ld_so_checksum, (guchar *) runtime_extensions, -1);", " return g_strdup (g_checksum_get_string (ld_so_checksum));\n}", "static gboolean\nadd_ld_so_conf (FlatpakBwrap *bwrap,\n GError **error)\n{\n const char *contents =\n \"include /run/flatpak/ld.so.conf.d/app-*.conf\\n\"\n \"include /app/etc/ld.so.conf\\n\"\n \"/app/lib\\n\"\n \"include /run/flatpak/ld.so.conf.d/runtime-*.conf\\n\";", " return flatpak_bwrap_add_args_data (bwrap, \"ld-so-conf\",\n contents, -1, \"/etc/ld.so.conf\", error);\n}", "static int\nregenerate_ld_cache (GPtrArray *base_argv_array,\n GArray *base_fd_array,\n GFile *app_id_dir,\n const char *checksum,\n GFile *runtime_files,\n gboolean generate_ld_so_conf,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(FlatpakBwrap) bwrap = NULL;\n g_autoptr(GArray) combined_fd_array = NULL;\n g_autoptr(GFile) ld_so_cache = NULL;\n g_autoptr(GFile) ld_so_cache_tmp = NULL;\n g_autofree char *sandbox_cache_path = NULL;\n g_autofree char *tmp_basename = NULL;\n g_auto(GStrv) minimal_envp = NULL;\n g_autofree char *commandline = NULL;\n int exit_status;\n glnx_autofd int ld_so_fd = -1;\n g_autoptr(GFile) ld_so_dir = NULL;", " if (app_id_dir)\n ld_so_dir = g_file_get_child (app_id_dir, \".ld.so\");\n else\n {\n g_autoptr(GFile) base_dir = g_file_new_for_path (g_get_user_cache_dir ());\n ld_so_dir = g_file_resolve_relative_path (base_dir, \"flatpak/ld.so\");\n }", " ld_so_cache = g_file_get_child (ld_so_dir, checksum);\n ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache), O_RDONLY);\n if (ld_so_fd >= 0)\n return glnx_steal_fd (&ld_so_fd);", " g_debug (\"Regenerating ld.so.cache %s\", flatpak_file_get_path_cached (ld_so_cache));", " if (!flatpak_mkdir_p (ld_so_dir, cancellable, error))\n return FALSE;", " minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);\n bwrap = flatpak_bwrap_new (minimal_envp);", " flatpak_bwrap_append_args (bwrap, base_argv_array);", " flatpak_run_setup_usr_links (bwrap, runtime_files);", " if (generate_ld_so_conf)\n {\n if (!add_ld_so_conf (bwrap, error))\n return -1;\n }\n else\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", \"../usr/etc/ld.so.conf\", \"/etc/ld.so.conf\",\n NULL);", " tmp_basename = g_strconcat (checksum, \".XXXXXX\", NULL);\n glnx_gen_temp_name (tmp_basename);", " sandbox_cache_path = g_build_filename (\"/run/ld-so-cache-dir\", tmp_basename, NULL);\n ld_so_cache_tmp = g_file_get_child (ld_so_dir, tmp_basename);", " flatpak_bwrap_add_args (bwrap,\n \"--unshare-pid\",\n \"--unshare-ipc\",\n \"--unshare-net\",\n \"--proc\", \"/proc\",\n \"--dev\", \"/dev\",\n \"--bind\", flatpak_file_get_path_cached (ld_so_dir), \"/run/ld-so-cache-dir\",\n NULL);", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return -1;", " flatpak_bwrap_add_args (bwrap,\n \"ldconfig\", \"-X\", \"-C\", sandbox_cache_path, NULL);", " flatpak_bwrap_finish (bwrap);", " commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);\n g_debug (\"Running: '%s'\", commandline);", " combined_fd_array = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_append_vals (combined_fd_array, base_fd_array->data, base_fd_array->len);\n g_array_append_vals (combined_fd_array, bwrap->fds->data, bwrap->fds->len);", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_sync (NULL,\n (char **) bwrap->argv->pdata,\n bwrap->envp,\n G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n flatpak_bwrap_child_setup_cb, combined_fd_array,\n NULL, NULL,\n &exit_status,\n error))\n return -1;", " if (!WIFEXITED (exit_status) || WEXITSTATUS (exit_status) != 0)\n {\n flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,\n _(\"ldconfig failed, exit status %d\"), exit_status);\n return -1;\n }", " ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache_tmp), O_RDONLY);\n if (ld_so_fd < 0)\n {\n flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Can't open generated ld.so.cache\"));\n return -1;\n }", " if (app_id_dir == NULL)\n {\n /* For runs without an app id dir we always regenerate the ld.so.cache */\n unlink (flatpak_file_get_path_cached (ld_so_cache_tmp));\n }\n else\n {\n g_autoptr(GFile) active = g_file_get_child (ld_so_dir, \"active\");", " /* For app-dirs we keep one checksum alive, by pointing the active symlink to it */", " /* Rename to known name, possibly overwriting existing ref if race */\n if (rename (flatpak_file_get_path_cached (ld_so_cache_tmp), flatpak_file_get_path_cached (ld_so_cache)) == -1)\n {\n glnx_set_error_from_errno (error);\n return -1;\n }", " if (!flatpak_switch_symlink_and_remove (flatpak_file_get_path_cached (active),\n checksum, error))\n return -1;\n }", " return glnx_steal_fd (&ld_so_fd);\n}", "/* Check that this user is actually allowed to run this app. When running\n * from the gnome-initial-setup session, an app filter might not be available. */\nstatic gboolean\ncheck_parental_controls (FlatpakDecomposed *app_ref,\n FlatpakDeploy *deploy,\n GCancellable *cancellable,\n GError **error)\n{\n#ifdef HAVE_LIBMALCONTENT\n g_autoptr(MctManager) manager = NULL;\n g_autoptr(MctAppFilter) app_filter = NULL;\n g_autoptr(GAsyncResult) app_filter_result = NULL;\n g_autoptr(GDBusConnection) system_bus = NULL;\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDesktopAppInfo) app_info = NULL;\n gboolean allowed = FALSE;", " system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);\n if (system_bus == NULL)\n return FALSE;", " manager = mct_manager_new (system_bus);\n app_filter = mct_manager_get_app_filter (manager, getuid (),\n MCT_GET_APP_FILTER_FLAGS_INTERACTIVE,\n cancellable, &local_error);\n if (g_error_matches (local_error, MCT_APP_FILTER_ERROR, MCT_APP_FILTER_ERROR_DISABLED))\n {\n g_debug (\"Skipping parental controls check for %s since parental \"\n \"controls are disabled globally\", flatpak_decomposed_get_ref (app_ref));\n return TRUE;\n }\n else if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN) ||\n g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_NAME_HAS_NO_OWNER))\n {\n g_debug (\"Skipping parental controls check for %s since a required \"\n \"service was not found\", flatpak_decomposed_get_ref (app_ref));\n return TRUE;\n }\n else if (local_error != NULL)\n {\n g_propagate_error (error, g_steal_pointer (&local_error));\n return FALSE;\n }", " /* Always filter by app ID. Additionally, filter by app info (which runs\n * multiple checks, including whether the app ID, executable path and\n * content types are allowed) if available. If the flatpak contains\n * multiple .desktop files, we use the main one. The app ID check is\n * always done, as the binary executed by `flatpak run` isn’t necessarily\n * extracted from a .desktop file. */\n allowed = mct_app_filter_is_flatpak_ref_allowed (app_filter, flatpak_decomposed_get_ref (app_ref));", " /* Look up the app’s main .desktop file. */\n if (deploy != NULL && allowed)\n {\n g_autoptr(GFile) deploy_dir = NULL;\n const char *deploy_path;\n g_autofree char *desktop_file_name = NULL;\n g_autofree char *desktop_file_path = NULL;\n g_autofree char *app_id = flatpak_decomposed_dup_id (app_ref);", " deploy_dir = flatpak_deploy_get_dir (deploy);\n deploy_path = flatpak_file_get_path_cached (deploy_dir);", " desktop_file_name = g_strconcat (app_id, \".desktop\", NULL);\n desktop_file_path = g_build_path (G_DIR_SEPARATOR_S,\n deploy_path,\n \"export\",\n \"share\",\n \"applications\",\n desktop_file_name,\n NULL);\n app_info = g_desktop_app_info_new_from_filename (desktop_file_path);\n }", " if (app_info != NULL)\n allowed = allowed && mct_app_filter_is_appinfo_allowed (app_filter,\n G_APP_INFO (app_info));", " if (!allowed)\n return flatpak_fail_error (error, FLATPAK_ERROR_PERMISSION_DENIED,\n /* Translators: The placeholder is for an app ref. */\n _(\"Running %s is not allowed by the policy set by your administrator\"),\n flatpak_decomposed_get_ref (app_ref));\n#endif /* HAVE_LIBMALCONTENT */", " return TRUE;\n}", "static int\nopen_namespace_fd_if_needed (const char *path,\n const char *other_path) {\n struct stat s, other_s;", " if (stat (path, &s) != 0)\n return -1; /* No such namespace, ignore */", " if (stat (other_path, &other_s) != 0)\n return -1; /* No such namespace, ignore */", " /* setns calls fail if the process is already in the desired namespace, hence the\n check here to ensure the namespaces are different. */\n if (s.st_ino != other_s.st_ino)\n return open (path, O_RDONLY|O_CLOEXEC);", " return -1;\n}", "static gboolean\ncheck_sudo (GError **error)\n{\n const char *sudo_command_env = g_getenv (\"SUDO_COMMAND\");\n g_auto(GStrv) split_command = NULL;", " /* This check exists to stop accidental usage of `sudo flatpak run`\n and is not to prevent running as root.\n */", " if (!sudo_command_env)\n return TRUE;", " /* SUDO_COMMAND could be a value like `/usr/bin/flatpak run foo` */\n split_command = g_strsplit (sudo_command_env, \" \", 2);\n if (g_str_has_suffix (split_command[0], \"flatpak\"))\n return flatpak_fail_error (error, FLATPAK_ERROR, _(\"\\\"flatpak run\\\" is not intended to be ran with sudo\"));", " return TRUE;\n}", "gboolean\nflatpak_run_app (FlatpakDecomposed *app_ref,\n FlatpakDeploy *app_deploy,\n FlatpakContext *extra_context,\n const char *custom_runtime,\n const char *custom_runtime_version,\n const char *custom_runtime_commit,\n int parent_pid,\n FlatpakRunFlags flags,\n const char *cwd,\n const char *custom_command,\n char *args[],\n int n_args,\n int instance_id_fd,\n char **instance_dir_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(FlatpakDeploy) runtime_deploy = NULL;\n g_autoptr(GBytes) runtime_deploy_data = NULL;\n g_autoptr(GBytes) app_deploy_data = NULL;\n g_autoptr(GFile) app_files = NULL;\n g_autoptr(GFile) runtime_files = NULL;\n g_autoptr(GFile) bin_ldconfig = NULL;\n g_autoptr(GFile) app_id_dir = NULL;\n g_autoptr(GFile) real_app_id_dir = NULL;\n g_autofree char *default_runtime_pref = NULL;\n g_autoptr(FlatpakDecomposed) default_runtime = NULL;\n g_autofree char *default_command = NULL;\n g_autoptr(GKeyFile) metakey = NULL;\n g_autoptr(GKeyFile) runtime_metakey = NULL;\n g_autoptr(FlatpakBwrap) bwrap = NULL;\n const char *command = \"/bin/sh\";\n g_autoptr(GError) my_error = NULL;\n g_autoptr(FlatpakDecomposed) runtime_ref = NULL;\n int i;\n g_autoptr(GPtrArray) previous_app_id_dirs = NULL;\n g_autofree char *app_id = NULL;\n g_autofree char *app_arch = NULL;\n g_autofree char *app_info_path = NULL;\n g_autofree char *instance_id_host_dir = NULL;\n g_autoptr(FlatpakContext) app_context = NULL;\n g_autoptr(FlatpakContext) overrides = NULL;\n g_autoptr(FlatpakExports) exports = NULL;\n g_autofree char *commandline = NULL;\n g_autofree char *doc_mount_path = NULL;\n g_autofree char *app_extensions = NULL;\n g_autofree char *runtime_extensions = NULL;\n g_autofree char *checksum = NULL;\n int ld_so_fd = -1;\n g_autoptr(GFile) runtime_ld_so_conf = NULL;\n gboolean generate_ld_so_conf = TRUE;\n gboolean use_ld_so_cache = TRUE;\n gboolean sandboxed = (flags & FLATPAK_RUN_FLAG_SANDBOX) != 0;\n gboolean parent_expose_pids = (flags & FLATPAK_RUN_FLAG_PARENT_EXPOSE_PIDS) != 0;\n gboolean parent_share_pids = (flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS) != 0;\n struct stat s;", " if (!check_sudo (error))\n return FALSE;", " app_id = flatpak_decomposed_dup_id (app_ref);\n app_arch = flatpak_decomposed_dup_arch (app_ref);", " /* Check the user is allowed to run this flatpak. */\n if (!check_parental_controls (app_ref, app_deploy, cancellable, error))\n return FALSE;", " /* Construct the bwrap context. */\n bwrap = flatpak_bwrap_new (NULL);\n flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());", " if (app_deploy == NULL)\n {\n g_assert (flatpak_decomposed_is_runtime (app_ref));\n default_runtime_pref = flatpak_decomposed_dup_pref (app_ref);\n }\n else\n {\n const gchar *key;", " app_deploy_data = flatpak_deploy_get_deploy_data (app_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);\n if (app_deploy_data == NULL)\n return FALSE;", " if ((flags & FLATPAK_RUN_FLAG_DEVEL) != 0)\n key = FLATPAK_METADATA_KEY_SDK;\n else\n key = FLATPAK_METADATA_KEY_RUNTIME;", " metakey = flatpak_deploy_get_metadata (app_deploy);\n default_runtime_pref = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_APPLICATION,\n key, &my_error);\n if (my_error)\n {\n g_propagate_error (error, g_steal_pointer (&my_error));\n return FALSE;\n }\n }", " default_runtime = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, default_runtime_pref, error);\n if (default_runtime == NULL)\n return FALSE;", " if (custom_runtime != NULL || custom_runtime_version != NULL)\n {\n g_auto(GStrv) custom_runtime_parts = NULL;\n const char *custom_runtime_id = NULL;\n const char *custom_runtime_arch = NULL;", " if (custom_runtime)\n {\n custom_runtime_parts = g_strsplit (custom_runtime, \"/\", 0);\n for (i = 0; i < 3 && custom_runtime_parts[i] != NULL; i++)\n {\n if (strlen (custom_runtime_parts[i]) > 0)\n {\n if (i == 0)\n custom_runtime_id = custom_runtime_parts[i];\n if (i == 1)\n custom_runtime_arch = custom_runtime_parts[i];", " if (i == 2 && custom_runtime_version == NULL)\n custom_runtime_version = custom_runtime_parts[i];\n }\n }\n }", " runtime_ref = flatpak_decomposed_new_from_decomposed (default_runtime,\n FLATPAK_KINDS_RUNTIME,\n custom_runtime_id,\n custom_runtime_arch,\n custom_runtime_version,\n error);\n if (runtime_ref == NULL)\n return FALSE;\n }\n else\n runtime_ref = flatpak_decomposed_ref (default_runtime);", " runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), custom_runtime_commit, NULL, cancellable, error);\n if (runtime_deploy == NULL)\n return FALSE;", " runtime_deploy_data = flatpak_deploy_get_deploy_data (runtime_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);\n if (runtime_deploy_data == NULL)\n return FALSE;", " runtime_metakey = flatpak_deploy_get_metadata (runtime_deploy);", " app_context = flatpak_app_compute_permissions (metakey, runtime_metakey, error);\n if (app_context == NULL)\n return FALSE;", " if (app_deploy != NULL)\n {\n overrides = flatpak_deploy_get_overrides (app_deploy);\n flatpak_context_merge (app_context, overrides);\n }", " if (sandboxed)\n flatpak_context_make_sandboxed (app_context);", " if (extra_context)\n flatpak_context_merge (app_context, extra_context);", " runtime_files = flatpak_deploy_get_files (runtime_deploy);\n bin_ldconfig = g_file_resolve_relative_path (runtime_files, \"bin/ldconfig\");\n if (!g_file_query_exists (bin_ldconfig, NULL))\n use_ld_so_cache = FALSE;", " if (app_deploy != NULL)\n {\n g_autofree const char **previous_ids = NULL;\n gsize len = 0;\n gboolean do_migrate;", " real_app_id_dir = flatpak_get_data_dir (app_id);\n app_files = flatpak_deploy_get_files (app_deploy);", " previous_app_id_dirs = g_ptr_array_new_with_free_func (g_object_unref);\n previous_ids = flatpak_deploy_data_get_previous_ids (app_deploy_data, &len);", " do_migrate = !g_file_query_exists (real_app_id_dir, cancellable);", " /* When migrating, find most recent old existing source and rename that to\n * the new name.\n *\n * We ignore other names than that. For more recent names that don't exist\n * we never ran them so nothing will even reference them. For older names\n * either they were not used, or they were used but then the more recent\n * name was used and a symlink to it was created.\n *\n * This means we may end up with a chain of symlinks: oldest -> old -> current.\n * This is unfortunate but not really a problem, but for robustness reasons we\n * don't want to mess with user files unnecessary. For example, the app dir could\n * actually be a symlink for other reasons. Imagine for instance that you want to put the\n * steam games somewhere else so you leave the app dir as a symlink to /mnt/steam.\n */\n for (i = len - 1; i >= 0; i--)\n {\n g_autoptr(GFile) previous_app_id_dir = NULL;\n g_autoptr(GFileInfo) previous_app_id_dir_info = NULL;\n g_autoptr(GError) local_error = NULL;", " previous_app_id_dir = flatpak_get_data_dir (previous_ids[i]);\n previous_app_id_dir_info = g_file_query_info (previous_app_id_dir,\n G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK \",\"\n G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,\n G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n cancellable,\n &local_error);\n /* Warn about the migration failures, but don't make them fatal, then you can never run the app */\n if (previous_app_id_dir_info == NULL)\n {\n if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) && do_migrate)\n {\n g_warning (_(\"Failed to migrate from %s: %s\"), flatpak_file_get_path_cached (previous_app_id_dir),\n local_error->message);\n do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to the thing that we failed on */\n }", " g_clear_error (&local_error);\n continue;\n }", " if (do_migrate)\n {\n do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to this dir */", " if (!flatpak_file_rename (previous_app_id_dir, real_app_id_dir, cancellable, &local_error))\n {\n g_warning (_(\"Failed to migrate old app data directory %s to new name %s: %s\"),\n flatpak_file_get_path_cached (previous_app_id_dir), app_id,\n local_error->message);\n }\n else\n {\n /* Leave a symlink in place of the old data dir */\n if (!g_file_make_symbolic_link (previous_app_id_dir, app_id, cancellable, &local_error))\n {\n g_warning (_(\"Failed to create symlink while migrating %s: %s\"),\n flatpak_file_get_path_cached (previous_app_id_dir),\n local_error->message);\n }\n }\n }", " /* Give app access to this old dir */\n g_ptr_array_add (previous_app_id_dirs, g_steal_pointer (&previous_app_id_dir));\n }", " if (!flatpak_ensure_data_dir (real_app_id_dir, cancellable, error))\n return FALSE;", " if (!sandboxed)\n app_id_dir = g_object_ref (real_app_id_dir);\n }", " flatpak_run_apply_env_default (bwrap, use_ld_so_cache);\n flatpak_run_apply_env_vars (bwrap, app_context);\n flatpak_run_apply_env_prompt (bwrap, app_id);", " if (real_app_id_dir)\n {\n g_autoptr(GFile) sandbox_dir = g_file_get_child (real_app_id_dir, \"sandbox\");\n flatpak_bwrap_set_env (bwrap, \"FLATPAK_SANDBOX_DIR\", flatpak_file_get_path_cached (sandbox_dir), TRUE);\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (runtime_files), \"/usr\",\n \"--lock-file\", \"/usr/.ref\",\n NULL);", " if (app_files != NULL)\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (app_files), \"/app\",\n \"--lock-file\", \"/app/.ref\",\n NULL);\n else\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/app\",\n NULL);", " if (metakey != NULL &&\n !flatpak_run_add_extension_args (bwrap, metakey, app_ref, use_ld_so_cache, &app_extensions, cancellable, error))\n return FALSE;", " if (!flatpak_run_add_extension_args (bwrap, runtime_metakey, runtime_ref, use_ld_so_cache, &runtime_extensions, cancellable, error))\n return FALSE;", " runtime_ld_so_conf = g_file_resolve_relative_path (runtime_files, \"etc/ld.so.conf\");\n if (lstat (flatpak_file_get_path_cached (runtime_ld_so_conf), &s) == 0)\n generate_ld_so_conf = S_ISREG (s.st_mode) && s.st_size == 0;", " /* At this point we have the minimal argv set up, with just the app, runtime and extensions.\n We can reuse this to generate the ld.so.cache (if needed) */\n if (use_ld_so_cache)\n {\n checksum = calculate_ld_cache_checksum (app_deploy_data, runtime_deploy_data,\n app_extensions, runtime_extensions);\n ld_so_fd = regenerate_ld_cache (bwrap->argv,\n bwrap->fds,\n app_id_dir,\n checksum,\n runtime_files,\n generate_ld_so_conf,\n cancellable, error);\n if (ld_so_fd == -1)\n return FALSE;\n flatpak_bwrap_add_fd (bwrap, ld_so_fd);\n }", " flags |= flatpak_context_get_run_flags (app_context);", " if (!flatpak_run_setup_base_argv (bwrap, runtime_files, app_id_dir, app_arch, flags, error))\n return FALSE;", " if (generate_ld_so_conf)\n {\n if (!add_ld_so_conf (bwrap, error))\n return FALSE;\n }", " if (ld_so_fd != -1)\n {\n /* Don't add to fd_array, its already there */\n flatpak_bwrap_add_arg (bwrap, \"--ro-bind-data\");\n flatpak_bwrap_add_arg_printf (bwrap, \"%d\", ld_so_fd);\n flatpak_bwrap_add_arg (bwrap, \"/etc/ld.so.cache\");\n }", " if (!flatpak_run_add_app_info_args (bwrap,\n app_files, app_deploy_data, app_extensions,\n runtime_files, runtime_deploy_data, runtime_extensions,\n app_id, flatpak_decomposed_get_branch (app_ref),\n runtime_ref, app_id_dir, app_context, extra_context,\n sandboxed, FALSE, flags & FLATPAK_RUN_FLAG_DEVEL,\n &app_info_path, instance_id_fd, &instance_id_host_dir,\n error))\n return FALSE;", " if (!flatpak_run_add_dconf_args (bwrap, app_id, metakey, error))\n return FALSE;", " if (!sandboxed && !(flags & FLATPAK_RUN_FLAG_NO_DOCUMENTS_PORTAL))\n add_document_portal_args (bwrap, app_id, &doc_mount_path);", " if (!flatpak_run_add_environment_args (bwrap, app_info_path, flags,\n app_id, app_context, app_id_dir, previous_app_id_dirs,\n &exports, cancellable, error))\n return FALSE;", " if ((app_context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) != 0)\n flatpak_run_add_resolved_args (bwrap);", " flatpak_run_add_journal_args (bwrap);\n add_font_path_args (bwrap);\n add_icon_path_args (bwrap);", " flatpak_bwrap_add_args (bwrap,\n /* Not in base, because we don't want this for flatpak build */\n \"--symlink\", \"/app/lib/debug/source\", \"/run/build\",\n \"--symlink\", \"/usr/lib/debug/source\", \"/run/build-runtime\",\n NULL);", " if (cwd)\n flatpak_bwrap_add_args (bwrap, \"--chdir\", cwd, NULL);", " if (parent_expose_pids || parent_share_pids)\n {\n g_autofree char *userns_path = NULL;\n g_autofree char *pidns_path = NULL;\n g_autofree char *userns2_path = NULL;\n int userns_fd, userns2_fd, pidns_fd;", " if (parent_pid == 0)\n return flatpak_fail (error, \"No parent pid specified\");", " userns_path = g_strdup_printf (\"/proc/%d/root/run/.userns\", parent_pid);", " userns_fd = open_namespace_fd_if_needed (userns_path, \"/proc/self/ns/user\");\n if (userns_fd != -1)\n {\n flatpak_bwrap_add_args_data_fd (bwrap, \"--userns\", userns_fd, NULL);", " userns2_path = g_strdup_printf (\"/proc/%d/ns/user\", parent_pid);\n userns2_fd = open_namespace_fd_if_needed (userns2_path, userns_path);\n if (userns2_fd != -1)\n flatpak_bwrap_add_args_data_fd (bwrap, \"--userns2\", userns2_fd, NULL);\n }", " pidns_path = g_strdup_printf (\"/proc/%d/ns/pid\", parent_pid);\n pidns_fd = open (pidns_path, O_RDONLY|O_CLOEXEC);\n if (pidns_fd != -1)\n flatpak_bwrap_add_args_data_fd (bwrap, \"--pidns\", pidns_fd, NULL);\n }", " if (custom_command)\n {\n command = custom_command;\n }\n else if (metakey)\n {\n default_command = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_COMMAND,\n &my_error);\n if (my_error)\n {\n g_propagate_error (error, g_steal_pointer (&my_error));\n return FALSE;\n }\n command = default_command;\n }\n", "", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return FALSE;", " flatpak_bwrap_add_arg (bwrap, command);", " if (!add_rest_args (bwrap, app_id,\n exports, (flags & FLATPAK_RUN_FLAG_FILE_FORWARDING) != 0,\n doc_mount_path,\n args, n_args, error))\n return FALSE;", " flatpak_bwrap_finish (bwrap);", " commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);\n g_debug (\"Running '%s'\", commandline);", " if ((flags & FLATPAK_RUN_FLAG_BACKGROUND) != 0)\n {\n GPid child_pid;\n char pid_str[64];\n g_autofree char *pid_path = NULL;\n GSpawnFlags spawn_flags;", " spawn_flags = G_SPAWN_SEARCH_PATH;\n if (flags & FLATPAK_RUN_FLAG_DO_NOT_REAP)\n spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;", "", "\n if (!g_spawn_async (NULL,\n (char **) bwrap->argv->pdata,\n bwrap->envp,\n spawn_flags,\n flatpak_bwrap_child_setup_cb, bwrap->fds,\n &child_pid,\n error))\n return FALSE;", " g_snprintf (pid_str, sizeof (pid_str), \"%d\", child_pid);\n pid_path = g_build_filename (instance_id_host_dir, \"pid\", NULL);\n g_file_set_contents (pid_path, pid_str, -1, NULL);\n }\n else\n {\n char pid_str[64];\n g_autofree char *pid_path = NULL;", " g_snprintf (pid_str, sizeof (pid_str), \"%d\", getpid ());\n pid_path = g_build_filename (instance_id_host_dir, \"pid\", NULL);\n g_file_set_contents (pid_path, pid_str, -1, NULL);", " /* Ensure we unset O_CLOEXEC for marked fds and rewind fds as needed.\n * Note that this does not close fds that are not already marked O_CLOEXEC, because\n * we do want to allow inheriting fds into flatpak run. */\n flatpak_bwrap_child_setup (bwrap->fds, FALSE);\n", "", " if (execvpe (flatpak_get_bwrap (), (char **) bwrap->argv->pdata, bwrap->envp) == -1)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Unable to start app\"));\n return FALSE;\n }\n /* Not actually reached... */\n }", " if (instance_dir_out)\n *instance_dir_out = g_steal_pointer (&instance_id_host_dir);", " return TRUE;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright © 2014-2019 Red Hat, Inc\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library 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.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n * Authors:\n * Alexander Larsson <alexl@redhat.com>\n */", "#include \"config.h\"", "#include <string.h>\n#include <ctype.h>\n#include <fcntl.h>\n#include <gio/gdesktopappinfo.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/utsname.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/vfs.h>\n#include <sys/personality.h>\n#include <grp.h>\n#include <unistd.h>\n#include <gio/gunixfdlist.h>\n#ifdef HAVE_DCONF\n#include <dconf/dconf.h>\n#endif\n#ifdef HAVE_LIBMALCONTENT\n#include <libmalcontent/malcontent.h>\n#endif", "#ifdef ENABLE_SECCOMP\n#include <seccomp.h>\n#endif", "#ifdef ENABLE_XAUTH\n#include <X11/Xauth.h>\n#endif", "#include <glib/gi18n-lib.h>", "#include <gio/gio.h>\n#include \"libglnx/libglnx.h\"", "#include \"flatpak-run-private.h\"\n#include \"flatpak-proxy.h\"\n#include \"flatpak-utils-base-private.h\"\n#include \"flatpak-dir-private.h\"\n#include \"flatpak-instance-private.h\"\n#include \"flatpak-systemd-dbus-generated.h\"\n#include \"flatpak-document-dbus-generated.h\"\n#include \"flatpak-error.h\"", "#define DEFAULT_SHELL \"/bin/sh\"", "const char * const abs_usrmerged_dirs[] =\n{\n \"/bin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/sbin\",\n NULL\n};\nconst char * const *flatpak_abs_usrmerged_dirs = abs_usrmerged_dirs;", "static char *\nextract_unix_path_from_dbus_address (const char *address)\n{\n const char *path, *path_end;", " if (address == NULL)\n return NULL;", " if (!g_str_has_prefix (address, \"unix:\"))\n return NULL;", " path = strstr (address, \"path=\");\n if (path == NULL)\n return NULL;\n path += strlen (\"path=\");\n path_end = path;\n while (*path_end != 0 && *path_end != ',')\n path_end++;", " return g_strndup (path, path_end - path);\n}", "#ifdef ENABLE_XAUTH\nstatic gboolean\nauth_streq (char *str,\n char *au_str,\n int au_len)\n{\n return au_len == strlen (str) && memcmp (str, au_str, au_len) == 0;\n}", "static gboolean\nxauth_entry_should_propagate (Xauth *xa,\n char *hostname,\n char *number)\n{\n /* ensure entry isn't for remote access */\n if (xa->family != FamilyLocal && xa->family != FamilyWild)\n return FALSE;", " /* ensure entry is for this machine */\n if (xa->family == FamilyLocal && !auth_streq (hostname, xa->address, xa->address_length))\n return FALSE;", " /* ensure entry is for this session */\n if (xa->number != NULL && !auth_streq (number, xa->number, xa->number_length))\n return FALSE;", " return TRUE;\n}", "static void\nwrite_xauth (char *number, FILE *output)\n{\n Xauth *xa, local_xa;\n char *filename;\n FILE *f;\n struct utsname unames;", " if (uname (&unames))\n {\n g_warning (\"uname failed\");\n return;\n }", " filename = XauFileName ();\n f = fopen (filename, \"rb\");\n if (f == NULL)\n return;", " while (TRUE)\n {\n xa = XauReadAuth (f);\n if (xa == NULL)\n break;\n if (xauth_entry_should_propagate (xa, unames.nodename, number))\n {\n local_xa = *xa;\n if (local_xa.number)\n {\n local_xa.number = \"99\";\n local_xa.number_length = 2;\n }", " if (!XauWriteAuth (output, &local_xa))\n g_warning (\"xauth write error\");\n }", " XauDisposeAuth (xa);\n }", " fclose (f);\n}\n#endif /* ENABLE_XAUTH */", "static void\nflatpak_run_add_x11_args (FlatpakBwrap *bwrap,\n gboolean allowed)\n{\n g_autofree char *x11_socket = NULL;\n const char *display;", " /* Always cover /tmp/.X11-unix, that way we never see the host one in case\n * we have access to the host /tmp. If you request X access we'll put the right\n * thing in this anyway.\n */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/tmp/.X11-unix\",\n NULL);", " if (!allowed)\n {\n flatpak_bwrap_unset_env (bwrap, \"DISPLAY\");\n return;\n }", " g_debug (\"Allowing x11 access\");", " display = g_getenv (\"DISPLAY\");\n if (display && display[0] == ':' && g_ascii_isdigit (display[1]))\n {\n const char *display_nr = &display[1];\n const char *display_nr_end = display_nr;\n g_autofree char *d = NULL;", " while (g_ascii_isdigit (*display_nr_end))\n display_nr_end++;", " d = g_strndup (display_nr, display_nr_end - display_nr);\n x11_socket = g_strdup_printf (\"/tmp/.X11-unix/X%s\", d);", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", x11_socket, \"/tmp/.X11-unix/X99\",\n NULL);\n flatpak_bwrap_set_env (bwrap, \"DISPLAY\", \":99.0\", TRUE);", "#ifdef ENABLE_XAUTH\n g_auto(GLnxTmpfile) xauth_tmpf = { 0, };", " if (glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &xauth_tmpf, NULL))\n {\n FILE *output = fdopen (xauth_tmpf.fd, \"wb\");\n if (output != NULL)\n {\n /* fd is now owned by output, steal it from the tmpfile */\n int tmp_fd = dup (glnx_steal_fd (&xauth_tmpf.fd));\n if (tmp_fd != -1)\n {\n g_autofree char *dest = g_strdup_printf (\"/run/user/%d/Xauthority\", getuid ());", " write_xauth (d, output);\n flatpak_bwrap_add_args_data_fd (bwrap, \"--ro-bind-data\", tmp_fd, dest);", " flatpak_bwrap_set_env (bwrap, \"XAUTHORITY\", dest, TRUE);\n }", " fclose (output);", " if (tmp_fd != -1)\n lseek (tmp_fd, 0, SEEK_SET);\n }\n }\n#endif\n }\n else\n {\n flatpak_bwrap_unset_env (bwrap, \"DISPLAY\");\n }\n}", "static gboolean\nflatpak_run_add_wayland_args (FlatpakBwrap *bwrap)\n{\n const char *wayland_display;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *wayland_socket = NULL;\n g_autofree char *sandbox_wayland_socket = NULL;\n gboolean res = FALSE;\n struct stat statbuf;", " wayland_display = g_getenv (\"WAYLAND_DISPLAY\");\n if (!wayland_display)\n wayland_display = \"wayland-0\";", " wayland_socket = g_build_filename (user_runtime_dir, wayland_display, NULL);\n sandbox_wayland_socket = g_strdup_printf (\"/run/user/%d/%s\", getuid (), wayland_display);", " if (stat (wayland_socket, &statbuf) == 0 &&\n (statbuf.st_mode & S_IFMT) == S_IFSOCK)\n {\n res = TRUE;\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", wayland_socket, sandbox_wayland_socket,\n NULL);\n }\n return res;\n}", "static void\nflatpak_run_add_ssh_args (FlatpakBwrap *bwrap)\n{\n const char * auth_socket;\n g_autofree char * sandbox_auth_socket = NULL;", " auth_socket = g_getenv (\"SSH_AUTH_SOCK\");", " if (!auth_socket)\n return; /* ssh agent not present */", " if (!g_file_test (auth_socket, G_FILE_TEST_EXISTS))\n {\n /* Let's clean it up, so that the application will not try to connect */\n flatpak_bwrap_unset_env (bwrap, \"SSH_AUTH_SOCK\");\n return;\n }", " sandbox_auth_socket = g_strdup_printf (\"/run/user/%d/ssh-auth\", getuid ());", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", auth_socket, sandbox_auth_socket,\n NULL);\n flatpak_bwrap_set_env (bwrap, \"SSH_AUTH_SOCK\", sandbox_auth_socket, TRUE);\n}", "static void\nflatpak_run_add_pcsc_args (FlatpakBwrap *bwrap)\n{\n const char * pcsc_socket;\n const char * sandbox_pcsc_socket = \"/run/pcscd/pcscd.comm\";", " pcsc_socket = g_getenv (\"PCSCLITE_CSOCK_NAME\");\n if (pcsc_socket)\n {\n if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_unset_env (bwrap, \"PCSCLITE_CSOCK_NAME\");\n return;\n }\n }\n else\n {\n pcsc_socket = \"/run/pcscd/pcscd.comm\";\n if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))\n return;\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pcsc_socket, sandbox_pcsc_socket,\n NULL);\n flatpak_bwrap_set_env (bwrap, \"PCSCLITE_CSOCK_NAME\", sandbox_pcsc_socket, TRUE);\n}", "static gboolean\nflatpak_run_cups_check_server_is_socket (const char *server)\n{\n if (g_str_has_prefix (server, \"/\") && strstr (server, \":\") == NULL)\n return TRUE;", " return FALSE;\n}", "/* Try to find a default server from a cups confguration file */\nstatic char *\nflatpak_run_get_cups_server_name_config (const char *path)\n{\n g_autoptr(GFile) file = g_file_new_for_path (path);\n g_autoptr(GError) my_error = NULL;\n g_autoptr(GFileInputStream) input_stream = NULL;\n g_autoptr(GDataInputStream) data_stream = NULL;\n size_t len;", " input_stream = g_file_read (file, NULL, &my_error);\n if (my_error)\n {\n g_debug (\"CUPS configuration file '%s': %s\", path, my_error->message);\n return NULL;\n }", " data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));", " while (TRUE)\n {\n g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);\n if (line == NULL)\n break;", " g_strchug (line);", " if ((*line == '\\0') || (*line == '#'))\n continue;", " g_auto(GStrv) tokens = g_strsplit (line, \" \", 2);", " if ((tokens[0] != NULL) && (tokens[1] != NULL))\n {\n if (strcmp (\"ServerName\", tokens[0]) == 0)\n {\n g_strchug (tokens[1]);", " if (flatpak_run_cups_check_server_is_socket (tokens[1]))\n return g_strdup (tokens[1]);\n }\n }\n }", " return NULL;\n}", "static char *\nflatpak_run_get_cups_server_name (void)\n{\n g_autofree char * cups_server = NULL;\n g_autofree char * cups_config_path = NULL;", " /* TODO\n * we don't currently support cups servers located on the network, if such\n * server is detected, we simply ignore it and in the worst case we fallback\n * to the default socket\n */\n cups_server = g_strdup (g_getenv (\"CUPS_SERVER\"));\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);\n g_clear_pointer (&cups_server, g_free);", " cups_config_path = g_build_filename (g_get_home_dir (), \".cups/client.conf\", NULL);\n cups_server = flatpak_run_get_cups_server_name_config (cups_config_path);\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);\n g_clear_pointer (&cups_server, g_free);", " cups_server = flatpak_run_get_cups_server_name_config (\"/etc/cups/client.conf\");\n if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))\n return g_steal_pointer (&cups_server);", " // Fallback to default socket\n return g_strdup (\"/var/run/cups/cups.sock\");\n}", "static void\nflatpak_run_add_cups_args (FlatpakBwrap *bwrap)\n{\n g_autofree char * sandbox_server_name = g_strdup (\"/var/run/cups/cups.sock\");\n g_autofree char * cups_server_name = flatpak_run_get_cups_server_name ();", " if (!g_file_test (cups_server_name, G_FILE_TEST_EXISTS))\n {\n g_debug (\"Could not find CUPS server\");\n return;\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", cups_server_name, sandbox_server_name,\n NULL);\n}", "/* Try to find a default server from a pulseaudio confguration file */\nstatic char *\nflatpak_run_get_pulseaudio_server_user_config (const char *path)\n{\n g_autoptr(GFile) file = g_file_new_for_path (path);\n g_autoptr(GError) my_error = NULL;\n g_autoptr(GFileInputStream) input_stream = NULL;\n g_autoptr(GDataInputStream) data_stream = NULL;\n size_t len;", " input_stream = g_file_read (file, NULL, &my_error);\n if (my_error)\n {\n g_debug (\"Pulseaudio user configuration file '%s': %s\", path, my_error->message);\n return NULL;\n }", " data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));", " while (TRUE)\n {\n g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);\n if (line == NULL)\n break;", " g_strchug (line);", " if ((*line == '\\0') || (*line == ';') || (*line == '#'))\n continue;", " if (g_str_has_prefix (line, \".include \"))\n {\n g_autofree char *rec_path = g_strdup (line + 9);\n g_strstrip (rec_path);\n char *found = flatpak_run_get_pulseaudio_server_user_config (rec_path);\n if (found)\n return found;\n }\n else if (g_str_has_prefix (line, \"[\"))\n {\n return NULL;\n }\n else\n {\n g_auto(GStrv) tokens = g_strsplit (line, \"=\", 2);", " if ((tokens[0] != NULL) && (tokens[1] != NULL))\n {\n g_strchomp (tokens[0]);\n if (strcmp (\"default-server\", tokens[0]) == 0)\n {\n g_strstrip (tokens[1]);\n g_debug (\"Found pulseaudio socket from configuration file '%s': %s\", path, tokens[1]);\n return g_strdup (tokens[1]);\n }\n }\n }\n }", " return NULL;\n}", "static char *\nflatpak_run_get_pulseaudio_server (void)\n{\n const char * pulse_clientconfig;\n char *pulse_server;\n g_autofree char *pulse_user_config = NULL;", " pulse_server = g_strdup (g_getenv (\"PULSE_SERVER\"));\n if (pulse_server)\n return pulse_server;", " pulse_clientconfig = g_getenv (\"PULSE_CLIENTCONFIG\");\n if (pulse_clientconfig)\n return flatpak_run_get_pulseaudio_server_user_config (pulse_clientconfig);", " pulse_user_config = g_build_filename (g_get_user_config_dir (), \"pulse/client.conf\", NULL);\n pulse_server = flatpak_run_get_pulseaudio_server_user_config (pulse_user_config);\n if (pulse_server)\n return pulse_server;", " pulse_server = flatpak_run_get_pulseaudio_server_user_config (\"/etc/pulse/client.conf\");\n if (pulse_server)\n return pulse_server;", " return NULL;\n}", "static char *\nflatpak_run_parse_pulse_server (const char *value)\n{\n g_auto(GStrv) servers = g_strsplit (value, \" \", 0);\n gsize i;", " for (i = 0; servers[i] != NULL; i++)\n {\n const char *server = servers[i];\n if (g_str_has_prefix (server, \"{\"))\n {\n const char * closing = strstr (server, \"}\");\n if (closing == NULL)\n continue;\n server = closing + 1;\n }\n if (g_str_has_prefix (server, \"unix:\"))\n return g_strdup (server + 5);\n }", " return NULL;\n}", "/*\n * Get the machine ID as used by PulseAudio. This is the systemd/D-Bus\n * machine ID, or failing that, the hostname.\n */\nstatic char *\nflatpak_run_get_pulse_machine_id (void)\n{\n static const char * const machine_ids[] =\n {\n \"/etc/machine-id\",\n \"/var/lib/dbus/machine-id\",\n };\n gsize i;", " for (i = 0; i < G_N_ELEMENTS (machine_ids); i++)\n {\n g_autofree char *ret = NULL;", " if (g_file_get_contents (machine_ids[i], &ret, NULL, NULL))\n {\n gsize j;", " g_strstrip (ret);", " for (j = 0; ret[j] != '\\0'; j++)\n {\n if (!g_ascii_isxdigit (ret[j]))\n break;\n }", " if (ret[0] != '\\0' && ret[j] == '\\0')\n return g_steal_pointer (&ret);\n }\n }", " return g_strdup (g_get_host_name ());\n}", "/*\n * Get the directory used by PulseAudio for its configuration.\n */\nstatic char *\nflatpak_run_get_pulse_home (void)\n{\n /* Legacy path ~/.pulse is tried first, for compatibility */\n {\n const char *parent = g_get_home_dir ();\n g_autofree char *ret = g_build_filename (parent, \".pulse\", NULL);", " if (g_file_test (ret, G_FILE_TEST_IS_DIR))\n return g_steal_pointer (&ret);\n }", " /* The more modern path, usually ~/.config/pulse */\n {\n const char *parent = g_get_user_config_dir ();\n /* Usually ~/.config/pulse */\n g_autofree char *ret = g_build_filename (parent, \"pulse\", NULL);", " if (g_file_test (ret, G_FILE_TEST_IS_DIR))\n return g_steal_pointer (&ret);\n }", " return NULL;\n}", "/*\n * Get the runtime directory used by PulseAudio for its socket.\n */\nstatic char *\nflatpak_run_get_pulse_runtime_dir (void)\n{\n const char *val = NULL;", " val = g_getenv (\"PULSE_RUNTIME_PATH\");", " if (val != NULL)\n return realpath (val, NULL);", " {\n const char *user_runtime_dir = g_get_user_runtime_dir ();", " if (user_runtime_dir != NULL)\n {\n g_autofree char *dir = g_build_filename (user_runtime_dir, \"pulse\", NULL);", " if (g_file_test (dir, G_FILE_TEST_IS_DIR))\n return realpath (dir, NULL);\n }\n }", " {\n g_autofree char *pulse_home = flatpak_run_get_pulse_home ();\n g_autofree char *machine_id = flatpak_run_get_pulse_machine_id ();", " if (pulse_home != NULL && machine_id != NULL)\n {\n /* This is usually a symlink, but we take its realpath() anyway */\n g_autofree char *dir = g_strdup_printf (\"%s/%s-runtime\", pulse_home, machine_id);", " if (g_file_test (dir, G_FILE_TEST_IS_DIR))\n return realpath (dir, NULL);\n }\n }", " return NULL;\n}", "static void\nflatpak_run_add_pulseaudio_args (FlatpakBwrap *bwrap)\n{\n g_autofree char *pulseaudio_server = flatpak_run_get_pulseaudio_server ();\n g_autofree char *pulseaudio_socket = NULL;\n g_autofree char *pulse_runtime_dir = flatpak_run_get_pulse_runtime_dir ();", " if (pulseaudio_server)\n pulseaudio_socket = flatpak_run_parse_pulse_server (pulseaudio_server);", " if (!pulseaudio_socket)\n {\n pulseaudio_socket = g_build_filename (pulse_runtime_dir, \"native\", NULL);", " if (!g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n g_clear_pointer (&pulseaudio_socket, g_free);\n }", " if (!pulseaudio_socket)\n {\n pulseaudio_socket = realpath (\"/var/run/pulse/native\", NULL);", " if (pulseaudio_socket && !g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n g_clear_pointer (&pulseaudio_socket, g_free);\n }", " flatpak_bwrap_unset_env (bwrap, \"PULSE_SERVER\");", " if (pulseaudio_socket && g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))\n {\n gboolean share_shm = FALSE; /* TODO: When do we add this? */\n g_autofree char *client_config = g_strdup_printf (\"enable-shm=%s\\n\", share_shm ? \"yes\" : \"no\");\n g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/pulse/native\", getuid ());\n g_autofree char *pulse_server = g_strdup_printf (\"unix:/run/user/%d/pulse/native\", getuid ());\n g_autofree char *config_path = g_strdup_printf (\"/run/user/%d/pulse/config\", getuid ());", " /* FIXME - error handling */\n if (!flatpak_bwrap_add_args_data (bwrap, \"pulseaudio\", client_config, -1, config_path, NULL))\n return;", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pulseaudio_socket, sandbox_socket_path,\n NULL);", " flatpak_bwrap_set_env (bwrap, \"PULSE_SERVER\", pulse_server, TRUE);\n flatpak_bwrap_set_env (bwrap, \"PULSE_CLIENTCONFIG\", config_path, TRUE);\n }\n else\n g_debug (\"Could not find pulseaudio socket\");", " /* Also allow ALSA access. This was added in 1.8, and is not ideally named. However,\n * since the practical permission of ALSA and PulseAudio are essentially the same, and\n * since we don't want to add more permissions for something we plan to replace with\n * portals/pipewire going forward we reinterpret pulseaudio to also mean ALSA.\n */\n if (g_file_test (\"/dev/snd\", G_FILE_TEST_IS_DIR))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", \"/dev/snd\", \"/dev/snd\", NULL);\n}", "static void\nflatpak_run_add_resolved_args (FlatpakBwrap *bwrap)\n{\n const char *resolved_socket = \"/run/systemd/resolve/io.systemd.Resolve\";", " if (g_file_test (resolved_socket, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--bind\", resolved_socket, resolved_socket, NULL);\n}", "static void\nflatpak_run_add_journal_args (FlatpakBwrap *bwrap)\n{\n g_autofree char *journal_socket_socket = g_strdup (\"/run/systemd/journal/socket\");\n g_autofree char *journal_stdout_socket = g_strdup (\"/run/systemd/journal/stdout\");", " if (g_file_test (journal_socket_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", journal_socket_socket, journal_socket_socket,\n NULL);\n }\n if (g_file_test (journal_stdout_socket, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", journal_stdout_socket, journal_stdout_socket,\n NULL);\n }\n}", "static char *\ncreate_proxy_socket (char *template)\n{\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, \".dbus-proxy\", NULL);\n g_autofree char *proxy_socket = g_build_filename (proxy_socket_dir, template, NULL);\n int fd;", " if (!glnx_shutil_mkdir_p_at (AT_FDCWD, proxy_socket_dir, 0755, NULL, NULL))\n return NULL;", " fd = g_mkstemp (proxy_socket);\n if (fd == -1)\n return NULL;", " close (fd);", " return g_steal_pointer (&proxy_socket);\n}", "static gboolean\nflatpak_run_add_system_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags)\n{\n gboolean unrestricted, no_proxy;\n const char *dbus_address = g_getenv (\"DBUS_SYSTEM_BUS_ADDRESS\");\n g_autofree char *real_dbus_address = NULL;\n g_autofree char *dbus_system_socket = NULL;", " unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) != 0;\n if (unrestricted)\n g_debug (\"Allowing system-dbus access\");", " no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY) != 0;", " if (dbus_address != NULL)\n dbus_system_socket = extract_unix_path_from_dbus_address (dbus_address);\n else if (g_file_test (\"/var/run/dbus/system_bus_socket\", G_FILE_TEST_EXISTS))\n dbus_system_socket = g_strdup (\"/var/run/dbus/system_bus_socket\");", " if (dbus_system_socket != NULL && unrestricted)\n {\n flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", dbus_system_socket, \"/run/dbus/system_bus_socket\",\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SYSTEM_BUS_ADDRESS\", \"unix:path=/run/dbus/system_bus_socket\", TRUE);", " return TRUE;\n }\n else if (!no_proxy && flatpak_context_get_needs_system_bus_proxy (context))\n {\n g_autofree char *proxy_socket = create_proxy_socket (\"system-bus-proxy-XXXXXX\");", " if (proxy_socket == NULL)\n return FALSE;", " if (dbus_address)\n real_dbus_address = g_strdup (dbus_address);\n else\n real_dbus_address = g_strdup_printf (\"unix:path=%s\", dbus_system_socket);", " flatpak_bwrap_add_args (proxy_arg_bwrap, real_dbus_address, proxy_socket, NULL);", " if (!unrestricted)\n flatpak_context_add_bus_filters (context, NULL, FALSE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);", " if ((flags & FLATPAK_RUN_FLAG_LOG_SYSTEM_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, \"/run/dbus/system_bus_socket\",\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SYSTEM_BUS_ADDRESS\", \"unix:path=/run/dbus/system_bus_socket\", TRUE);", " return TRUE;\n }\n return FALSE;\n}", "static gboolean\nflatpak_run_add_session_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags,\n const char *app_id)\n{\n gboolean unrestricted, no_proxy;\n const char *dbus_address = g_getenv (\"DBUS_SESSION_BUS_ADDRESS\");\n g_autofree char *dbus_session_socket = NULL;\n g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/bus\", getuid ());\n g_autofree char *sandbox_dbus_address = g_strdup_printf (\"unix:path=/run/user/%d/bus\", getuid ());", " unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) != 0;", " if (dbus_address != NULL)\n {\n dbus_session_socket = extract_unix_path_from_dbus_address (dbus_address);\n }\n else\n {\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n struct stat statbuf;", " dbus_session_socket = g_build_filename (user_runtime_dir, \"bus\", NULL);", " if (stat (dbus_session_socket, &statbuf) < 0\n || (statbuf.st_mode & S_IFMT) != S_IFSOCK\n || statbuf.st_uid != getuid ())\n return FALSE;\n }", " if (unrestricted)\n g_debug (\"Allowing session-dbus access\");", " no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY) != 0;", " if (dbus_session_socket != NULL && unrestricted)\n {\n flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", dbus_session_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SESSION_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n }\n else if (!no_proxy && dbus_address != NULL)\n {\n g_autofree char *proxy_socket = create_proxy_socket (\"session-bus-proxy-XXXXXX\");", " if (proxy_socket == NULL)\n return FALSE;", " flatpak_bwrap_add_args (proxy_arg_bwrap, dbus_address, proxy_socket, NULL);", " if (!unrestricted)\n {\n flatpak_context_add_bus_filters (context, app_id, TRUE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);", " /* Allow calling any interface+method on all portals, but only receive broadcasts under /org/desktop/portal */\n flatpak_bwrap_add_arg (proxy_arg_bwrap,\n \"--call=org.freedesktop.portal.*=*\");\n flatpak_bwrap_add_arg (proxy_arg_bwrap,\n \"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*\");\n }", " if ((flags & FLATPAK_RUN_FLAG_LOG_SESSION_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"DBUS_SESSION_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n }", " return FALSE;\n}", "static gboolean\nflatpak_run_add_a11y_dbus_args (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n FlatpakContext *context,\n FlatpakRunFlags flags)\n{\n g_autoptr(GDBusConnection) session_bus = NULL;\n g_autofree char *a11y_address = NULL;\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDBusMessage) reply = NULL;\n g_autoptr(GDBusMessage) msg = NULL;\n g_autofree char *proxy_socket = NULL;", " if ((flags & FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY) != 0)\n return FALSE;", " session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);\n if (session_bus == NULL)\n return FALSE;", " msg = g_dbus_message_new_method_call (\"org.a11y.Bus\", \"/org/a11y/bus\", \"org.a11y.Bus\", \"GetAddress\");\n g_dbus_message_set_body (msg, g_variant_new (\"()\"));\n reply =\n g_dbus_connection_send_message_with_reply_sync (session_bus, msg,\n G_DBUS_SEND_MESSAGE_FLAGS_NONE,\n 30000,\n NULL,\n NULL,\n NULL);\n if (reply)\n {\n if (g_dbus_message_to_gerror (reply, &local_error))\n {\n if (!g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))\n g_message (\"Can't find a11y bus: %s\", local_error->message);\n }\n else\n {\n g_variant_get (g_dbus_message_get_body (reply),\n \"(s)\", &a11y_address);\n }\n }", " if (!a11y_address)\n return FALSE;", " proxy_socket = create_proxy_socket (\"a11y-bus-proxy-XXXXXX\");\n if (proxy_socket == NULL)\n return FALSE;", " g_autofree char *sandbox_socket_path = g_strdup_printf (\"/run/user/%d/at-spi-bus\", getuid ());\n g_autofree char *sandbox_dbus_address = g_strdup_printf (\"unix:path=/run/user/%d/at-spi-bus\", getuid ());", " flatpak_bwrap_add_args (proxy_arg_bwrap,\n a11y_address,\n proxy_socket, \"--filter\", \"--sloppy-names\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Embed@/org/a11y/atspi/accessible/root\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Unembed@/org/a11y/atspi/accessible/root\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.Registry.GetRegisteredEvents@/org/a11y/atspi/registry\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetKeystrokeListeners@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetDeviceEventListeners@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersSync@/org/a11y/atspi/registry/deviceeventcontroller\",\n \"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersAsync@/org/a11y/atspi/registry/deviceeventcontroller\",\n NULL);", " if ((flags & FLATPAK_RUN_FLAG_LOG_A11Y_BUS) != 0)\n flatpak_bwrap_add_args (proxy_arg_bwrap, \"--log\", NULL);", " flatpak_bwrap_add_args (app_bwrap,\n \"--ro-bind\", proxy_socket, sandbox_socket_path,\n NULL);\n flatpak_bwrap_set_env (app_bwrap, \"AT_SPI_BUS_ADDRESS\", sandbox_dbus_address, TRUE);", " return TRUE;\n}", "/* This wraps the argv in a bwrap call, primary to allow the\n command to be run with a proper /.flatpak-info with data\n taken from app_info_path */\nstatic gboolean\nadd_bwrap_wrapper (FlatpakBwrap *bwrap,\n const char *app_info_path,\n GError **error)\n{\n glnx_autofd int app_info_fd = -1;\n g_auto(GLnxDirFdIterator) dir_iter = { 0 };\n struct dirent *dent;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, \".dbus-proxy/\", NULL);", " app_info_fd = open (app_info_path, O_RDONLY | O_CLOEXEC);\n if (app_info_fd == -1)\n return glnx_throw_errno_prefix (error, _(\"Failed to open app info file\"));", " if (!glnx_dirfd_iterator_init_at (AT_FDCWD, \"/\", FALSE, &dir_iter, error))\n return FALSE;", " flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());", " while (TRUE)\n {\n glnx_autofd int o_path_fd = -1;\n struct statfs stfs;", " if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dir_iter, &dent, NULL, error))\n return FALSE;", " if (dent == NULL)\n break;", " if (strcmp (dent->d_name, \".flatpak-info\") == 0)\n continue;", " /* O_PATH + fstatfs is the magic that we need to statfs without automounting the target */\n o_path_fd = openat (dir_iter.fd, dent->d_name, O_PATH | O_NOFOLLOW | O_CLOEXEC);\n if (o_path_fd == -1 || fstatfs (o_path_fd, &stfs) != 0 || stfs.f_type == AUTOFS_SUPER_MAGIC)\n continue; /* AUTOFS mounts are risky and can cause us to block (see issue #1633), so ignore it. Its unlikely the proxy needs such a directory. */", " if (dent->d_type == DT_DIR)\n {\n if (strcmp (dent->d_name, \"tmp\") == 0 ||\n strcmp (dent->d_name, \"var\") == 0 ||\n strcmp (dent->d_name, \"run\") == 0)\n flatpak_bwrap_add_arg (bwrap, \"--bind\");\n else\n flatpak_bwrap_add_arg (bwrap, \"--ro-bind\");", " flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n }\n else if (dent->d_type == DT_LNK)\n {\n g_autofree gchar *target = NULL;", " target = glnx_readlinkat_malloc (dir_iter.fd, dent->d_name,\n NULL, error);\n if (target == NULL)\n return FALSE;\n flatpak_bwrap_add_args (bwrap, \"--symlink\", target, NULL);\n flatpak_bwrap_add_arg_printf (bwrap, \"/%s\", dent->d_name);\n }\n }", " flatpak_bwrap_add_args (bwrap, \"--bind\", proxy_socket_dir, proxy_socket_dir, NULL);", " /* This is a file rather than a bind mount, because it will then\n not be unmounted from the namespace when the namespace dies. */\n flatpak_bwrap_add_args_data_fd (bwrap, \"--file\", glnx_steal_fd (&app_info_fd), \"/.flatpak-info\");", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return FALSE;", " return TRUE;\n}", "static gboolean\nstart_dbus_proxy (FlatpakBwrap *app_bwrap,\n FlatpakBwrap *proxy_arg_bwrap,\n const char *app_info_path,\n GError **error)\n{\n char x = 'x';\n const char *proxy;\n g_autofree char *commandline = NULL;\n g_autoptr(FlatpakBwrap) proxy_bwrap = NULL;\n int sync_fds[2] = {-1, -1};\n int proxy_start_index;\n g_auto(GStrv) minimal_envp = NULL;", " minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);\n proxy_bwrap = flatpak_bwrap_new (NULL);", " if (!add_bwrap_wrapper (proxy_bwrap, app_info_path, error))\n return FALSE;", " proxy = g_getenv (\"FLATPAK_DBUSPROXY\");\n if (proxy == NULL)\n proxy = DBUSPROXY;", " flatpak_bwrap_add_arg (proxy_bwrap, proxy);", " proxy_start_index = proxy_bwrap->argv->len;", " if (pipe2 (sync_fds, O_CLOEXEC) < 0)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Unable to create sync pipe\"));\n return FALSE;\n }", " /* read end goes to app */\n flatpak_bwrap_add_args_data_fd (app_bwrap, \"--sync-fd\", sync_fds[0], NULL);", " /* write end goes to proxy */\n flatpak_bwrap_add_fd (proxy_bwrap, sync_fds[1]);\n flatpak_bwrap_add_arg_printf (proxy_bwrap, \"--fd=%d\", sync_fds[1]);", " /* Note: This steals the fds from proxy_arg_bwrap */\n flatpak_bwrap_append_bwrap (proxy_bwrap, proxy_arg_bwrap);", " if (!flatpak_bwrap_bundle_args (proxy_bwrap, proxy_start_index, -1, TRUE, error))\n return FALSE;", " flatpak_bwrap_finish (proxy_bwrap);", " commandline = flatpak_quote_argv ((const char **) proxy_bwrap->argv->pdata, -1);\n g_debug (\"Running '%s'\", commandline);", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async (NULL,\n (char **) proxy_bwrap->argv->pdata,\n NULL,\n G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n flatpak_bwrap_child_setup_cb, proxy_bwrap->fds,\n NULL, error))\n return FALSE;", " /* The write end can be closed now, otherwise the read below will hang of xdg-dbus-proxy\n fails to start. */\n g_clear_pointer (&proxy_bwrap, flatpak_bwrap_free);", " /* Sync with proxy, i.e. wait until its listening on the sockets */\n if (read (sync_fds[0], &x, 1) != 1)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Failed to sync with dbus proxy\"));\n return FALSE;\n }", " return TRUE;\n}", "static int\nflatpak_extension_compare_by_path (gconstpointer _a,\n gconstpointer _b)\n{\n const FlatpakExtension *a = _a;\n const FlatpakExtension *b = _b;", " return g_strcmp0 (a->directory, b->directory);\n}", "gboolean\nflatpak_run_add_extension_args (FlatpakBwrap *bwrap,\n GKeyFile *metakey,\n FlatpakDecomposed *ref,\n gboolean use_ld_so_cache,\n char **extensions_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GString) used_extensions = g_string_new (\"\");\n GList *extensions, *path_sorted_extensions, *l;\n g_autoptr(GString) ld_library_path = g_string_new (\"\");\n int count = 0;\n g_autoptr(GHashTable) mounted_tmpfs =\n g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n g_autoptr(GHashTable) created_symlink =\n g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n g_autofree char *arch = flatpak_decomposed_dup_arch (ref);\n const char *branch = flatpak_decomposed_get_branch (ref);\n gboolean is_app = flatpak_decomposed_is_app (ref);", " extensions = flatpak_list_extensions (metakey, arch, branch);", " /* First we apply all the bindings, they are sorted alphabetically in order for parent directory\n to be mounted before child directories */\n path_sorted_extensions = g_list_copy (extensions);\n path_sorted_extensions = g_list_sort (path_sorted_extensions, flatpak_extension_compare_by_path);", " for (l = path_sorted_extensions; l != NULL; l = l->next)\n {\n FlatpakExtension *ext = l->data;\n g_autofree char *directory = g_build_filename (is_app ? \"/app\" : \"/usr\", ext->directory, NULL);\n g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);\n g_autofree char *ref_file = g_build_filename (full_directory, \".ref\", NULL);\n g_autofree char *real_ref = g_build_filename (ext->files_path, ext->directory, \".ref\", NULL);", " if (ext->needs_tmpfs)\n {\n g_autofree char *parent = g_path_get_dirname (directory);", " if (g_hash_table_lookup (mounted_tmpfs, parent) == NULL)\n {\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", parent,\n NULL);\n g_hash_table_insert (mounted_tmpfs, g_steal_pointer (&parent), \"mounted\");\n }\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", ext->files_path, full_directory,\n NULL);", " if (g_file_test (real_ref, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--lock-file\", ref_file,\n NULL);\n }", " g_list_free (path_sorted_extensions);", " /* Then apply library directories and file merging, in extension prio order */", " for (l = extensions; l != NULL; l = l->next)\n {\n FlatpakExtension *ext = l->data;\n g_autofree char *directory = g_build_filename (is_app ? \"/app\" : \"/usr\", ext->directory, NULL);\n g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);\n int i;", " if (used_extensions->len > 0)\n g_string_append (used_extensions, \";\");\n g_string_append (used_extensions, ext->installed_id);\n g_string_append (used_extensions, \"=\");\n if (ext->commit != NULL)\n g_string_append (used_extensions, ext->commit);\n else\n g_string_append (used_extensions, \"local\");", " if (ext->add_ld_path)\n {\n g_autofree char *ld_path = g_build_filename (full_directory, ext->add_ld_path, NULL);", " if (use_ld_so_cache)\n {\n g_autofree char *contents = g_strconcat (ld_path, \"\\n\", NULL);\n /* We prepend app or runtime and a counter in order to get the include order correct for the conf files */\n g_autofree char *ld_so_conf_file = g_strdup_printf (\"%s-%03d-%s.conf\", flatpak_decomposed_get_kind_str (ref), ++count, ext->installed_id);\n g_autofree char *ld_so_conf_file_path = g_build_filename (\"/run/flatpak/ld.so.conf.d\", ld_so_conf_file, NULL);", " if (!flatpak_bwrap_add_args_data (bwrap, \"ld-so-conf\",\n contents, -1, ld_so_conf_file_path, error))\n return FALSE;\n }\n else\n {\n if (ld_library_path->len != 0)\n g_string_append (ld_library_path, \":\");\n g_string_append (ld_library_path, ld_path);\n }\n }", " for (i = 0; ext->merge_dirs != NULL && ext->merge_dirs[i] != NULL; i++)\n {\n g_autofree char *parent = g_path_get_dirname (directory);\n g_autofree char *merge_dir = g_build_filename (parent, ext->merge_dirs[i], NULL);\n g_autofree char *source_dir = g_build_filename (ext->files_path, ext->merge_dirs[i], NULL);\n g_auto(GLnxDirFdIterator) source_iter = { 0 };\n struct dirent *dent;", " if (glnx_dirfd_iterator_init_at (AT_FDCWD, source_dir, TRUE, &source_iter, NULL))\n {\n while (glnx_dirfd_iterator_next_dent (&source_iter, &dent, NULL, NULL) && dent != NULL)\n {\n g_autofree char *symlink_path = g_build_filename (merge_dir, dent->d_name, NULL);\n /* Only create the first, because extensions are listed in prio order */\n if (g_hash_table_lookup (created_symlink, symlink_path) == NULL)\n {\n g_autofree char *symlink = g_build_filename (directory, ext->merge_dirs[i], dent->d_name, NULL);\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", symlink, symlink_path,\n NULL);\n g_hash_table_insert (created_symlink, g_steal_pointer (&symlink_path), \"created\");\n }\n }\n }\n }\n }", " g_list_free_full (extensions, (GDestroyNotify) flatpak_extension_free);", " if (ld_library_path->len != 0)\n {\n const gchar *old_ld_path = g_environ_getenv (bwrap->envp, \"LD_LIBRARY_PATH\");", " if (old_ld_path != NULL && *old_ld_path != 0)\n {\n if (is_app)\n {\n g_string_append (ld_library_path, \":\");\n g_string_append (ld_library_path, old_ld_path);\n }\n else\n {\n g_string_prepend (ld_library_path, \":\");\n g_string_prepend (ld_library_path, old_ld_path);\n }\n }", " flatpak_bwrap_set_env (bwrap, \"LD_LIBRARY_PATH\", ld_library_path->str, TRUE);\n }", " if (extensions_out)\n *extensions_out = g_string_free (g_steal_pointer (&used_extensions), FALSE);", " return TRUE;\n}", "gboolean\nflatpak_run_add_environment_args (FlatpakBwrap *bwrap,\n const char *app_info_path,\n FlatpakRunFlags flags,\n const char *app_id,\n FlatpakContext *context,\n GFile *app_id_dir,\n GPtrArray *previous_app_id_dirs,\n FlatpakExports **exports_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GError) my_error = NULL;\n g_autoptr(FlatpakExports) exports = NULL;\n g_autoptr(FlatpakBwrap) proxy_arg_bwrap = flatpak_bwrap_new (flatpak_bwrap_empty_env);\n gboolean has_wayland = FALSE;\n gboolean allow_x11 = FALSE;", " if ((context->shares & FLATPAK_CONTEXT_SHARED_IPC) == 0)\n {\n g_debug (\"Disallowing ipc access\");\n flatpak_bwrap_add_args (bwrap, \"--unshare-ipc\", NULL);\n }", " if ((context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) == 0)\n {\n g_debug (\"Disallowing network access\");\n flatpak_bwrap_add_args (bwrap, \"--unshare-net\", NULL);\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_ALL)\n {\n flatpak_bwrap_add_args (bwrap,\n \"--dev-bind\", \"/dev\", \"/dev\",\n NULL);\n /* Don't expose the host /dev/shm, just the device nodes, unless explicitly allowed */\n if (g_file_test (\"/dev/shm\", G_FILE_TEST_IS_DIR))\n {\n if ((context->devices & FLATPAK_CONTEXT_DEVICE_SHM) == 0)\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/dev/shm\",\n NULL);\n }\n else if (g_file_test (\"/dev/shm\", G_FILE_TEST_IS_SYMLINK))\n {\n g_autofree char *link = flatpak_readlink (\"/dev/shm\", NULL);", " /* On debian (with sysv init) the host /dev/shm is a symlink to /run/shm, so we can't\n mount on top of it. */\n if (g_strcmp0 (link, \"/run/shm\") == 0)\n {\n if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM &&\n g_file_test (\"/run/shm\", G_FILE_TEST_IS_DIR))\n flatpak_bwrap_add_args (bwrap,\n \"--bind\", \"/run/shm\", \"/run/shm\",\n NULL);\n else\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/run/shm\",\n NULL);\n }\n else\n g_warning (\"Unexpected /dev/shm symlink %s\", link);\n }\n }\n else\n {\n flatpak_bwrap_add_args (bwrap,\n \"--dev\", \"/dev\",\n NULL);\n if (context->devices & FLATPAK_CONTEXT_DEVICE_DRI)\n {\n g_debug (\"Allowing dri access\");\n int i;\n char *dri_devices[] = {\n \"/dev/dri\",\n /* mali */\n \"/dev/mali\",\n \"/dev/mali0\",\n \"/dev/umplock\",\n /* nvidia */\n \"/dev/nvidiactl\",\n \"/dev/nvidia-modeset\",\n /* nvidia OpenCL/CUDA */\n \"/dev/nvidia-uvm\",\n \"/dev/nvidia-uvm-tools\",\n };", " for (i = 0; i < G_N_ELEMENTS (dri_devices); i++)\n {\n if (g_file_test (dri_devices[i], G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", dri_devices[i], dri_devices[i], NULL);\n }", " /* Each Nvidia card gets its own device.\n This is a fairly arbitrary limit but ASUS sells mining boards supporting 20 in theory. */\n char nvidia_dev[14]; /* /dev/nvidia plus up to 2 digits */\n for (i = 0; i < 20; i++)\n {\n g_snprintf (nvidia_dev, sizeof (nvidia_dev), \"/dev/nvidia%d\", i);\n if (g_file_test (nvidia_dev, G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", nvidia_dev, nvidia_dev, NULL);\n }\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_KVM)\n {\n g_debug (\"Allowing kvm access\");\n if (g_file_test (\"/dev/kvm\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--dev-bind\", \"/dev/kvm\", \"/dev/kvm\", NULL);\n }", " if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM)\n {\n /* This is a symlink to /run/shm on debian, so bind to real target */\n g_autofree char *real_dev_shm = realpath (\"/dev/shm\", NULL);", " g_debug (\"Allowing /dev/shm access (as %s)\", real_dev_shm);\n if (real_dev_shm != NULL)\n flatpak_bwrap_add_args (bwrap, \"--bind\", real_dev_shm, \"/dev/shm\", NULL);\n }\n }", " flatpak_context_append_bwrap_filesystem (context, bwrap, app_id, app_id_dir, previous_app_id_dirs, &exports);", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_WAYLAND)\n {\n g_debug (\"Allowing wayland access\");\n has_wayland = flatpak_run_add_wayland_args (bwrap);\n }", " if ((context->sockets & FLATPAK_CONTEXT_SOCKET_FALLBACK_X11) != 0)\n allow_x11 = !has_wayland;\n else\n allow_x11 = (context->sockets & FLATPAK_CONTEXT_SOCKET_X11) != 0;", " flatpak_run_add_x11_args (bwrap, allow_x11);", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_SSH_AUTH)\n {\n flatpak_run_add_ssh_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_PULSEAUDIO)\n {\n g_debug (\"Allowing pulseaudio access\");\n flatpak_run_add_pulseaudio_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_PCSC)\n {\n flatpak_run_add_pcsc_args (bwrap);\n }", " if (context->sockets & FLATPAK_CONTEXT_SOCKET_CUPS)\n {\n flatpak_run_add_cups_args (bwrap);\n }", " flatpak_run_add_session_dbus_args (bwrap, proxy_arg_bwrap, context, flags, app_id);\n flatpak_run_add_system_dbus_args (bwrap, proxy_arg_bwrap, context, flags);\n flatpak_run_add_a11y_dbus_args (bwrap, proxy_arg_bwrap, context, flags);", "", "\n /* Must run this before spawning the dbus proxy, to ensure it\n ends up in the app cgroup */\n if (!flatpak_run_in_transient_unit (app_id, &my_error))\n {\n /* We still run along even if we don't get a cgroup, as nothing\n really depends on it. Its just nice to have */\n g_debug (\"Failed to run in transient scope: %s\", my_error->message);\n g_clear_error (&my_error);\n }", " if (!flatpak_bwrap_is_empty (proxy_arg_bwrap) &&\n !start_dbus_proxy (bwrap, proxy_arg_bwrap, app_info_path, error))\n return FALSE;", " if (exports_out)\n *exports_out = g_steal_pointer (&exports);", " return TRUE;\n}", "typedef struct\n{\n const char *env;\n const char *val;\n} ExportData;", "static const ExportData default_exports[] = {\n {\"PATH\", \"/app/bin:/usr/bin\"},\n /* We always want to unset LD_LIBRARY_PATH to avoid inheriting weird\n * dependencies from the host. But if not using ld.so.cache this is\n * later set. */\n {\"LD_LIBRARY_PATH\", NULL},\n {\"XDG_CONFIG_DIRS\", \"/app/etc/xdg:/etc/xdg\"},\n {\"XDG_DATA_DIRS\", \"/app/share:/usr/share\"},\n {\"SHELL\", \"/bin/sh\"},\n {\"TMPDIR\", NULL}, /* Unset TMPDIR as it may not exist in the sandbox */", " /* Some env vars are common enough and will affect the sandbox badly\n if set on the host. We clear these always. */\n {\"PYTHONPATH\", NULL},\n {\"PERLLIB\", NULL},\n {\"PERL5LIB\", NULL},\n {\"XCURSOR_PATH\", NULL},\n};", "static const ExportData no_ld_so_cache_exports[] = {\n {\"LD_LIBRARY_PATH\", \"/app/lib\"},\n};", "static const ExportData devel_exports[] = {\n {\"ACLOCAL_PATH\", \"/app/share/aclocal\"},\n {\"C_INCLUDE_PATH\", \"/app/include\"},\n {\"CPLUS_INCLUDE_PATH\", \"/app/include\"},\n {\"LDFLAGS\", \"-L/app/lib \"},\n {\"PKG_CONFIG_PATH\", \"/app/lib/pkgconfig:/app/share/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig\"},\n {\"LC_ALL\", \"en_US.utf8\"},\n};", "static void\nadd_exports (GPtrArray *env_array,\n const ExportData *exports,\n gsize n_exports)\n{\n int i;", " for (i = 0; i < n_exports; i++)\n {\n if (exports[i].val)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", exports[i].env, exports[i].val));\n }\n}", "char **\nflatpak_run_get_minimal_env (gboolean devel, gboolean use_ld_so_cache)\n{\n GPtrArray *env_array;\n static const char * const copy[] = {\n \"PWD\",\n \"GDMSESSION\",\n \"XDG_CURRENT_DESKTOP\",\n \"XDG_SESSION_DESKTOP\",\n \"DESKTOP_SESSION\",\n \"EMAIL_ADDRESS\",\n \"HOME\",\n \"HOSTNAME\",\n \"LOGNAME\",\n \"REAL_NAME\",\n \"TERM\",\n \"USER\",\n \"USERNAME\",\n };\n static const char * const copy_nodevel[] = {\n \"LANG\",\n \"LANGUAGE\",\n \"LC_ALL\",\n \"LC_ADDRESS\",\n \"LC_COLLATE\",\n \"LC_CTYPE\",\n \"LC_IDENTIFICATION\",\n \"LC_MEASUREMENT\",\n \"LC_MESSAGES\",\n \"LC_MONETARY\",\n \"LC_NAME\",\n \"LC_NUMERIC\",\n \"LC_PAPER\",\n \"LC_TELEPHONE\",\n \"LC_TIME\",\n };\n int i;", " env_array = g_ptr_array_new_with_free_func (g_free);", " add_exports (env_array, default_exports, G_N_ELEMENTS (default_exports));", " if (!use_ld_so_cache)\n add_exports (env_array, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));", " if (devel)\n add_exports (env_array, devel_exports, G_N_ELEMENTS (devel_exports));", " for (i = 0; i < G_N_ELEMENTS (copy); i++)\n {\n const char *current = g_getenv (copy[i]);\n if (current)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", copy[i], current));\n }", " if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (copy_nodevel); i++)\n {\n const char *current = g_getenv (copy_nodevel[i]);\n if (current)\n g_ptr_array_add (env_array, g_strdup_printf (\"%s=%s\", copy_nodevel[i], current));\n }\n }", " g_ptr_array_add (env_array, NULL);\n return (char **) g_ptr_array_free (env_array, FALSE);\n}", "static char **\napply_exports (char **envp,\n const ExportData *exports,\n gsize n_exports)\n{\n int i;", " for (i = 0; i < n_exports; i++)\n {\n const char *value = exports[i].val;", " if (value)\n envp = g_environ_setenv (envp, exports[i].env, value, TRUE);\n else\n envp = g_environ_unsetenv (envp, exports[i].env);\n }", " return envp;\n}", "void\nflatpak_run_apply_env_default (FlatpakBwrap *bwrap, gboolean use_ld_so_cache)\n{\n bwrap->envp = apply_exports (bwrap->envp, default_exports, G_N_ELEMENTS (default_exports));", " if (!use_ld_so_cache)\n bwrap->envp = apply_exports (bwrap->envp, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));\n}", "static void\nflatpak_run_apply_env_prompt (FlatpakBwrap *bwrap, const char *app_id)\n{\n /* A custom shell prompt. FLATPAK_ID is always set.\n * PS1 can be overwritten by runtime metadata or by --env overrides\n */\n flatpak_bwrap_set_env (bwrap, \"FLATPAK_ID\", app_id, TRUE);\n flatpak_bwrap_set_env (bwrap, \"PS1\", \"[📦 $FLATPAK_ID \\\\W]\\\\$ \", FALSE);\n}", "void\nflatpak_run_apply_env_appid (FlatpakBwrap *bwrap,\n GFile *app_dir)\n{\n g_autoptr(GFile) app_dir_data = NULL;\n g_autoptr(GFile) app_dir_config = NULL;\n g_autoptr(GFile) app_dir_cache = NULL;", " app_dir_data = g_file_get_child (app_dir, \"data\");\n app_dir_config = g_file_get_child (app_dir, \"config\");\n app_dir_cache = g_file_get_child (app_dir, \"cache\");\n flatpak_bwrap_set_env (bwrap, \"XDG_DATA_HOME\", flatpak_file_get_path_cached (app_dir_data), TRUE);\n flatpak_bwrap_set_env (bwrap, \"XDG_CONFIG_HOME\", flatpak_file_get_path_cached (app_dir_config), TRUE);\n flatpak_bwrap_set_env (bwrap, \"XDG_CACHE_HOME\", flatpak_file_get_path_cached (app_dir_cache), TRUE);", " if (g_getenv (\"XDG_DATA_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_DATA_HOME\", g_getenv (\"XDG_DATA_HOME\"), TRUE);\n if (g_getenv (\"XDG_CONFIG_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_CONFIG_HOME\", g_getenv (\"XDG_CONFIG_HOME\"), TRUE);\n if (g_getenv (\"XDG_CACHE_HOME\"))\n flatpak_bwrap_set_env (bwrap, \"HOST_XDG_CACHE_HOME\", g_getenv (\"XDG_CACHE_HOME\"), TRUE);\n}", "void\nflatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context)\n{\n GHashTableIter iter;\n gpointer key, value;", " g_hash_table_iter_init (&iter, context->env_vars);\n while (g_hash_table_iter_next (&iter, &key, &value))\n {\n const char *var = key;\n const char *val = value;", " if (val && val[0] != 0)\n flatpak_bwrap_set_env (bwrap, var, val, TRUE);\n else\n flatpak_bwrap_unset_env (bwrap, var);\n }\n}", "GFile *\nflatpak_get_data_dir (const char *app_id)\n{\n g_autoptr(GFile) home = g_file_new_for_path (g_get_home_dir ());\n g_autoptr(GFile) var_app = g_file_resolve_relative_path (home, \".var/app\");", " return g_file_get_child (var_app, app_id);\n}", "gboolean\nflatpak_ensure_data_dir (GFile *app_id_dir,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(GFile) data_dir = g_file_get_child (app_id_dir, \"data\");\n g_autoptr(GFile) cache_dir = g_file_get_child (app_id_dir, \"cache\");\n g_autoptr(GFile) fontconfig_cache_dir = g_file_get_child (cache_dir, \"fontconfig\");\n g_autoptr(GFile) tmp_dir = g_file_get_child (cache_dir, \"tmp\");\n g_autoptr(GFile) config_dir = g_file_get_child (app_id_dir, \"config\");", " if (!flatpak_mkdir_p (data_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (cache_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (fontconfig_cache_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (tmp_dir, cancellable, error))\n return FALSE;", " if (!flatpak_mkdir_p (config_dir, cancellable, error))\n return FALSE;", " return TRUE;\n}", "struct JobData\n{\n char *job;\n GMainLoop *main_loop;\n};", "static void\njob_removed_cb (SystemdManager *manager,\n guint32 id,\n char *job,\n char *unit,\n char *result,\n struct JobData *data)\n{\n if (strcmp (job, data->job) == 0)\n g_main_loop_quit (data->main_loop);\n}", "static gchar *\nsystemd_unit_name_escape (const gchar *in)\n{\n /* Adapted from systemd source */\n GString * const str = g_string_sized_new (strlen (in));", " for (; *in; in++)\n {\n if (g_ascii_isalnum (*in) || *in == ':' || *in == '_' || *in == '.')\n g_string_append_c (str, *in);\n else\n g_string_append_printf (str, \"\\\\x%02x\", *in);\n }\n return g_string_free (str, FALSE);\n}", "gboolean\nflatpak_run_in_transient_unit (const char *appid, GError **error)\n{\n g_autoptr(GDBusConnection) conn = NULL;\n g_autofree char *path = NULL;\n g_autofree char *address = NULL;\n g_autofree char *name = NULL;\n g_autofree char *appid_escaped = NULL;\n g_autofree char *job = NULL;\n SystemdManager *manager = NULL;\n GVariantBuilder builder;\n GVariant *properties = NULL;\n GVariant *aux = NULL;\n guint32 pid;\n GMainLoop *main_loop = NULL;\n struct JobData data;\n gboolean res = FALSE;\n g_autoptr(GMainContextPopDefault) main_context = NULL;", " path = g_strdup_printf (\"/run/user/%d/systemd/private\", getuid ());", " if (!g_file_test (path, G_FILE_TEST_EXISTS))\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,\n _(\"No systemd user session available, cgroups not available\"));", " main_context = flatpak_main_context_new_default ();\n main_loop = g_main_loop_new (main_context, FALSE);", " address = g_strconcat (\"unix:path=\", path, NULL);", " conn = g_dbus_connection_new_for_address_sync (address,\n G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,\n NULL,\n NULL, error);\n if (!conn)\n goto out;", " manager = systemd_manager_proxy_new_sync (conn,\n G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,\n NULL,\n \"/org/freedesktop/systemd1\",\n NULL, error);\n if (!manager)\n goto out;", " appid_escaped = systemd_unit_name_escape (appid);\n name = g_strdup_printf (\"app-flatpak-%s-%d.scope\", appid_escaped, getpid ());", " g_variant_builder_init (&builder, G_VARIANT_TYPE (\"a(sv)\"));", " pid = getpid ();\n g_variant_builder_add (&builder, \"(sv)\",\n \"PIDs\",\n g_variant_new_fixed_array (G_VARIANT_TYPE (\"u\"),\n &pid, 1, sizeof (guint32))\n );", " properties = g_variant_builder_end (&builder);", " aux = g_variant_new_array (G_VARIANT_TYPE (\"(sa(sv))\"), NULL, 0);", " if (!systemd_manager_call_start_transient_unit_sync (manager,\n name,\n \"fail\",\n properties,\n aux,\n &job,\n NULL,\n error))\n goto out;", " data.job = job;\n data.main_loop = main_loop;\n g_signal_connect (manager, \"job-removed\", G_CALLBACK (job_removed_cb), &data);", " g_main_loop_run (main_loop);", " res = TRUE;", "out:\n if (main_loop)\n g_main_loop_unref (main_loop);\n if (manager)\n g_object_unref (manager);", " return res;\n}", "static void\nadd_font_path_args (FlatpakBwrap *bwrap)\n{\n g_autoptr(GString) xml_snippet = g_string_new (\"\");\n gchar *path_build_tmp = NULL;\n g_autoptr(GFile) user_font1 = NULL;\n g_autoptr(GFile) user_font2 = NULL;\n g_autoptr(GFile) user_font_cache = NULL;\n g_auto(GStrv) system_cache_dirs = NULL;\n gboolean found_cache = FALSE;\n int i;", "\n g_string_append (xml_snippet,\n \"<?xml version=\\\"1.0\\\"?>\\n\"\n \"<!DOCTYPE fontconfig SYSTEM \\\"fonts.dtd\\\">\\n\"\n \"<fontconfig>\\n\");", " if (g_file_test (SYSTEM_FONTS_DIR, G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", SYSTEM_FONTS_DIR, \"/run/host/fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/fonts</remap-dir>\\n\",\n SYSTEM_FONTS_DIR);\n }", " if (g_file_test (\"/usr/local/share/fonts\", G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/local/share/fonts\", \"/run/host/local-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/local-fonts</remap-dir>\\n\",\n \"/usr/local/share/fonts\");\n }", " system_cache_dirs = g_strsplit (SYSTEM_FONT_CACHE_DIRS, \":\", 0);\n for (i = 0; system_cache_dirs[i] != NULL; i++)\n {\n if (g_file_test (system_cache_dirs[i], G_FILE_TEST_EXISTS))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", system_cache_dirs[i], \"/run/host/fonts-cache\",\n NULL);\n found_cache = TRUE;\n break;\n }\n }", " if (!found_cache)\n {\n /* We ensure these directories are never writable, or fontconfig\n will use them to write the default cache */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/run/host/fonts-cache\",\n \"--remount-ro\", \"/run/host/fonts-cache\",\n NULL);\n }", " path_build_tmp = g_build_filename (g_get_user_data_dir (), \"fonts\", NULL);\n user_font1 = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " path_build_tmp = g_build_filename (g_get_home_dir (), \".fonts\", NULL);\n user_font2 = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " if (g_file_query_exists (user_font1, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font1), \"/run/host/user-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/user-fonts</remap-dir>\\n\",\n flatpak_file_get_path_cached (user_font1));\n }\n else if (g_file_query_exists (user_font2, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font2), \"/run/host/user-fonts\",\n NULL);\n g_string_append_printf (xml_snippet,\n \"\\t<remap-dir as-path=\\\"%s\\\">/run/host/user-fonts</remap-dir>\\n\",\n flatpak_file_get_path_cached (user_font2));\n }", " path_build_tmp = g_build_filename (g_get_user_cache_dir (), \"fontconfig\", NULL);\n user_font_cache = g_file_new_for_path (path_build_tmp);\n g_clear_pointer (&path_build_tmp, g_free);", " if (g_file_query_exists (user_font_cache, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_font_cache), \"/run/host/user-fonts-cache\",\n NULL);\n }\n else\n {\n /* We ensure these directories are never writable, or fontconfig\n will use them to write the default cache */\n flatpak_bwrap_add_args (bwrap,\n \"--tmpfs\", \"/run/host/user-fonts-cache\",\n \"--remount-ro\", \"/run/host/user-fonts-cache\",\n NULL);\n }", " g_string_append (xml_snippet,\n \"</fontconfig>\\n\");", " if (!flatpak_bwrap_add_args_data (bwrap, \"font-dirs.xml\", xml_snippet->str, xml_snippet->len, \"/run/host/font-dirs.xml\", NULL))\n g_warning (\"Unable to add fontconfig data snippet\");\n}", "static void\nadd_icon_path_args (FlatpakBwrap *bwrap)\n{\n g_autofree gchar *user_icons_path = NULL;\n g_autoptr(GFile) user_icons = NULL;", " if (g_file_test (\"/usr/share/icons\", G_FILE_TEST_IS_DIR))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/share/icons\", \"/run/host/share/icons\",\n NULL);\n }", " user_icons_path = g_build_filename (g_get_user_data_dir (), \"icons\", NULL);\n user_icons = g_file_new_for_path (user_icons_path);\n if (g_file_query_exists (user_icons, NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (user_icons), \"/run/host/user-share/icons\",\n NULL);\n }\n}", "FlatpakContext *\nflatpak_app_compute_permissions (GKeyFile *app_metadata,\n GKeyFile *runtime_metadata,\n GError **error)\n{\n g_autoptr(FlatpakContext) app_context = NULL;", " app_context = flatpak_context_new ();", " if (runtime_metadata != NULL)\n {\n if (!flatpak_context_load_metadata (app_context, runtime_metadata, error))\n return NULL;", " /* Don't inherit any permissions from the runtime, only things like env vars. */\n flatpak_context_reset_permissions (app_context);\n }", " if (app_metadata != NULL &&\n !flatpak_context_load_metadata (app_context, app_metadata, error))\n return NULL;", " return g_steal_pointer (&app_context);\n}", "static void\nflatpak_run_gc_ids (void)\n{\n flatpak_instance_iterate_all_and_gc (NULL);\n}", "static char *\nflatpak_run_allocate_id (int *lock_fd_out)\n{\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *base_dir = g_build_filename (user_runtime_dir, \".flatpak\", NULL);\n int count;", " g_mkdir_with_parents (base_dir, 0755);", " flatpak_run_gc_ids ();", " for (count = 0; count < 1000; count++)\n {\n g_autofree char *instance_id = NULL;\n g_autofree char *instance_dir = NULL;", " instance_id = g_strdup_printf (\"%u\", g_random_int ());", " instance_dir = g_build_filename (base_dir, instance_id, NULL);", " /* We use an atomic mkdir to ensure the instance id is unique */\n if (mkdir (instance_dir, 0755) == 0)\n {\n g_autofree char *lock_file = g_build_filename (instance_dir, \".ref\", NULL);\n glnx_autofd int lock_fd = -1;\n struct flock l = {\n .l_type = F_RDLCK,\n .l_whence = SEEK_SET,\n .l_start = 0,\n .l_len = 0\n };", " /* Then we take a file lock inside the dir, hold that during\n * setup and in bwrap. Anyone trying to clean up unused\n * directories need to first verify that there is a .ref\n * file and take a write lock on .ref to ensure its not in\n * use. */\n lock_fd = open (lock_file, O_RDWR | O_CREAT | O_CLOEXEC, 0644);\n /* There is a tiny race here between the open creating the file and the lock succeeding.\n We work around that by only gc:ing \"old\" .ref files */\n if (lock_fd != -1 && fcntl (lock_fd, F_SETLK, &l) == 0)\n {\n *lock_fd_out = glnx_steal_fd (&lock_fd);\n g_debug (\"Allocated instance id %s\", instance_id);\n return g_steal_pointer (&instance_id);\n }\n }\n }", " return NULL;\n}", "#ifdef HAVE_DCONF", "static void\nadd_dconf_key_to_keyfile (GKeyFile *keyfile,\n DConfClient *client,\n const char *key,\n DConfReadFlags flags)\n{\n g_autofree char *group = g_path_get_dirname (key);\n g_autofree char *k = g_path_get_basename (key);\n GVariant *value = dconf_client_read_full (client, key, flags, NULL);", " if (value)\n {\n g_autofree char *val = g_variant_print (value, TRUE);\n g_key_file_set_value (keyfile, group + 1, k, val);\n }\n}", "static void\nadd_dconf_dir_to_keyfile (GKeyFile *keyfile,\n DConfClient *client,\n const char *dir,\n DConfReadFlags flags)\n{\n g_auto(GStrv) keys = NULL;\n int i;", " keys = dconf_client_list (client, dir, NULL);\n for (i = 0; keys[i]; i++)\n {\n g_autofree char *k = g_strconcat (dir, keys[i], NULL);\n if (dconf_is_dir (k, NULL))\n add_dconf_dir_to_keyfile (keyfile, client, k, flags);\n else if (dconf_is_key (k, NULL))\n add_dconf_key_to_keyfile (keyfile, client, k, flags);\n }\n}", "static void\nadd_dconf_locks_to_list (GString *s,\n DConfClient *client,\n const char *dir)\n{\n g_auto(GStrv) locks = NULL;\n int i;", " locks = dconf_client_list_locks (client, dir, NULL);\n for (i = 0; locks[i]; i++)\n {\n g_string_append (s, locks[i]);\n g_string_append_c (s, '\\n');\n }\n}", "#endif /* HAVE_DCONF */", "static void\nget_dconf_data (const char *app_id,\n const char **paths,\n const char *migrate_path,\n char **defaults,\n gsize *defaults_size,\n char **values,\n gsize *values_size,\n char **locks,\n gsize *locks_size)\n{\n#ifdef HAVE_DCONF\n DConfClient *client = NULL;\n g_autofree char *prefix = NULL;\n#endif\n g_autoptr(GKeyFile) defaults_data = NULL;\n g_autoptr(GKeyFile) values_data = NULL;\n g_autoptr(GString) locks_data = NULL;", " defaults_data = g_key_file_new ();\n values_data = g_key_file_new ();\n locks_data = g_string_new (\"\");", "#ifdef HAVE_DCONF", " client = dconf_client_new ();", " prefix = flatpak_dconf_path_for_app_id (app_id);", " if (migrate_path)\n {\n g_debug (\"Add values in dir '%s', prefix is '%s'\", migrate_path, prefix);\n if (flatpak_dconf_path_is_similar (migrate_path, prefix))\n add_dconf_dir_to_keyfile (values_data, client, migrate_path, DCONF_READ_USER_VALUE);\n else\n g_warning (\"Ignoring D-Conf migrate-path setting %s\", migrate_path);\n }", " g_debug (\"Add defaults in dir %s\", prefix);\n add_dconf_dir_to_keyfile (defaults_data, client, prefix, DCONF_READ_DEFAULT_VALUE);", " g_debug (\"Add locks in dir %s\", prefix);\n add_dconf_locks_to_list (locks_data, client, prefix);", " /* We allow extra paths for defaults and locks, but not for user values */\n if (paths)\n {\n int i;\n for (i = 0; paths[i]; i++)\n {\n if (dconf_is_dir (paths[i], NULL))\n {\n g_debug (\"Add defaults in dir %s\", paths[i]);\n add_dconf_dir_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);", " g_debug (\"Add locks in dir %s\", paths[i]);\n add_dconf_locks_to_list (locks_data, client, paths[i]);\n }\n else if (dconf_is_key (paths[i], NULL))\n {\n g_debug (\"Add individual key %s\", paths[i]);\n add_dconf_key_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);\n add_dconf_key_to_keyfile (values_data, client, paths[i], DCONF_READ_USER_VALUE);\n }\n else\n {\n g_warning (\"Ignoring settings path '%s': neither dir nor key\", paths[i]);\n }\n }\n }\n#endif", " *defaults = g_key_file_to_data (defaults_data, defaults_size, NULL);\n *values = g_key_file_to_data (values_data, values_size, NULL);\n *locks_size = locks_data->len;\n *locks = g_string_free (g_steal_pointer (&locks_data), FALSE);", "#ifdef HAVE_DCONF\n g_object_unref (client);\n#endif\n}", "static gboolean\nflatpak_run_add_dconf_args (FlatpakBwrap *bwrap,\n const char *app_id,\n GKeyFile *metakey,\n GError **error)\n{\n g_auto(GStrv) paths = NULL;\n g_autofree char *migrate_path = NULL;\n g_autofree char *defaults = NULL;\n g_autofree char *values = NULL;\n g_autofree char *locks = NULL;\n gsize defaults_size;\n gsize values_size;\n gsize locks_size;", " if (metakey)\n {\n paths = g_key_file_get_string_list (metakey,\n FLATPAK_METADATA_GROUP_DCONF,\n FLATPAK_METADATA_KEY_DCONF_PATHS,\n NULL, NULL);\n migrate_path = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_DCONF,\n FLATPAK_METADATA_KEY_DCONF_MIGRATE_PATH,\n NULL);\n }", " get_dconf_data (app_id,\n (const char **) paths,\n migrate_path,\n &defaults, &defaults_size,\n &values, &values_size,\n &locks, &locks_size);", " if (defaults_size != 0 &&\n !flatpak_bwrap_add_args_data (bwrap,\n \"dconf-defaults\",\n defaults, defaults_size,\n \"/etc/glib-2.0/settings/defaults\",\n error))\n return FALSE;", " if (locks_size != 0 &&\n !flatpak_bwrap_add_args_data (bwrap,\n \"dconf-locks\",\n locks, locks_size,\n \"/etc/glib-2.0/settings/locks\",\n error))\n return FALSE;", " /* We do a one-time conversion of existing dconf settings to a keyfile.\n * Only do that once the app stops requesting dconf access.\n */\n if (migrate_path)\n {\n g_autofree char *filename = NULL;", " filename = g_build_filename (g_get_home_dir (),\n \".var/app\", app_id,\n \"config/glib-2.0/settings/keyfile\",\n NULL);", " g_debug (\"writing D-Conf values to %s\", filename);", " if (values_size != 0 && !g_file_test (filename, G_FILE_TEST_EXISTS))\n {\n g_autofree char *dir = g_path_get_dirname (filename);", " if (g_mkdir_with_parents (dir, 0700) == -1)\n {\n g_warning (\"failed creating dirs for %s\", filename);\n return FALSE;\n }", " if (!g_file_set_contents (filename, values, values_size, error))\n {\n g_warning (\"failed writing %s\", filename);\n return FALSE;\n }\n }\n }", " return TRUE;\n}", "gboolean\nflatpak_run_add_app_info_args (FlatpakBwrap *bwrap,\n GFile *app_files,\n GBytes *app_deploy_data,\n const char *app_extensions,\n GFile *runtime_files,\n GBytes *runtime_deploy_data,\n const char *runtime_extensions,\n const char *app_id,\n const char *app_branch,\n FlatpakDecomposed *runtime_ref,\n GFile *app_id_dir,\n FlatpakContext *final_app_context,\n FlatpakContext *cmdline_context,\n gboolean sandbox,\n gboolean build,\n gboolean devel,\n char **app_info_path_out,\n int instance_id_fd,\n char **instance_id_host_dir_out,\n GError **error)\n{\n g_autofree char *info_path = NULL;\n g_autofree char *bwrapinfo_path = NULL;\n int fd, fd2, fd3;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree char *runtime_path = NULL;\n g_autofree char *old_dest = g_strdup_printf (\"/run/user/%d/flatpak-info\", getuid ());\n const char *group;\n g_autofree char *instance_id = NULL;\n glnx_autofd int lock_fd = -1;\n g_autofree char *instance_id_host_dir = NULL;\n g_autofree char *instance_id_sandbox_dir = NULL;\n g_autofree char *instance_id_lock_file = NULL;\n g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();\n g_autofree char *arch = flatpak_decomposed_dup_arch (runtime_ref);", " instance_id = flatpak_run_allocate_id (&lock_fd);\n if (instance_id == NULL)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Unable to allocate instance id\"));", " instance_id_host_dir = g_build_filename (user_runtime_dir, \".flatpak\", instance_id, NULL);\n instance_id_sandbox_dir = g_strdup_printf (\"/run/user/%d/.flatpak/%s\", getuid (), instance_id);\n instance_id_lock_file = g_build_filename (instance_id_sandbox_dir, \".ref\", NULL);", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\",\n instance_id_host_dir,\n instance_id_sandbox_dir,\n \"--lock-file\",\n instance_id_lock_file,\n NULL);\n /* Keep the .ref lock held until we've started bwrap to avoid races */\n flatpak_bwrap_add_noinherit_fd (bwrap, glnx_steal_fd (&lock_fd));", " info_path = g_build_filename (instance_id_host_dir, \"info\", NULL);", " keyfile = g_key_file_new ();", " if (app_files)\n group = FLATPAK_METADATA_GROUP_APPLICATION;\n else\n group = FLATPAK_METADATA_GROUP_RUNTIME;", " g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_NAME, app_id);\n g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_RUNTIME,\n flatpak_decomposed_get_ref (runtime_ref));", " g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, instance_id);\n if (app_id_dir)\n {\n g_autofree char *instance_path = g_file_get_path (app_id_dir);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, instance_path);\n }", " if (app_files)\n {\n g_autofree char *app_path = g_file_get_path (app_files);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_PATH, app_path);\n }\n if (app_deploy_data)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, flatpak_deploy_data_get_commit (app_deploy_data));\n if (app_extensions && *app_extensions != 0)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_EXTENSIONS, app_extensions);\n runtime_path = g_file_get_path (runtime_files);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_PATH, runtime_path);\n if (runtime_deploy_data)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, flatpak_deploy_data_get_commit (runtime_deploy_data));\n if (runtime_extensions && *runtime_extensions != 0)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_EXTENSIONS, runtime_extensions);\n if (app_branch != NULL)\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, app_branch);\n g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, arch);", " g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_FLATPAK_VERSION, PACKAGE_VERSION);", " if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) == 0)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SESSION_BUS_PROXY, TRUE);", " if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) == 0)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SYSTEM_BUS_PROXY, TRUE);", " if (sandbox)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_SANDBOX, TRUE);\n if (build)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BUILD, TRUE);\n if (devel)\n g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, TRUE);", " if (cmdline_context)\n {\n g_autoptr(GPtrArray) cmdline_args = g_ptr_array_new_with_free_func (g_free);\n flatpak_context_to_args (cmdline_context, cmdline_args);\n if (cmdline_args->len > 0)\n {\n g_key_file_set_string_list (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS,\n (const char * const *) cmdline_args->pdata,\n cmdline_args->len);\n }\n }", " flatpak_context_save_metadata (final_app_context, TRUE, keyfile);", " if (!g_key_file_save_to_file (keyfile, info_path, error))\n return FALSE;", " /* We want to create a file on /.flatpak-info that the app cannot modify, which\n we do by creating a read-only bind mount. This way one can openat()\n /proc/$pid/root, and if that succeeds use openat via that to find the\n unfakable .flatpak-info file. However, there is a tiny race in that if\n you manage to open /proc/$pid/root, but then the pid dies, then\n every mount but the root is unmounted in the namespace, so the\n .flatpak-info will be empty. We fix this by first creating a real file\n with the real info in, then bind-mounting on top of that, the same info.\n This way even if the bind-mount is unmounted we can find the real data.\n */", " fd = open (info_path, O_RDONLY);\n if (fd == -1)\n {\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open flatpak-info file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " fd2 = open (info_path, O_RDONLY);\n if (fd2 == -1)\n {\n close (fd);\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open flatpak-info file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " flatpak_bwrap_add_args_data_fd (bwrap,\n \"--file\", fd, \"/.flatpak-info\");\n flatpak_bwrap_add_args_data_fd (bwrap,\n \"--ro-bind-data\", fd2, \"/.flatpak-info\");\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", \"../../../.flatpak-info\", old_dest,\n NULL);", " /* Tell the application that it's running under Flatpak in a generic way. */\n flatpak_bwrap_add_args (bwrap,\n \"--setenv\", \"container\", \"flatpak\",\n NULL);\n if (!flatpak_bwrap_add_args_data (bwrap,\n \"container-manager\",\n \"flatpak\\n\", -1,\n \"/run/host/container-manager\",\n error))\n return FALSE;", " bwrapinfo_path = g_build_filename (instance_id_host_dir, \"bwrapinfo.json\", NULL);\n fd3 = open (bwrapinfo_path, O_RDWR | O_CREAT, 0644);\n if (fd3 == -1)\n {\n close (fd);\n close (fd2);\n int errsv = errno;\n g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to open bwrapinfo.json file: %s\"), g_strerror (errsv));\n return FALSE;\n }", " /* NOTE: It is important that this takes place after bwrapinfo.json is created,\n otherwise start notifications in the portal may not work. */\n if (instance_id_fd != -1)\n {\n gsize instance_id_position = 0;\n gsize instance_id_size = strlen (instance_id);", " while (instance_id_size > 0)\n {\n gssize bytes_written = write (instance_id_fd, instance_id + instance_id_position, instance_id_size);\n if (G_UNLIKELY (bytes_written <= 0))\n {\n int errsv = bytes_written == -1 ? errno : ENOSPC;\n if (errsv == EINTR)\n continue;", " close (fd);\n close (fd2);\n close (fd3);", " g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),\n _(\"Failed to write to instance id fd: %s\"), g_strerror (errsv));\n return FALSE;\n }", " instance_id_position += bytes_written;\n instance_id_size -= bytes_written;\n }", " close (instance_id_fd);\n }", " flatpak_bwrap_add_args_data_fd (bwrap, \"--info-fd\", fd3, NULL);", " if (app_info_path_out != NULL)\n *app_info_path_out = g_strdup_printf (\"/proc/self/fd/%d\", fd);", " if (instance_id_host_dir_out != NULL)\n *instance_id_host_dir_out = g_steal_pointer (&instance_id_host_dir);", " return TRUE;\n}", "static void\nadd_tzdata_args (FlatpakBwrap *bwrap,\n GFile *runtime_files)\n{\n g_autofree char *raw_timezone = flatpak_get_timezone ();\n g_autofree char *timezone_content = g_strdup_printf (\"%s\\n\", raw_timezone);\n g_autofree char *localtime_content = g_strconcat (\"../usr/share/zoneinfo/\", raw_timezone, NULL);\n g_autoptr(GFile) runtime_zoneinfo = NULL;", " if (runtime_files)\n runtime_zoneinfo = g_file_resolve_relative_path (runtime_files, \"share/zoneinfo\");", " /* Check for runtime /usr/share/zoneinfo */\n if (runtime_zoneinfo != NULL && g_file_query_exists (runtime_zoneinfo, NULL))\n {\n /* Check for host /usr/share/zoneinfo */\n if (g_file_test (\"/usr/share/zoneinfo\", G_FILE_TEST_IS_DIR))\n {\n /* Here we assume the host timezone file exist in the host data */\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/usr/share/zoneinfo\", \"/usr/share/zoneinfo\",\n \"--symlink\", localtime_content, \"/etc/localtime\",\n NULL);\n }\n else\n {\n g_autoptr(GFile) runtime_tzfile = g_file_resolve_relative_path (runtime_zoneinfo, raw_timezone);", " /* Check if host timezone file exist in the runtime tzdata */\n if (g_file_query_exists (runtime_tzfile, NULL))\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", localtime_content, \"/etc/localtime\",\n NULL);\n }\n }", " flatpak_bwrap_add_args_data (bwrap, \"timezone\",\n timezone_content, -1, \"/etc/timezone\",\n NULL);\n}", "static void\nadd_monitor_path_args (gboolean use_session_helper,\n FlatpakBwrap *bwrap)\n{\n g_autoptr(AutoFlatpakSessionHelper) session_helper = NULL;\n g_autofree char *monitor_path = NULL;\n g_autofree char *pkcs11_socket_path = NULL;\n g_autoptr(GVariant) session_data = NULL;", " if (use_session_helper)\n {\n session_helper =\n flatpak_session_helper_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,\n G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,\n \"org.freedesktop.Flatpak\",\n \"/org/freedesktop/Flatpak/SessionHelper\",\n NULL, NULL);\n }", " if (session_helper &&\n flatpak_session_helper_call_request_session_sync (session_helper,\n &session_data,\n NULL, NULL))\n {\n if (g_variant_lookup (session_data, \"path\", \"s\", &monitor_path))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", monitor_path, \"/run/host/monitor\",\n \"--symlink\", \"/run/host/monitor/resolv.conf\", \"/etc/resolv.conf\",\n \"--symlink\", \"/run/host/monitor/host.conf\", \"/etc/host.conf\",\n \"--symlink\", \"/run/host/monitor/hosts\", \"/etc/hosts\",\n NULL);", " if (g_variant_lookup (session_data, \"pkcs11-socket\", \"s\", &pkcs11_socket_path))\n {\n g_autofree char *sandbox_pkcs11_socket_path = g_strdup_printf (\"/run/user/%d/p11-kit/pkcs11\", getuid ());\n const char *trusted_module_contents =\n \"# This overrides the runtime p11-kit-trusted module with a client one talking to the trust module on the host\\n\"\n \"module: p11-kit-client.so\\n\";", " if (flatpak_bwrap_add_args_data (bwrap, \"p11-kit-trust.module\",\n trusted_module_contents, -1,\n \"/etc/pkcs11/modules/p11-kit-trust.module\", NULL))\n {\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", pkcs11_socket_path, sandbox_pkcs11_socket_path,\n NULL);\n flatpak_bwrap_unset_env (bwrap, \"P11_KIT_SERVER_ADDRESS\");\n }\n }\n }\n else\n {\n if (g_file_test (\"/etc/resolv.conf\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/resolv.conf\", \"/etc/resolv.conf\",\n NULL);\n if (g_file_test (\"/etc/host.conf\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/host.conf\", \"/etc/host.conf\",\n NULL);\n if (g_file_test (\"/etc/hosts\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", \"/etc/hosts\", \"/etc/hosts\",\n NULL);\n }\n}", "static void\nadd_document_portal_args (FlatpakBwrap *bwrap,\n const char *app_id,\n char **out_mount_path)\n{\n g_autoptr(GDBusConnection) session_bus = NULL;\n g_autofree char *doc_mount_path = NULL;", " session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);\n if (session_bus)\n {\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDBusMessage) reply = NULL;\n g_autoptr(GDBusMessage) msg =\n g_dbus_message_new_method_call (\"org.freedesktop.portal.Documents\",\n \"/org/freedesktop/portal/documents\",\n \"org.freedesktop.portal.Documents\",\n \"GetMountPoint\");\n g_dbus_message_set_body (msg, g_variant_new (\"()\"));\n reply =\n g_dbus_connection_send_message_with_reply_sync (session_bus, msg,\n G_DBUS_SEND_MESSAGE_FLAGS_NONE,\n 30000,\n NULL,\n NULL,\n NULL);\n if (reply)\n {\n if (g_dbus_message_to_gerror (reply, &local_error))\n {\n if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))\n g_debug (\"Document portal not available, not mounting /run/user/%d/doc\", getuid ());\n else\n g_message (\"Can't get document portal: %s\", local_error->message);\n }\n else\n {\n g_autofree char *src_path = NULL;\n g_autofree char *dst_path = NULL;\n g_variant_get (g_dbus_message_get_body (reply),\n \"(^ay)\", &doc_mount_path);", " src_path = g_strdup_printf (\"%s/by-app/%s\",\n doc_mount_path, app_id);\n dst_path = g_strdup_printf (\"/run/user/%d/doc\", getuid ());\n flatpak_bwrap_add_args (bwrap, \"--bind\", src_path, dst_path, NULL);\n }\n }\n }", " *out_mount_path = g_steal_pointer (&doc_mount_path);\n}", "#ifdef ENABLE_SECCOMP\nstatic const uint32_t seccomp_x86_64_extra_arches[] = { SCMP_ARCH_X86, 0, };", "#ifdef SCMP_ARCH_AARCH64\nstatic const uint32_t seccomp_aarch64_extra_arches[] = { SCMP_ARCH_ARM, 0 };\n#endif", "static inline void\ncleanup_seccomp (void *p)\n{\n scmp_filter_ctx *pp = (scmp_filter_ctx *) p;", " if (*pp)\n seccomp_release (*pp);\n}", "static gboolean\nsetup_seccomp (FlatpakBwrap *bwrap,\n const char *arch,\n gulong allowed_personality,\n FlatpakRunFlags run_flags,\n GError **error)\n{\n gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;\n gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;", " __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;", " /**** BEGIN NOTE ON CODE SHARING\n *\n * There are today a number of different Linux container\n * implementations. That will likely continue for long into the\n * future. But we can still try to share code, and it's important\n * to do so because it affects what library and application writers\n * can do, and we should support code portability between different\n * container tools.\n *\n * This syscall blocklist is copied from linux-user-chroot, which was in turn\n * clearly influenced by the Sandstorm.io blocklist.\n *\n * If you make any changes here, I suggest sending the changes along\n * to other sandbox maintainers. Using the libseccomp list is also\n * an appropriate venue:\n * https://groups.google.com/forum/#!forum/libseccomp\n *\n * A non-exhaustive list of links to container tooling that might\n * want to share this blocklist:\n *\n * https://github.com/sandstorm-io/sandstorm\n * in src/sandstorm/supervisor.c++\n * https://github.com/flatpak/flatpak.git\n * in common/flatpak-run.c\n * https://git.gnome.org/browse/linux-user-chroot\n * in src/setup-seccomp.c\n *\n **** END NOTE ON CODE SHARING\n */\n struct\n {\n int scall;\n struct scmp_arg_cmp *arg;\n } syscall_blocklist[] = {\n /* Block dmesg */\n {SCMP_SYS (syslog)},\n /* Useless old syscall */\n {SCMP_SYS (uselib)},\n /* Don't allow disabling accounting */\n {SCMP_SYS (acct)},\n /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a\n historic source of interesting information leaks. */\n {SCMP_SYS (modify_ldt)},\n /* Don't allow reading current quota use */\n {SCMP_SYS (quotactl)},", " /* Don't allow access to the kernel keyring */\n {SCMP_SYS (add_key)},\n {SCMP_SYS (keyctl)},\n {SCMP_SYS (request_key)},", " /* Scary VM/NUMA ops */\n {SCMP_SYS (move_pages)},\n {SCMP_SYS (mbind)},\n {SCMP_SYS (get_mempolicy)},\n {SCMP_SYS (set_mempolicy)},\n {SCMP_SYS (migrate_pages)},", " /* Don't allow subnamespace setups: */\n {SCMP_SYS (unshare)},\n {SCMP_SYS (mount)},\n {SCMP_SYS (pivot_root)},\n#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack\n * and flags arguments are reversed so the flags come second */\n {SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#else\n /* Normally the flags come first */\n {SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},\n#endif", " /* Don't allow faking input to the controlling tty (CVE-2017-5226) */\n {SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},\n };", " struct\n {\n int scall;\n struct scmp_arg_cmp *arg;\n } syscall_nondevel_blocklist[] = {\n /* Profiling operations; we expect these to be done by tools from outside\n * the sandbox. In particular perf has been the source of many CVEs.\n */\n {SCMP_SYS (perf_event_open)},\n /* Don't allow you to switch to bsd emulation or whatnot */\n {SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},\n {SCMP_SYS (ptrace)}\n };\n /* Blocklist all but unix, inet, inet6 and netlink */\n struct\n {\n int family;\n FlatpakRunFlags flags_mask;\n } socket_family_allowlist[] = {\n /* NOTE: Keep in numerical order */\n { AF_UNSPEC, 0 },\n { AF_LOCAL, 0 },\n { AF_INET, 0 },\n { AF_INET6, 0 },\n { AF_NETLINK, 0 },\n { AF_CAN, FLATPAK_RUN_FLAG_CANBUS },\n { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },\n };\n int last_allowed_family;\n int i, r;\n g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };", " seccomp = seccomp_init (SCMP_ACT_ALLOW);\n if (!seccomp)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Initialize seccomp failed\"));", " if (arch != NULL)\n {\n uint32_t arch_id = 0;\n const uint32_t *extra_arches = NULL;", " if (strcmp (arch, \"i386\") == 0)\n {\n arch_id = SCMP_ARCH_X86;\n }\n else if (strcmp (arch, \"x86_64\") == 0)\n {\n arch_id = SCMP_ARCH_X86_64;\n extra_arches = seccomp_x86_64_extra_arches;\n }\n else if (strcmp (arch, \"arm\") == 0)\n {\n arch_id = SCMP_ARCH_ARM;\n }\n#ifdef SCMP_ARCH_AARCH64\n else if (strcmp (arch, \"aarch64\") == 0)\n {\n arch_id = SCMP_ARCH_AARCH64;\n extra_arches = seccomp_aarch64_extra_arches;\n }\n#endif", " /* We only really need to handle arches on multiarch systems.\n * If only one arch is supported the default is fine */\n if (arch_id != 0)\n {\n /* This *adds* the target arch, instead of replacing the\n native one. This is not ideal, because we'd like to only\n allow the target arch, but we can't really disallow the\n native arch at this point, because then bubblewrap\n couldn't continue running. */\n r = seccomp_arch_add (seccomp, arch_id);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add architecture to seccomp filter\"));", " if (multiarch && extra_arches != NULL)\n {\n for (i = 0; extra_arches[i] != 0; i++)\n {\n r = seccomp_arch_add (seccomp, extra_arches[i]);\n if (r < 0 && r != -EEXIST)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to add multiarch architecture to seccomp filter\"));\n }\n }\n }\n }", " /* TODO: Should we filter the kernel keyring syscalls in some way?\n * We do want them to be used by desktop apps, but they could also perhaps\n * leak system stuff or secrets from other apps.\n */", " for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)\n {\n int scall = syscall_blocklist[i].scall;\n if (syscall_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);\n if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }", " if (!devel)\n {\n for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)\n {\n int scall = syscall_nondevel_blocklist[i].scall;\n if (syscall_nondevel_blocklist[i].arg)\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg);\n else\n r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);", " if (r < 0 && r == -EFAULT /* unknown syscall */)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to block syscall %d\"), scall);\n }\n }", " /* Socket filtering doesn't work on e.g. i386, so ignore failures here\n * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing\n * something else: https://github.com/seccomp/libseccomp/issues/8 */\n last_allowed_family = -1;\n for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)\n {\n int family = socket_family_allowlist[i].family;\n int disallowed;", " if (socket_family_allowlist[i].flags_mask != 0 &&\n (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)\n continue;", " for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)\n {\n /* Blocklist the in-between valid families */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));\n }\n last_allowed_family = family;\n }\n /* Blocklist the rest */\n seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));", " if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, \"/tmp\", &seccomp_tmpf, error))\n return FALSE;", " if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)\n return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Failed to export bpf\"));", " lseek (seccomp_tmpf.fd, 0, SEEK_SET);", " flatpak_bwrap_add_args_data_fd (bwrap,\n \"--seccomp\", glnx_steal_fd (&seccomp_tmpf.fd), NULL);", " return TRUE;\n}\n#endif", "static void\nflatpak_run_setup_usr_links (FlatpakBwrap *bwrap,\n GFile *runtime_files)\n{\n int i;", " if (runtime_files == NULL)\n return;", " for (i = 0; flatpak_abs_usrmerged_dirs[i] != NULL; i++)\n {\n const char *subdir = flatpak_abs_usrmerged_dirs[i];\n g_autoptr(GFile) runtime_subdir = NULL;", " g_assert (subdir[0] == '/');\n /* Skip the '/' when using as a subdirectory of the runtime */\n runtime_subdir = g_file_get_child (runtime_files, subdir + 1);", " if (g_file_query_exists (runtime_subdir, NULL))\n {\n g_autofree char *link = g_strconcat (\"usr\", subdir, NULL);\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", link, subdir,\n NULL);\n }\n }\n}", "gboolean\nflatpak_run_setup_base_argv (FlatpakBwrap *bwrap,\n GFile *runtime_files,\n GFile *app_id_dir,\n const char *arch,\n FlatpakRunFlags flags,\n GError **error)\n{\n g_autofree char *run_dir = NULL;\n g_autofree char *passwd_contents = NULL;\n g_autoptr(GString) group_contents = NULL;\n const char *pkcs11_conf_contents = NULL;\n struct group *g;\n gulong pers;\n gid_t gid = getgid ();\n g_autoptr(GFile) etc = NULL;", " run_dir = g_strdup_printf (\"/run/user/%d\", getuid ());", " passwd_contents = g_strdup_printf (\"%s:x:%d:%d:%s:%s:%s\\n\"\n \"nfsnobody:x:65534:65534:Unmapped user:/:/sbin/nologin\\n\",\n g_get_user_name (),\n getuid (), gid,\n g_get_real_name (),\n g_get_home_dir (),\n DEFAULT_SHELL);", " group_contents = g_string_new (\"\");\n g = getgrgid (gid);\n /* if NULL, the primary group is not known outside the container, so\n * it might as well stay unknown inside the container... */\n if (g != NULL)\n g_string_append_printf (group_contents, \"%s:x:%d:%s\\n\",\n g->gr_name, gid, g_get_user_name ());\n g_string_append (group_contents, \"nfsnobody:x:65534:\\n\");", " pkcs11_conf_contents =\n \"# Disable user pkcs11 config, because the host modules don't work in the runtime\\n\"\n \"user-config: none\\n\";", " if ((flags & FLATPAK_RUN_FLAG_NO_PROC) == 0)\n flatpak_bwrap_add_args (bwrap,\n \"--proc\", \"/proc\",\n NULL);", " if (!(flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS))\n flatpak_bwrap_add_arg (bwrap, \"--unshare-pid\");", " flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/tmp\",\n \"--dir\", \"/var/tmp\",\n \"--dir\", \"/run/host\",\n \"--dir\", run_dir,\n \"--setenv\", \"XDG_RUNTIME_DIR\", run_dir,\n \"--symlink\", \"../run\", \"/var/run\",\n \"--ro-bind\", \"/sys/block\", \"/sys/block\",\n \"--ro-bind\", \"/sys/bus\", \"/sys/bus\",\n \"--ro-bind\", \"/sys/class\", \"/sys/class\",\n \"--ro-bind\", \"/sys/dev\", \"/sys/dev\",\n \"--ro-bind\", \"/sys/devices\", \"/sys/devices\",\n \"--ro-bind-try\", \"/proc/self/ns/user\", \"/run/.userns\",\n /* glib uses this like /etc/timezone */\n \"--symlink\", \"/etc/timezone\", \"/var/db/zoneinfo\",\n NULL);", " if (flags & FLATPAK_RUN_FLAG_DIE_WITH_PARENT)\n flatpak_bwrap_add_args (bwrap,\n \"--die-with-parent\",\n NULL);", " if (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC)\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/usr/etc\",\n \"--symlink\", \"usr/etc\", \"/etc\",\n NULL);", " if (!flatpak_bwrap_add_args_data (bwrap, \"passwd\", passwd_contents, -1, \"/etc/passwd\", error))\n return FALSE;", " if (!flatpak_bwrap_add_args_data (bwrap, \"group\", group_contents->str, -1, \"/etc/group\", error))\n return FALSE;", " if (!flatpak_bwrap_add_args_data (bwrap, \"pkcs11.conf\", pkcs11_conf_contents, -1, \"/etc/pkcs11/pkcs11.conf\", error))\n return FALSE;", " if (g_file_test (\"/etc/machine-id\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", \"/etc/machine-id\", \"/etc/machine-id\", NULL);\n else if (g_file_test (\"/var/lib/dbus/machine-id\", G_FILE_TEST_EXISTS))\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", \"/var/lib/dbus/machine-id\", \"/etc/machine-id\", NULL);", " if (runtime_files)\n etc = g_file_get_child (runtime_files, \"etc\");\n if (etc != NULL &&\n (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0 &&\n g_file_query_exists (etc, NULL))\n {\n g_auto(GLnxDirFdIterator) dfd_iter = { 0, };\n struct dirent *dent;\n gboolean inited;", " inited = glnx_dirfd_iterator_init_at (AT_FDCWD, flatpak_file_get_path_cached (etc), FALSE, &dfd_iter, NULL);", " while (inited)\n {\n g_autofree char *src = NULL;\n g_autofree char *dest = NULL;", " if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, NULL, NULL) || dent == NULL)\n break;", " if (strcmp (dent->d_name, \"passwd\") == 0 ||\n strcmp (dent->d_name, \"group\") == 0 ||\n strcmp (dent->d_name, \"machine-id\") == 0 ||\n strcmp (dent->d_name, \"resolv.conf\") == 0 ||\n strcmp (dent->d_name, \"host.conf\") == 0 ||\n strcmp (dent->d_name, \"hosts\") == 0 ||\n strcmp (dent->d_name, \"localtime\") == 0 ||\n strcmp (dent->d_name, \"timezone\") == 0 ||\n strcmp (dent->d_name, \"pkcs11\") == 0)\n continue;", " src = g_build_filename (flatpak_file_get_path_cached (etc), dent->d_name, NULL);\n dest = g_build_filename (\"/etc\", dent->d_name, NULL);\n if (dent->d_type == DT_LNK)\n {\n g_autofree char *target = NULL;", " target = glnx_readlinkat_malloc (dfd_iter.fd, dent->d_name,\n NULL, error);\n if (target == NULL)\n return FALSE;", " flatpak_bwrap_add_args (bwrap, \"--symlink\", target, dest, NULL);\n }\n else\n {\n flatpak_bwrap_add_args (bwrap, \"--ro-bind\", src, dest, NULL);\n }\n }\n }", " if (app_id_dir != NULL)\n {\n g_autoptr(GFile) app_cache_dir = g_file_get_child (app_id_dir, \"cache\");\n g_autoptr(GFile) app_tmp_dir = g_file_get_child (app_cache_dir, \"tmp\");\n g_autoptr(GFile) app_data_dir = g_file_get_child (app_id_dir, \"data\");\n g_autoptr(GFile) app_config_dir = g_file_get_child (app_id_dir, \"config\");", " flatpak_bwrap_add_args (bwrap,\n /* These are nice to have as a fixed path */\n \"--bind\", flatpak_file_get_path_cached (app_cache_dir), \"/var/cache\",\n \"--bind\", flatpak_file_get_path_cached (app_data_dir), \"/var/data\",\n \"--bind\", flatpak_file_get_path_cached (app_config_dir), \"/var/config\",\n \"--bind\", flatpak_file_get_path_cached (app_tmp_dir), \"/var/tmp\",\n NULL);\n }", " flatpak_run_setup_usr_links (bwrap, runtime_files);", " add_tzdata_args (bwrap, runtime_files);", " pers = PER_LINUX;", " if ((flags & FLATPAK_RUN_FLAG_SET_PERSONALITY) &&\n flatpak_is_linux32_arch (arch))\n {\n g_debug (\"Setting personality linux32\");\n pers = PER_LINUX32;\n }", " /* Always set the personallity, and clear all weird flags */\n personality (pers);", "#ifdef ENABLE_SECCOMP\n if (!setup_seccomp (bwrap, arch, pers, flags, error))\n return FALSE;\n#endif", " if ((flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0)\n add_monitor_path_args ((flags & FLATPAK_RUN_FLAG_NO_SESSION_HELPER) == 0, bwrap);", " return TRUE;\n}", "static gboolean\nforward_file (XdpDbusDocuments *documents,\n const char *app_id,\n const char *file,\n char **out_doc_id,\n GError **error)\n{\n int fd, fd_id;\n g_autofree char *doc_id = NULL;\n g_autoptr(GUnixFDList) fd_list = NULL;\n const char *perms[] = { \"read\", \"write\", NULL };", " fd = open (file, O_PATH | O_CLOEXEC);\n if (fd == -1)\n return flatpak_fail (error, _(\"Failed to open ‘%s’\"), file);", " fd_list = g_unix_fd_list_new ();\n fd_id = g_unix_fd_list_append (fd_list, fd, error);\n close (fd);", " if (!xdp_dbus_documents_call_add_sync (documents,\n g_variant_new (\"h\", fd_id),\n TRUE, /* reuse */\n FALSE, /* not persistent */\n fd_list,\n &doc_id,\n NULL,\n NULL,\n error))\n {\n if (error)\n g_dbus_error_strip_remote_error (*error);\n return FALSE;\n }", " if (!xdp_dbus_documents_call_grant_permissions_sync (documents,\n doc_id,\n app_id,\n perms,\n NULL,\n error))\n {\n if (error)\n g_dbus_error_strip_remote_error (*error);\n return FALSE;\n }", " *out_doc_id = g_steal_pointer (&doc_id);", " return TRUE;\n}", "static gboolean\nadd_rest_args (FlatpakBwrap *bwrap,\n const char *app_id,\n FlatpakExports *exports,\n gboolean file_forwarding,\n const char *doc_mount_path,\n char *args[],\n int n_args,\n GError **error)\n{\n g_autoptr(XdpDbusDocuments) documents = NULL;\n gboolean forwarding = FALSE;\n gboolean forwarding_uri = FALSE;\n gboolean can_forward = TRUE;\n int i;", " if (file_forwarding && doc_mount_path == NULL)\n {\n g_message (\"Can't get document portal mount path\");\n can_forward = FALSE;\n }\n else if (file_forwarding)\n {\n g_autoptr(GError) local_error = NULL;", " documents = xdp_dbus_documents_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, 0,\n \"org.freedesktop.portal.Documents\",\n \"/org/freedesktop/portal/documents\",\n NULL,\n &local_error);\n if (documents == NULL)\n {\n g_message (\"Can't get document portal: %s\", local_error->message);\n can_forward = FALSE;\n }\n }", " for (i = 0; i < n_args; i++)\n {\n g_autoptr(GFile) file = NULL;", " if (file_forwarding &&\n (strcmp (args[i], \"@@\") == 0 ||\n strcmp (args[i], \"@@u\") == 0))\n {\n forwarding_uri = strcmp (args[i], \"@@u\") == 0;\n forwarding = !forwarding;\n continue;\n }", " if (can_forward && forwarding)\n {\n if (forwarding_uri)\n {\n if (g_str_has_prefix (args[i], \"file:\"))\n file = g_file_new_for_uri (args[i]);\n else if (G_IS_DIR_SEPARATOR (args[i][0]))\n file = g_file_new_for_path (args[i]);\n }\n else\n file = g_file_new_for_path (args[i]);\n }", " if (file && !flatpak_exports_path_is_visible (exports,\n flatpak_file_get_path_cached (file)))\n {\n g_autofree char *doc_id = NULL;\n g_autofree char *basename = NULL;\n g_autofree char *doc_path = NULL;\n if (!forward_file (documents, app_id, flatpak_file_get_path_cached (file),\n &doc_id, error))\n return FALSE;", " basename = g_file_get_basename (file);\n doc_path = g_build_filename (doc_mount_path, doc_id, basename, NULL);", " if (forwarding_uri)\n {\n g_autofree char *path = doc_path;\n doc_path = g_filename_to_uri (path, NULL, NULL);\n /* This should never fail */\n g_assert (doc_path != NULL);\n }", " g_debug (\"Forwarding file '%s' as '%s' to %s\", args[i], doc_path, app_id);\n flatpak_bwrap_add_arg (bwrap, doc_path);\n }\n else\n flatpak_bwrap_add_arg (bwrap, args[i]);\n }", " return TRUE;\n}", "FlatpakContext *\nflatpak_context_load_for_deploy (FlatpakDeploy *deploy,\n GError **error)\n{\n g_autoptr(FlatpakContext) context = NULL;\n g_autoptr(FlatpakContext) overrides = NULL;\n g_autoptr(GKeyFile) metakey = NULL;", " metakey = flatpak_deploy_get_metadata (deploy);\n context = flatpak_app_compute_permissions (metakey, NULL, error);\n if (context == NULL)\n return NULL;", " overrides = flatpak_deploy_get_overrides (deploy);\n flatpak_context_merge (context, overrides);", " return g_steal_pointer (&context);\n}", "static char *\ncalculate_ld_cache_checksum (GBytes *app_deploy_data,\n GBytes *runtime_deploy_data,\n const char *app_extensions,\n const char *runtime_extensions)\n{\n g_autoptr(GChecksum) ld_so_checksum = g_checksum_new (G_CHECKSUM_SHA256);\n if (app_deploy_data)\n g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (app_deploy_data), -1);\n g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (runtime_deploy_data), -1);\n if (app_extensions)\n g_checksum_update (ld_so_checksum, (guchar *) app_extensions, -1);\n if (runtime_extensions)\n g_checksum_update (ld_so_checksum, (guchar *) runtime_extensions, -1);", " return g_strdup (g_checksum_get_string (ld_so_checksum));\n}", "static gboolean\nadd_ld_so_conf (FlatpakBwrap *bwrap,\n GError **error)\n{\n const char *contents =\n \"include /run/flatpak/ld.so.conf.d/app-*.conf\\n\"\n \"include /app/etc/ld.so.conf\\n\"\n \"/app/lib\\n\"\n \"include /run/flatpak/ld.so.conf.d/runtime-*.conf\\n\";", " return flatpak_bwrap_add_args_data (bwrap, \"ld-so-conf\",\n contents, -1, \"/etc/ld.so.conf\", error);\n}", "static int\nregenerate_ld_cache (GPtrArray *base_argv_array,\n GArray *base_fd_array,\n GFile *app_id_dir,\n const char *checksum,\n GFile *runtime_files,\n gboolean generate_ld_so_conf,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(FlatpakBwrap) bwrap = NULL;\n g_autoptr(GArray) combined_fd_array = NULL;\n g_autoptr(GFile) ld_so_cache = NULL;\n g_autoptr(GFile) ld_so_cache_tmp = NULL;\n g_autofree char *sandbox_cache_path = NULL;\n g_autofree char *tmp_basename = NULL;\n g_auto(GStrv) minimal_envp = NULL;\n g_autofree char *commandline = NULL;\n int exit_status;\n glnx_autofd int ld_so_fd = -1;\n g_autoptr(GFile) ld_so_dir = NULL;", " if (app_id_dir)\n ld_so_dir = g_file_get_child (app_id_dir, \".ld.so\");\n else\n {\n g_autoptr(GFile) base_dir = g_file_new_for_path (g_get_user_cache_dir ());\n ld_so_dir = g_file_resolve_relative_path (base_dir, \"flatpak/ld.so\");\n }", " ld_so_cache = g_file_get_child (ld_so_dir, checksum);\n ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache), O_RDONLY);\n if (ld_so_fd >= 0)\n return glnx_steal_fd (&ld_so_fd);", " g_debug (\"Regenerating ld.so.cache %s\", flatpak_file_get_path_cached (ld_so_cache));", " if (!flatpak_mkdir_p (ld_so_dir, cancellable, error))\n return FALSE;", " minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);\n bwrap = flatpak_bwrap_new (minimal_envp);", " flatpak_bwrap_append_args (bwrap, base_argv_array);", " flatpak_run_setup_usr_links (bwrap, runtime_files);", " if (generate_ld_so_conf)\n {\n if (!add_ld_so_conf (bwrap, error))\n return -1;\n }\n else\n flatpak_bwrap_add_args (bwrap,\n \"--symlink\", \"../usr/etc/ld.so.conf\", \"/etc/ld.so.conf\",\n NULL);", " tmp_basename = g_strconcat (checksum, \".XXXXXX\", NULL);\n glnx_gen_temp_name (tmp_basename);", " sandbox_cache_path = g_build_filename (\"/run/ld-so-cache-dir\", tmp_basename, NULL);\n ld_so_cache_tmp = g_file_get_child (ld_so_dir, tmp_basename);", " flatpak_bwrap_add_args (bwrap,\n \"--unshare-pid\",\n \"--unshare-ipc\",\n \"--unshare-net\",\n \"--proc\", \"/proc\",\n \"--dev\", \"/dev\",\n \"--bind\", flatpak_file_get_path_cached (ld_so_dir), \"/run/ld-so-cache-dir\",\n NULL);", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return -1;", " flatpak_bwrap_add_args (bwrap,\n \"ldconfig\", \"-X\", \"-C\", sandbox_cache_path, NULL);", " flatpak_bwrap_finish (bwrap);", " commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);\n g_debug (\"Running: '%s'\", commandline);", " combined_fd_array = g_array_new (FALSE, TRUE, sizeof (int));\n g_array_append_vals (combined_fd_array, base_fd_array->data, base_fd_array->len);\n g_array_append_vals (combined_fd_array, bwrap->fds->data, bwrap->fds->len);", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_sync (NULL,\n (char **) bwrap->argv->pdata,\n bwrap->envp,\n G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n flatpak_bwrap_child_setup_cb, combined_fd_array,\n NULL, NULL,\n &exit_status,\n error))\n return -1;", " if (!WIFEXITED (exit_status) || WEXITSTATUS (exit_status) != 0)\n {\n flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,\n _(\"ldconfig failed, exit status %d\"), exit_status);\n return -1;\n }", " ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache_tmp), O_RDONLY);\n if (ld_so_fd < 0)\n {\n flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(\"Can't open generated ld.so.cache\"));\n return -1;\n }", " if (app_id_dir == NULL)\n {\n /* For runs without an app id dir we always regenerate the ld.so.cache */\n unlink (flatpak_file_get_path_cached (ld_so_cache_tmp));\n }\n else\n {\n g_autoptr(GFile) active = g_file_get_child (ld_so_dir, \"active\");", " /* For app-dirs we keep one checksum alive, by pointing the active symlink to it */", " /* Rename to known name, possibly overwriting existing ref if race */\n if (rename (flatpak_file_get_path_cached (ld_so_cache_tmp), flatpak_file_get_path_cached (ld_so_cache)) == -1)\n {\n glnx_set_error_from_errno (error);\n return -1;\n }", " if (!flatpak_switch_symlink_and_remove (flatpak_file_get_path_cached (active),\n checksum, error))\n return -1;\n }", " return glnx_steal_fd (&ld_so_fd);\n}", "/* Check that this user is actually allowed to run this app. When running\n * from the gnome-initial-setup session, an app filter might not be available. */\nstatic gboolean\ncheck_parental_controls (FlatpakDecomposed *app_ref,\n FlatpakDeploy *deploy,\n GCancellable *cancellable,\n GError **error)\n{\n#ifdef HAVE_LIBMALCONTENT\n g_autoptr(MctManager) manager = NULL;\n g_autoptr(MctAppFilter) app_filter = NULL;\n g_autoptr(GAsyncResult) app_filter_result = NULL;\n g_autoptr(GDBusConnection) system_bus = NULL;\n g_autoptr(GError) local_error = NULL;\n g_autoptr(GDesktopAppInfo) app_info = NULL;\n gboolean allowed = FALSE;", " system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);\n if (system_bus == NULL)\n return FALSE;", " manager = mct_manager_new (system_bus);\n app_filter = mct_manager_get_app_filter (manager, getuid (),\n MCT_GET_APP_FILTER_FLAGS_INTERACTIVE,\n cancellable, &local_error);\n if (g_error_matches (local_error, MCT_APP_FILTER_ERROR, MCT_APP_FILTER_ERROR_DISABLED))\n {\n g_debug (\"Skipping parental controls check for %s since parental \"\n \"controls are disabled globally\", flatpak_decomposed_get_ref (app_ref));\n return TRUE;\n }\n else if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN) ||\n g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_NAME_HAS_NO_OWNER))\n {\n g_debug (\"Skipping parental controls check for %s since a required \"\n \"service was not found\", flatpak_decomposed_get_ref (app_ref));\n return TRUE;\n }\n else if (local_error != NULL)\n {\n g_propagate_error (error, g_steal_pointer (&local_error));\n return FALSE;\n }", " /* Always filter by app ID. Additionally, filter by app info (which runs\n * multiple checks, including whether the app ID, executable path and\n * content types are allowed) if available. If the flatpak contains\n * multiple .desktop files, we use the main one. The app ID check is\n * always done, as the binary executed by `flatpak run` isn’t necessarily\n * extracted from a .desktop file. */\n allowed = mct_app_filter_is_flatpak_ref_allowed (app_filter, flatpak_decomposed_get_ref (app_ref));", " /* Look up the app’s main .desktop file. */\n if (deploy != NULL && allowed)\n {\n g_autoptr(GFile) deploy_dir = NULL;\n const char *deploy_path;\n g_autofree char *desktop_file_name = NULL;\n g_autofree char *desktop_file_path = NULL;\n g_autofree char *app_id = flatpak_decomposed_dup_id (app_ref);", " deploy_dir = flatpak_deploy_get_dir (deploy);\n deploy_path = flatpak_file_get_path_cached (deploy_dir);", " desktop_file_name = g_strconcat (app_id, \".desktop\", NULL);\n desktop_file_path = g_build_path (G_DIR_SEPARATOR_S,\n deploy_path,\n \"export\",\n \"share\",\n \"applications\",\n desktop_file_name,\n NULL);\n app_info = g_desktop_app_info_new_from_filename (desktop_file_path);\n }", " if (app_info != NULL)\n allowed = allowed && mct_app_filter_is_appinfo_allowed (app_filter,\n G_APP_INFO (app_info));", " if (!allowed)\n return flatpak_fail_error (error, FLATPAK_ERROR_PERMISSION_DENIED,\n /* Translators: The placeholder is for an app ref. */\n _(\"Running %s is not allowed by the policy set by your administrator\"),\n flatpak_decomposed_get_ref (app_ref));\n#endif /* HAVE_LIBMALCONTENT */", " return TRUE;\n}", "static int\nopen_namespace_fd_if_needed (const char *path,\n const char *other_path) {\n struct stat s, other_s;", " if (stat (path, &s) != 0)\n return -1; /* No such namespace, ignore */", " if (stat (other_path, &other_s) != 0)\n return -1; /* No such namespace, ignore */", " /* setns calls fail if the process is already in the desired namespace, hence the\n check here to ensure the namespaces are different. */\n if (s.st_ino != other_s.st_ino)\n return open (path, O_RDONLY|O_CLOEXEC);", " return -1;\n}", "static gboolean\ncheck_sudo (GError **error)\n{\n const char *sudo_command_env = g_getenv (\"SUDO_COMMAND\");\n g_auto(GStrv) split_command = NULL;", " /* This check exists to stop accidental usage of `sudo flatpak run`\n and is not to prevent running as root.\n */", " if (!sudo_command_env)\n return TRUE;", " /* SUDO_COMMAND could be a value like `/usr/bin/flatpak run foo` */\n split_command = g_strsplit (sudo_command_env, \" \", 2);\n if (g_str_has_suffix (split_command[0], \"flatpak\"))\n return flatpak_fail_error (error, FLATPAK_ERROR, _(\"\\\"flatpak run\\\" is not intended to be ran with sudo\"));", " return TRUE;\n}", "gboolean\nflatpak_run_app (FlatpakDecomposed *app_ref,\n FlatpakDeploy *app_deploy,\n FlatpakContext *extra_context,\n const char *custom_runtime,\n const char *custom_runtime_version,\n const char *custom_runtime_commit,\n int parent_pid,\n FlatpakRunFlags flags,\n const char *cwd,\n const char *custom_command,\n char *args[],\n int n_args,\n int instance_id_fd,\n char **instance_dir_out,\n GCancellable *cancellable,\n GError **error)\n{\n g_autoptr(FlatpakDeploy) runtime_deploy = NULL;\n g_autoptr(GBytes) runtime_deploy_data = NULL;\n g_autoptr(GBytes) app_deploy_data = NULL;\n g_autoptr(GFile) app_files = NULL;\n g_autoptr(GFile) runtime_files = NULL;\n g_autoptr(GFile) bin_ldconfig = NULL;\n g_autoptr(GFile) app_id_dir = NULL;\n g_autoptr(GFile) real_app_id_dir = NULL;\n g_autofree char *default_runtime_pref = NULL;\n g_autoptr(FlatpakDecomposed) default_runtime = NULL;\n g_autofree char *default_command = NULL;\n g_autoptr(GKeyFile) metakey = NULL;\n g_autoptr(GKeyFile) runtime_metakey = NULL;\n g_autoptr(FlatpakBwrap) bwrap = NULL;\n const char *command = \"/bin/sh\";\n g_autoptr(GError) my_error = NULL;\n g_autoptr(FlatpakDecomposed) runtime_ref = NULL;\n int i;\n g_autoptr(GPtrArray) previous_app_id_dirs = NULL;\n g_autofree char *app_id = NULL;\n g_autofree char *app_arch = NULL;\n g_autofree char *app_info_path = NULL;\n g_autofree char *instance_id_host_dir = NULL;\n g_autoptr(FlatpakContext) app_context = NULL;\n g_autoptr(FlatpakContext) overrides = NULL;\n g_autoptr(FlatpakExports) exports = NULL;\n g_autofree char *commandline = NULL;\n g_autofree char *doc_mount_path = NULL;\n g_autofree char *app_extensions = NULL;\n g_autofree char *runtime_extensions = NULL;\n g_autofree char *checksum = NULL;\n int ld_so_fd = -1;\n g_autoptr(GFile) runtime_ld_so_conf = NULL;\n gboolean generate_ld_so_conf = TRUE;\n gboolean use_ld_so_cache = TRUE;\n gboolean sandboxed = (flags & FLATPAK_RUN_FLAG_SANDBOX) != 0;\n gboolean parent_expose_pids = (flags & FLATPAK_RUN_FLAG_PARENT_EXPOSE_PIDS) != 0;\n gboolean parent_share_pids = (flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS) != 0;\n struct stat s;", " if (!check_sudo (error))\n return FALSE;", " app_id = flatpak_decomposed_dup_id (app_ref);\n app_arch = flatpak_decomposed_dup_arch (app_ref);", " /* Check the user is allowed to run this flatpak. */\n if (!check_parental_controls (app_ref, app_deploy, cancellable, error))\n return FALSE;", " /* Construct the bwrap context. */\n bwrap = flatpak_bwrap_new (NULL);\n flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());", " if (app_deploy == NULL)\n {\n g_assert (flatpak_decomposed_is_runtime (app_ref));\n default_runtime_pref = flatpak_decomposed_dup_pref (app_ref);\n }\n else\n {\n const gchar *key;", " app_deploy_data = flatpak_deploy_get_deploy_data (app_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);\n if (app_deploy_data == NULL)\n return FALSE;", " if ((flags & FLATPAK_RUN_FLAG_DEVEL) != 0)\n key = FLATPAK_METADATA_KEY_SDK;\n else\n key = FLATPAK_METADATA_KEY_RUNTIME;", " metakey = flatpak_deploy_get_metadata (app_deploy);\n default_runtime_pref = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_APPLICATION,\n key, &my_error);\n if (my_error)\n {\n g_propagate_error (error, g_steal_pointer (&my_error));\n return FALSE;\n }\n }", " default_runtime = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, default_runtime_pref, error);\n if (default_runtime == NULL)\n return FALSE;", " if (custom_runtime != NULL || custom_runtime_version != NULL)\n {\n g_auto(GStrv) custom_runtime_parts = NULL;\n const char *custom_runtime_id = NULL;\n const char *custom_runtime_arch = NULL;", " if (custom_runtime)\n {\n custom_runtime_parts = g_strsplit (custom_runtime, \"/\", 0);\n for (i = 0; i < 3 && custom_runtime_parts[i] != NULL; i++)\n {\n if (strlen (custom_runtime_parts[i]) > 0)\n {\n if (i == 0)\n custom_runtime_id = custom_runtime_parts[i];\n if (i == 1)\n custom_runtime_arch = custom_runtime_parts[i];", " if (i == 2 && custom_runtime_version == NULL)\n custom_runtime_version = custom_runtime_parts[i];\n }\n }\n }", " runtime_ref = flatpak_decomposed_new_from_decomposed (default_runtime,\n FLATPAK_KINDS_RUNTIME,\n custom_runtime_id,\n custom_runtime_arch,\n custom_runtime_version,\n error);\n if (runtime_ref == NULL)\n return FALSE;\n }\n else\n runtime_ref = flatpak_decomposed_ref (default_runtime);", " runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), custom_runtime_commit, NULL, cancellable, error);\n if (runtime_deploy == NULL)\n return FALSE;", " runtime_deploy_data = flatpak_deploy_get_deploy_data (runtime_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);\n if (runtime_deploy_data == NULL)\n return FALSE;", " runtime_metakey = flatpak_deploy_get_metadata (runtime_deploy);", " app_context = flatpak_app_compute_permissions (metakey, runtime_metakey, error);\n if (app_context == NULL)\n return FALSE;", " if (app_deploy != NULL)\n {\n overrides = flatpak_deploy_get_overrides (app_deploy);\n flatpak_context_merge (app_context, overrides);\n }", " if (sandboxed)\n flatpak_context_make_sandboxed (app_context);", " if (extra_context)\n flatpak_context_merge (app_context, extra_context);", " runtime_files = flatpak_deploy_get_files (runtime_deploy);\n bin_ldconfig = g_file_resolve_relative_path (runtime_files, \"bin/ldconfig\");\n if (!g_file_query_exists (bin_ldconfig, NULL))\n use_ld_so_cache = FALSE;", " if (app_deploy != NULL)\n {\n g_autofree const char **previous_ids = NULL;\n gsize len = 0;\n gboolean do_migrate;", " real_app_id_dir = flatpak_get_data_dir (app_id);\n app_files = flatpak_deploy_get_files (app_deploy);", " previous_app_id_dirs = g_ptr_array_new_with_free_func (g_object_unref);\n previous_ids = flatpak_deploy_data_get_previous_ids (app_deploy_data, &len);", " do_migrate = !g_file_query_exists (real_app_id_dir, cancellable);", " /* When migrating, find most recent old existing source and rename that to\n * the new name.\n *\n * We ignore other names than that. For more recent names that don't exist\n * we never ran them so nothing will even reference them. For older names\n * either they were not used, or they were used but then the more recent\n * name was used and a symlink to it was created.\n *\n * This means we may end up with a chain of symlinks: oldest -> old -> current.\n * This is unfortunate but not really a problem, but for robustness reasons we\n * don't want to mess with user files unnecessary. For example, the app dir could\n * actually be a symlink for other reasons. Imagine for instance that you want to put the\n * steam games somewhere else so you leave the app dir as a symlink to /mnt/steam.\n */\n for (i = len - 1; i >= 0; i--)\n {\n g_autoptr(GFile) previous_app_id_dir = NULL;\n g_autoptr(GFileInfo) previous_app_id_dir_info = NULL;\n g_autoptr(GError) local_error = NULL;", " previous_app_id_dir = flatpak_get_data_dir (previous_ids[i]);\n previous_app_id_dir_info = g_file_query_info (previous_app_id_dir,\n G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK \",\"\n G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,\n G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,\n cancellable,\n &local_error);\n /* Warn about the migration failures, but don't make them fatal, then you can never run the app */\n if (previous_app_id_dir_info == NULL)\n {\n if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) && do_migrate)\n {\n g_warning (_(\"Failed to migrate from %s: %s\"), flatpak_file_get_path_cached (previous_app_id_dir),\n local_error->message);\n do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to the thing that we failed on */\n }", " g_clear_error (&local_error);\n continue;\n }", " if (do_migrate)\n {\n do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to this dir */", " if (!flatpak_file_rename (previous_app_id_dir, real_app_id_dir, cancellable, &local_error))\n {\n g_warning (_(\"Failed to migrate old app data directory %s to new name %s: %s\"),\n flatpak_file_get_path_cached (previous_app_id_dir), app_id,\n local_error->message);\n }\n else\n {\n /* Leave a symlink in place of the old data dir */\n if (!g_file_make_symbolic_link (previous_app_id_dir, app_id, cancellable, &local_error))\n {\n g_warning (_(\"Failed to create symlink while migrating %s: %s\"),\n flatpak_file_get_path_cached (previous_app_id_dir),\n local_error->message);\n }\n }\n }", " /* Give app access to this old dir */\n g_ptr_array_add (previous_app_id_dirs, g_steal_pointer (&previous_app_id_dir));\n }", " if (!flatpak_ensure_data_dir (real_app_id_dir, cancellable, error))\n return FALSE;", " if (!sandboxed)\n app_id_dir = g_object_ref (real_app_id_dir);\n }", " flatpak_run_apply_env_default (bwrap, use_ld_so_cache);\n flatpak_run_apply_env_vars (bwrap, app_context);\n flatpak_run_apply_env_prompt (bwrap, app_id);", " if (real_app_id_dir)\n {\n g_autoptr(GFile) sandbox_dir = g_file_get_child (real_app_id_dir, \"sandbox\");\n flatpak_bwrap_set_env (bwrap, \"FLATPAK_SANDBOX_DIR\", flatpak_file_get_path_cached (sandbox_dir), TRUE);\n }", " flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (runtime_files), \"/usr\",\n \"--lock-file\", \"/usr/.ref\",\n NULL);", " if (app_files != NULL)\n flatpak_bwrap_add_args (bwrap,\n \"--ro-bind\", flatpak_file_get_path_cached (app_files), \"/app\",\n \"--lock-file\", \"/app/.ref\",\n NULL);\n else\n flatpak_bwrap_add_args (bwrap,\n \"--dir\", \"/app\",\n NULL);", " if (metakey != NULL &&\n !flatpak_run_add_extension_args (bwrap, metakey, app_ref, use_ld_so_cache, &app_extensions, cancellable, error))\n return FALSE;", " if (!flatpak_run_add_extension_args (bwrap, runtime_metakey, runtime_ref, use_ld_so_cache, &runtime_extensions, cancellable, error))\n return FALSE;", " runtime_ld_so_conf = g_file_resolve_relative_path (runtime_files, \"etc/ld.so.conf\");\n if (lstat (flatpak_file_get_path_cached (runtime_ld_so_conf), &s) == 0)\n generate_ld_so_conf = S_ISREG (s.st_mode) && s.st_size == 0;", " /* At this point we have the minimal argv set up, with just the app, runtime and extensions.\n We can reuse this to generate the ld.so.cache (if needed) */\n if (use_ld_so_cache)\n {\n checksum = calculate_ld_cache_checksum (app_deploy_data, runtime_deploy_data,\n app_extensions, runtime_extensions);\n ld_so_fd = regenerate_ld_cache (bwrap->argv,\n bwrap->fds,\n app_id_dir,\n checksum,\n runtime_files,\n generate_ld_so_conf,\n cancellable, error);\n if (ld_so_fd == -1)\n return FALSE;\n flatpak_bwrap_add_fd (bwrap, ld_so_fd);\n }", " flags |= flatpak_context_get_run_flags (app_context);", " if (!flatpak_run_setup_base_argv (bwrap, runtime_files, app_id_dir, app_arch, flags, error))\n return FALSE;", " if (generate_ld_so_conf)\n {\n if (!add_ld_so_conf (bwrap, error))\n return FALSE;\n }", " if (ld_so_fd != -1)\n {\n /* Don't add to fd_array, its already there */\n flatpak_bwrap_add_arg (bwrap, \"--ro-bind-data\");\n flatpak_bwrap_add_arg_printf (bwrap, \"%d\", ld_so_fd);\n flatpak_bwrap_add_arg (bwrap, \"/etc/ld.so.cache\");\n }", " if (!flatpak_run_add_app_info_args (bwrap,\n app_files, app_deploy_data, app_extensions,\n runtime_files, runtime_deploy_data, runtime_extensions,\n app_id, flatpak_decomposed_get_branch (app_ref),\n runtime_ref, app_id_dir, app_context, extra_context,\n sandboxed, FALSE, flags & FLATPAK_RUN_FLAG_DEVEL,\n &app_info_path, instance_id_fd, &instance_id_host_dir,\n error))\n return FALSE;", " if (!flatpak_run_add_dconf_args (bwrap, app_id, metakey, error))\n return FALSE;", " if (!sandboxed && !(flags & FLATPAK_RUN_FLAG_NO_DOCUMENTS_PORTAL))\n add_document_portal_args (bwrap, app_id, &doc_mount_path);", " if (!flatpak_run_add_environment_args (bwrap, app_info_path, flags,\n app_id, app_context, app_id_dir, previous_app_id_dirs,\n &exports, cancellable, error))\n return FALSE;", " if ((app_context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) != 0)\n flatpak_run_add_resolved_args (bwrap);", " flatpak_run_add_journal_args (bwrap);\n add_font_path_args (bwrap);\n add_icon_path_args (bwrap);", " flatpak_bwrap_add_args (bwrap,\n /* Not in base, because we don't want this for flatpak build */\n \"--symlink\", \"/app/lib/debug/source\", \"/run/build\",\n \"--symlink\", \"/usr/lib/debug/source\", \"/run/build-runtime\",\n NULL);", " if (cwd)\n flatpak_bwrap_add_args (bwrap, \"--chdir\", cwd, NULL);", " if (parent_expose_pids || parent_share_pids)\n {\n g_autofree char *userns_path = NULL;\n g_autofree char *pidns_path = NULL;\n g_autofree char *userns2_path = NULL;\n int userns_fd, userns2_fd, pidns_fd;", " if (parent_pid == 0)\n return flatpak_fail (error, \"No parent pid specified\");", " userns_path = g_strdup_printf (\"/proc/%d/root/run/.userns\", parent_pid);", " userns_fd = open_namespace_fd_if_needed (userns_path, \"/proc/self/ns/user\");\n if (userns_fd != -1)\n {\n flatpak_bwrap_add_args_data_fd (bwrap, \"--userns\", userns_fd, NULL);", " userns2_path = g_strdup_printf (\"/proc/%d/ns/user\", parent_pid);\n userns2_fd = open_namespace_fd_if_needed (userns2_path, userns_path);\n if (userns2_fd != -1)\n flatpak_bwrap_add_args_data_fd (bwrap, \"--userns2\", userns2_fd, NULL);\n }", " pidns_path = g_strdup_printf (\"/proc/%d/ns/pid\", parent_pid);\n pidns_fd = open (pidns_path, O_RDONLY|O_CLOEXEC);\n if (pidns_fd != -1)\n flatpak_bwrap_add_args_data_fd (bwrap, \"--pidns\", pidns_fd, NULL);\n }", " if (custom_command)\n {\n command = custom_command;\n }\n else if (metakey)\n {\n default_command = g_key_file_get_string (metakey,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_COMMAND,\n &my_error);\n if (my_error)\n {\n g_propagate_error (error, g_steal_pointer (&my_error));\n return FALSE;\n }\n command = default_command;\n }\n", " flatpak_bwrap_envp_to_args (bwrap);\n", " if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))\n return FALSE;", " flatpak_bwrap_add_arg (bwrap, command);", " if (!add_rest_args (bwrap, app_id,\n exports, (flags & FLATPAK_RUN_FLAG_FILE_FORWARDING) != 0,\n doc_mount_path,\n args, n_args, error))\n return FALSE;", " flatpak_bwrap_finish (bwrap);", " commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);\n g_debug (\"Running '%s'\", commandline);", " if ((flags & FLATPAK_RUN_FLAG_BACKGROUND) != 0)\n {\n GPid child_pid;\n char pid_str[64];\n g_autofree char *pid_path = NULL;\n GSpawnFlags spawn_flags;", " spawn_flags = G_SPAWN_SEARCH_PATH;\n if (flags & FLATPAK_RUN_FLAG_DO_NOT_REAP)\n spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;", " /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;", "\n /* flatpak_bwrap_envp_to_args() moved the environment variables to\n * be set into --setenv instructions in argv, so the environment\n * in which the bwrap command runs must be empty. */\n g_assert (bwrap->envp != NULL);\n g_assert (bwrap->envp[0] == NULL);", "\n if (!g_spawn_async (NULL,\n (char **) bwrap->argv->pdata,\n bwrap->envp,\n spawn_flags,\n flatpak_bwrap_child_setup_cb, bwrap->fds,\n &child_pid,\n error))\n return FALSE;", " g_snprintf (pid_str, sizeof (pid_str), \"%d\", child_pid);\n pid_path = g_build_filename (instance_id_host_dir, \"pid\", NULL);\n g_file_set_contents (pid_path, pid_str, -1, NULL);\n }\n else\n {\n char pid_str[64];\n g_autofree char *pid_path = NULL;", " g_snprintf (pid_str, sizeof (pid_str), \"%d\", getpid ());\n pid_path = g_build_filename (instance_id_host_dir, \"pid\", NULL);\n g_file_set_contents (pid_path, pid_str, -1, NULL);", " /* Ensure we unset O_CLOEXEC for marked fds and rewind fds as needed.\n * Note that this does not close fds that are not already marked O_CLOEXEC, because\n * we do want to allow inheriting fds into flatpak run. */\n flatpak_bwrap_child_setup (bwrap->fds, FALSE);\n", " /* flatpak_bwrap_envp_to_args() moved the environment variables to\n * be set into --setenv instructions in argv, so the environment\n * in which the bwrap command runs must be empty. */\n g_assert (bwrap->envp != NULL);\n g_assert (bwrap->envp[0] == NULL);\n", " if (execvpe (flatpak_get_bwrap (), (char **) bwrap->argv->pdata, bwrap->envp) == -1)\n {\n g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),\n _(\"Unable to start app\"));\n return FALSE;\n }\n /* Not actually reached... */\n }", " if (instance_dir_out)\n *instance_dir_out = g_steal_pointer (&instance_id_host_dir);", " return TRUE;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [75, 276, 4127], "buggy_code_start_loc": [45, 111, 1465], "filenames": ["common/flatpak-bwrap-private.h", "common/flatpak-bwrap.c", "common/flatpak-run.c"], "fixing_code_end_loc": [79, 320, 4124], "fixing_code_start_loc": [46, 112, 1464], "message": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "041D999E-622C-4771-9819-57C6F1BE7056", "versionEndExcluding": "1.8.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.11.4", "vulnerable": true}, {"criteria": "cpe:2.3:a:flatpak:flatpak:*:*:*:*:*:*:*:*", "matchCriteriaId": "FD8B7A39-7AB9-43AA-9B31-B2112B6D90CF", "versionEndExcluding": "1.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "1.9.1", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Flatpak is a system for building, distributing, and running sandboxed desktop applications on Linux. A bug was discovered in the `flatpak-portal` service that can allow sandboxed applications to execute arbitrary code on the host system (a sandbox escape). This sandbox-escape bug is present in versions from 0.11.4 and before fixed versions 1.8.5 and 1.10.0. The Flatpak portal D-Bus service (`flatpak-portal`, also known by its D-Bus service name `org.freedesktop.portal.Flatpak`) allows apps in a Flatpak sandbox to launch their own subprocesses in a new sandbox instance, either with the same security settings as the caller or with more restrictive security settings. For example, this is used in Flatpak-packaged web browsers such as Chromium to launch subprocesses that will process untrusted web content, and give those subprocesses a more restrictive sandbox than the browser itself. In vulnerable versions, the Flatpak portal service passes caller-specified environment variables to non-sandboxed processes on the host system, and in particular to the `flatpak run` command that is used to launch the new sandbox instance. A malicious or compromised Flatpak app could set environment variables that are trusted by the `flatpak run` command, and use them to execute arbitrary code that is not in a sandbox. As a workaround, this vulnerability can be mitigated by preventing the `flatpak-portal` service from starting, but that mitigation will prevent many Flatpak apps from working correctly. This is fixed in versions 1.8.5 and 1.10.0."}, {"lang": "es", "value": "Flatpak es un sistema para crear, distribuir y ejecutar aplicaciones de escritorio en sandbox en Linux. Se detect\u00f3 un fallo en el servicio \"flatpak-portal\" que puede permitir que las aplicaciones en sandbox ejecuten c\u00f3digo arbitrario en el sistema host (un escape del sandbox). Este fallo de escape del sandbox est\u00e1 presente en las versiones 0.11.4 y anteriores a las versiones reparadas 1.8.5 y 1.10.0. El servicio D-Bus del portal Flatpak (\"flatpak-portal\", tambi\u00e9n conocido por su nombre de servicio D-Bus \"org.freedesktop.portal.Flatpak\") permite que las aplicaciones en un sandbox de Flatpak inicien sus propios subprocesos en una nueva instancia del sandbox, ya sea con la misma configuraci\u00f3n de seguridad que la persona que llama o con una configuraci\u00f3n de seguridad m\u00e1s restrictiva. Por ejemplo, esto se usa en navegadores web empaquetados con Flatpak, como Chromium, para iniciar subprocesos que procesar\u00e1n contenido web no confiable. y dar a esos subprocesos un sandbox m\u00e1s restrictivo que el propio navegador. En versiones vulnerables, el servicio del portal Flatpak pasa las variables de entorno especificadas por la persona que llama hacia procesos que no est\u00e1n en el sandbox en el sistema host y, en particular, al comando \"flatpak run\" que se usa para iniciar la nueva instancia del sandbox. Una aplicaci\u00f3n Flatpak maliciosa o comprometida podr\u00eda establecer variables de entorno en las que conf\u00ede el comando \"flatpak run\" y usarlas para ejecutar c\u00f3digo arbitrario que no se encuentra en un sandbox. Como soluci\u00f3n alternativa, esta vulnerabilidad puede ser mitigada evitando que se inicie el servicio \"flatpak-portal\", pero esa mitigaci\u00f3n impedir\u00e1 que muchas aplicaciones de Flatpak funcionen correctamente. Esto se corrige en las versiones 1.8.5 y 1.10.0"}], "evaluatorComment": null, "id": "CVE-2021-21261", "lastModified": "2021-01-27T19:34:12.467", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.2, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:L/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 6.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 7.3, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.0, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-14T20:15:12.360", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/6e5ae7a109cdfa9735ea7ccbd8cb79f9e8d3ae8b"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/aeb6a7ab0abaac4a8f4ad98b3df476d9de6b8bd4"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/commit/cc1401043c075268ecc652eac557ef8076b5eaba"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/releases/tag/1.8.5"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/202101-21"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4830"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/flatpak/flatpak/commit/6d1773d2a54dde9b099043f07a2094a4f1c2f486"}, "type": "CWE-74"}
121
Determine whether the {function_name} code is vulnerable or not.
[ "", "2016-05-03 7.0.1-1 Cristy <quetzlzacatenango@image...>\n * New version 7.0.1-1, GIT revision 10723:9fc8a0c:20160503.", "2016-05-03 7.0.1-1 Cristy <quetzlzacatenango@image...>\n * Sanitize input filename for http / https delegates (improved patch).\n * Fix for possible security vulnerabilities (reference\n https://www.imagemagick.org/discourse-server/viewtopic.php?f=4&t=29588).", "2016-04-30 7.0.1-0 Cristy <quetzlzacatenango@image...>\n * New version 7.0.1-0, GIT revision 10716:b527bce:20160430.", "2016-01-30 7.0.0-0 \tFahad-Alsaidi & ShamsaHamed\n * Add support for languages that require complex text layout (reference\n https://github.com/ImageMagick/ImageMagick/pull/88).", "2012-04-27 7.0.0-0 Anthony thyssen <A.Thyssen@griffith...>\n * Allow the use of set and escapes when no images in memory\n (unless you attempt to access per-image meta-data)\n Currently does not include %[fx:...] and %[pixel:...]", "2012-10-05 7.0.0-0 Anthony thyssen <A.Thyssen@griffith...>\n * Rather than replicate 'options' into 'artifacts' make a link\n from image to image_info and lookup a global option if no artifact\n is defined.", "2012-09-11 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * sigmoidal-contrast:\n * Remove unnecessary initial ClampToQuantum.", "2012-09-10 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * sigmoidal-contrast:\n * Direct computation, without LUT;\n * Fix re-declaration of i (at the top, and inside a conditional).", "2012-09-04 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * Add tanh/atanh clone of legacy sigmoidal map (faster & more accurate).", "2012-08-08 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * Add final ClampToQuantum in sigmoidal colormap loop.\n * Remove OpenMP calls from colormap update loops.", "2011-08-01 7.0.0-0 Cristy <quetzlzacatenango@image...>\n * New version 7.0.0-0." ]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [0, 6060], "buggy_code_start_loc": [0, 1434], "filenames": ["ChangeLog", "MagickCore/draw.c"], "fixing_code_end_loc": [4, 6073], "fixing_code_start_loc": [1, 1434], "message": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "FEF4935E-1F84-4394-A897-30F56CDC0B1A", "versionEndExcluding": null, "versionEndIncluding": "6.9.3-0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.0-0:*:*:*:*:*:*:*", "matchCriteriaId": "3B7CCC6B-C66E-48E2-BA1E-CBF6421B4FEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-0:*:*:*:*:*:*:*", "matchCriteriaId": "693C9F8F-A8C1-4D06-8F31-E085E16E701C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-1:*:*:*:*:*:*:*", "matchCriteriaId": "6D3D3DFC-8459-41BA-BF3E-AE84E48FCEE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file."}, {"lang": "es", "value": "La funci\u00f3n DrawDashPolygon en MagickCore/draw.c en ImageMagick en versiones anteriores a 6.9.4-0 y 7.x en versiones anteriores a 7.0.1-2 no maneja correctamente los c\u00e1lculos de ciertos v\u00e9rtices de datos integrados, lo que permite a atacantes remotos provocar una denegaci\u00f3n de servicio (desbordamiento de buffer y ca\u00edda de aplicaci\u00f3n) o posiblemente tener otro impacto no especificado a trav\u00e9s de un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2016-4562", "lastModified": "2016-09-23T02:00:17.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-06-04T16:59:00.140", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.imagemagick.org/script/changelog.php"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.oracle.com/technetwork/topics/security/bulletinjul2016-3090568.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}, "type": "CWE-119"}
122
Determine whether the {function_name} code is vulnerable or not.
[ "2016-05-04 7.0.1-2 Cristy <quetzlzacatenango@image...>\n * Check for buffer overflow in magick/draw.c/DrawStrokePolygon().\n", "2016-05-03 7.0.1-1 Cristy <quetzlzacatenango@image...>\n * New version 7.0.1-1, GIT revision 10723:9fc8a0c:20160503.", "2016-05-03 7.0.1-1 Cristy <quetzlzacatenango@image...>\n * Sanitize input filename for http / https delegates (improved patch).\n * Fix for possible security vulnerabilities (reference\n https://www.imagemagick.org/discourse-server/viewtopic.php?f=4&t=29588).", "2016-04-30 7.0.1-0 Cristy <quetzlzacatenango@image...>\n * New version 7.0.1-0, GIT revision 10716:b527bce:20160430.", "2016-01-30 7.0.0-0 \tFahad-Alsaidi & ShamsaHamed\n * Add support for languages that require complex text layout (reference\n https://github.com/ImageMagick/ImageMagick/pull/88).", "2012-04-27 7.0.0-0 Anthony thyssen <A.Thyssen@griffith...>\n * Allow the use of set and escapes when no images in memory\n (unless you attempt to access per-image meta-data)\n Currently does not include %[fx:...] and %[pixel:...]", "2012-10-05 7.0.0-0 Anthony thyssen <A.Thyssen@griffith...>\n * Rather than replicate 'options' into 'artifacts' make a link\n from image to image_info and lookup a global option if no artifact\n is defined.", "2012-09-11 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * sigmoidal-contrast:\n * Remove unnecessary initial ClampToQuantum.", "2012-09-10 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * sigmoidal-contrast:\n * Direct computation, without LUT;\n * Fix re-declaration of i (at the top, and inside a conditional).", "2012-09-04 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * Add tanh/atanh clone of legacy sigmoidal map (faster & more accurate).", "2012-08-08 7.0.0-0 Nicolas Robidoux <nicolas.robidoux@gmail...>\n * Add final ClampToQuantum in sigmoidal colormap loop.\n * Remove OpenMP calls from colormap update loops.", "2011-08-01 7.0.0-0 Cristy <quetzlzacatenango@image...>\n * New version 7.0.0-0." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [0, 6060], "buggy_code_start_loc": [0, 1434], "filenames": ["ChangeLog", "MagickCore/draw.c"], "fixing_code_end_loc": [4, 6073], "fixing_code_start_loc": [1, 1434], "message": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "FEF4935E-1F84-4394-A897-30F56CDC0B1A", "versionEndExcluding": null, "versionEndIncluding": "6.9.3-0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.0-0:*:*:*:*:*:*:*", "matchCriteriaId": "3B7CCC6B-C66E-48E2-BA1E-CBF6421B4FEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-0:*:*:*:*:*:*:*", "matchCriteriaId": "693C9F8F-A8C1-4D06-8F31-E085E16E701C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-1:*:*:*:*:*:*:*", "matchCriteriaId": "6D3D3DFC-8459-41BA-BF3E-AE84E48FCEE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file."}, {"lang": "es", "value": "La funci\u00f3n DrawDashPolygon en MagickCore/draw.c en ImageMagick en versiones anteriores a 6.9.4-0 y 7.x en versiones anteriores a 7.0.1-2 no maneja correctamente los c\u00e1lculos de ciertos v\u00e9rtices de datos integrados, lo que permite a atacantes remotos provocar una denegaci\u00f3n de servicio (desbordamiento de buffer y ca\u00edda de aplicaci\u00f3n) o posiblemente tener otro impacto no especificado a trav\u00e9s de un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2016-4562", "lastModified": "2016-09-23T02:00:17.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-06-04T16:59:00.140", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.imagemagick.org/script/changelog.php"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.oracle.com/technetwork/topics/security/bulletinjul2016-3090568.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}, "type": "CWE-119"}
122
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% DDDD RRRR AAA W W %\n% D D R R A A W W %\n% D D RRRR AAAAA W W W %\n% D D R RN A A WW WW %\n% DDDD R R A A W W %\n% %\n% %\n% MagickCore Image Drawing Methods %\n% %\n% %\n% Software Design %\n% Cristy %\n% July 1998 %\n% %\n% %\n% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% http://www.imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon\n% rendering code based on Paul Heckbert's \"Concave Polygon Scan Conversion\",\n% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent\n% (www.appligent.com) contributed the dash pattern, linecap stroking\n% algorithm, and minor rendering improvements.\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/annotate.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/cache-view.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/color.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/composite.h\"\n#include \"MagickCore/composite-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/draw.h\"\n#include \"MagickCore/draw-private.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/gem.h\"\n#include \"MagickCore/geometry.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/paint.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/pixel-private.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/resample.h\"\n#include \"MagickCore/resample-private.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#include \"MagickCore/token.h\"\n#include \"MagickCore/transform-private.h\"\n#include \"MagickCore/utility.h\"\n\f\n/*\n Define declarations.\n*/\n#define BezierQuantum 200\n\f\n/*\n Typedef declarations.\n*/\ntypedef struct _EdgeInfo\n{\n SegmentInfo\n bounds;", " double\n scanline;", " PointInfo\n *points;", " size_t\n number_points;", " ssize_t\n direction;", " MagickBooleanType\n ghostline;", " size_t\n highwater;\n} EdgeInfo;", "typedef struct _ElementInfo\n{\n double\n cx,\n cy,\n major,\n minor,\n angle;\n} ElementInfo;", "typedef struct _PolygonInfo\n{\n EdgeInfo\n *edges;", " size_t\n number_edges;\n} PolygonInfo;", "typedef enum\n{\n MoveToCode,\n OpenCode,\n GhostlineCode,\n LineToCode,\n EndCode\n} PathInfoCode;", "typedef struct _PathInfo\n{\n PointInfo\n point;", " PathInfoCode\n code;\n} PathInfo;\n\f\n/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,\n ExceptionInfo *);", "static PrimitiveInfo\n *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);", "static size_t\n TracePath(PrimitiveInfo *,const char *);", "static void\n TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),\n TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,\n const double,const MagickBooleanType,const MagickBooleanType),\n TraceBezier(PrimitiveInfo *,const size_t),\n TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,\n const PointInfo),\n TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,\n PointInfo),\n TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% A c q u i r e D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% AcquireDrawInfo() returns a DrawInfo structure properly initialized.\n%\n% The format of the AcquireDrawInfo method is:\n%\n% DrawInfo *AcquireDrawInfo(void)\n%\n*/\nMagickExport DrawInfo *AcquireDrawInfo(void)\n{\n DrawInfo\n *draw_info;", " draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));\n if (draw_info == (DrawInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n GetDrawInfo((ImageInfo *) NULL,draw_info);\n return(draw_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% C l o n e D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL\n% is specified, a new DrawInfo structure is created initialized to default\n% values.\n%\n% The format of the CloneDrawInfo method is:\n%\n% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,\n% const DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,\n const DrawInfo *draw_info)\n{\n DrawInfo\n *clone_info;", " ExceptionInfo\n *exception;", " clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));\n if (clone_info == (DrawInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n GetDrawInfo(image_info,clone_info);\n if (draw_info == (DrawInfo *) NULL)\n return(clone_info);\n exception=AcquireExceptionInfo();\n if (clone_info->primitive != (char *) NULL)\n (void) CloneString(&clone_info->primitive,draw_info->primitive);\n if (draw_info->geometry != (char *) NULL)\n (void) CloneString(&clone_info->geometry,draw_info->geometry);\n clone_info->viewbox=draw_info->viewbox;\n clone_info->affine=draw_info->affine;\n clone_info->gravity=draw_info->gravity;\n clone_info->fill=draw_info->fill;\n clone_info->stroke=draw_info->stroke;\n clone_info->stroke_width=draw_info->stroke_width;\n if (draw_info->fill_pattern != (Image *) NULL)\n clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,\n exception);\n if (draw_info->stroke_pattern != (Image *) NULL)\n clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,\n MagickTrue,exception);\n clone_info->stroke_antialias=draw_info->stroke_antialias;\n clone_info->text_antialias=draw_info->text_antialias;\n clone_info->fill_rule=draw_info->fill_rule;\n clone_info->linecap=draw_info->linecap;\n clone_info->linejoin=draw_info->linejoin;\n clone_info->miterlimit=draw_info->miterlimit;\n clone_info->dash_offset=draw_info->dash_offset;\n clone_info->decorate=draw_info->decorate;\n clone_info->compose=draw_info->compose;\n if (draw_info->text != (char *) NULL)\n (void) CloneString(&clone_info->text,draw_info->text);\n if (draw_info->font != (char *) NULL)\n (void) CloneString(&clone_info->font,draw_info->font);\n if (draw_info->metrics != (char *) NULL)\n (void) CloneString(&clone_info->metrics,draw_info->metrics);\n if (draw_info->family != (char *) NULL)\n (void) CloneString(&clone_info->family,draw_info->family);\n clone_info->style=draw_info->style;\n clone_info->stretch=draw_info->stretch;\n clone_info->weight=draw_info->weight;\n if (draw_info->encoding != (char *) NULL)\n (void) CloneString(&clone_info->encoding,draw_info->encoding);\n clone_info->pointsize=draw_info->pointsize;\n clone_info->kerning=draw_info->kerning;\n clone_info->interline_spacing=draw_info->interline_spacing;\n clone_info->interword_spacing=draw_info->interword_spacing;\n clone_info->direction=draw_info->direction;\n if (draw_info->density != (char *) NULL)\n (void) CloneString(&clone_info->density,draw_info->density);\n clone_info->align=draw_info->align;\n clone_info->undercolor=draw_info->undercolor;\n clone_info->border_color=draw_info->border_color;\n if (draw_info->server_name != (char *) NULL)\n (void) CloneString(&clone_info->server_name,draw_info->server_name);\n if (draw_info->dash_pattern != (double *) NULL)\n {\n register ssize_t\n x;", " for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;\n clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,\n sizeof(*clone_info->dash_pattern));\n if (clone_info->dash_pattern == (double *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\n \"UnableToAllocateDashPattern\");\n (void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,\n (size_t) (x+1)*sizeof(*clone_info->dash_pattern));\n }\n clone_info->gradient=draw_info->gradient;\n if (draw_info->gradient.stops != (StopInfo *) NULL)\n {\n size_t\n number_stops;", " number_stops=clone_info->gradient.number_stops;\n clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)\n number_stops,sizeof(*clone_info->gradient.stops));\n if (clone_info->gradient.stops == (StopInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\n \"UnableToAllocateDashPattern\");\n (void) CopyMagickMemory(clone_info->gradient.stops,\n draw_info->gradient.stops,(size_t) number_stops*\n sizeof(*clone_info->gradient.stops));\n }\n if (draw_info->clip_mask != (char *) NULL)\n (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);\n clone_info->bounds=draw_info->bounds;\n clone_info->clip_units=draw_info->clip_units;\n clone_info->render=draw_info->render;\n clone_info->alpha=draw_info->alpha;\n clone_info->element_reference=draw_info->element_reference;\n clone_info->debug=IsEventLogging();\n exception=DestroyExceptionInfo(exception);\n return(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ C o n v e r t P a t h T o P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ConvertPathToPolygon() converts a path to the more efficient sorted\n% rendering form.\n%\n% The format of the ConvertPathToPolygon method is:\n%\n% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,\n% const PathInfo *path_info)\n%\n% A description of each parameter follows:\n%\n% o Method ConvertPathToPolygon returns the path in a more efficient sorted\n% rendering form of type PolygonInfo.\n%\n% o draw_info: Specifies a pointer to an DrawInfo structure.\n%\n% o path_info: Specifies a pointer to an PathInfo structure.\n%\n%\n*/", "#if defined(__cplusplus) || defined(c_plusplus)\nextern \"C\" {\n#endif", "static int CompareEdges(const void *x,const void *y)\n{\n register const EdgeInfo\n *p,\n *q;", " /*\n Compare two edges.\n */\n p=(const EdgeInfo *) x;\n q=(const EdgeInfo *) y;\n if ((p->points[0].y-MagickEpsilon) > q->points[0].y)\n return(1);\n if ((p->points[0].y+MagickEpsilon) < q->points[0].y)\n return(-1);\n if ((p->points[0].x-MagickEpsilon) > q->points[0].x)\n return(1);\n if ((p->points[0].x+MagickEpsilon) < q->points[0].x)\n return(-1);\n if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-\n (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)\n return(1);\n return(-1);\n}", "#if defined(__cplusplus) || defined(c_plusplus)\n}\n#endif", "static void LogPolygonInfo(const PolygonInfo *polygon_info)\n{\n register EdgeInfo\n *p;", " register ssize_t\n i,\n j;", " (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin active-edge\");\n p=polygon_info->edges;\n for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" edge %.20g:\",\n (double) i);\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" direction: %s\",\n p->direction != MagickFalse ? \"down\" : \"up\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" ghostline: %s\",\n p->ghostline != MagickFalse ? \"transparent\" : \"opaque\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" bounds: %g %g - %g %g\",p->bounds.x1,p->bounds.y1,\n p->bounds.x2,p->bounds.y2);\n for (j=0; j < (ssize_t) p->number_points; j++)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %g %g\",\n p->points[j].x,p->points[j].y);\n p++;\n }\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end active-edge\");\n}", "static void ReversePoints(PointInfo *points,const size_t number_points)\n{\n PointInfo\n point;", " register ssize_t\n i;", " for (i=0; i < (ssize_t) (number_points >> 1); i++)\n {\n point=points[i];\n points[i]=points[number_points-(i+1)];\n points[number_points-(i+1)]=point;\n }\n}", "static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)\n{\n long\n direction,\n next_direction;", " PointInfo\n point,\n *points;", " PolygonInfo\n *polygon_info;", " SegmentInfo\n bounds;", " register ssize_t\n i,\n n;", " MagickBooleanType\n ghostline;", " size_t\n edge,\n number_edges,\n number_points;", " /*\n Convert a path to the more efficient sorted rendering form.\n */\n polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));\n if (polygon_info == (PolygonInfo *) NULL)\n return((PolygonInfo *) NULL);\n number_edges=16;\n polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n direction=0;\n edge=0;\n ghostline=MagickFalse;\n n=0;\n number_points=0;\n points=(PointInfo *) NULL;\n (void) ResetMagickMemory(&point,0,sizeof(point));\n (void) ResetMagickMemory(&bounds,0,sizeof(bounds));\n for (i=0; path_info[i].code != EndCode; i++)\n {\n if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||\n (path_info[i].code == GhostlineCode))\n {\n /*\n Move to.\n */\n if ((points != (PointInfo *) NULL) && (n >= 2))\n {\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n points=(PointInfo *) NULL;\n ghostline=MagickFalse;\n edge++;\n }\n if (points == (PointInfo *) NULL)\n {\n number_points=16;\n points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;\n point=path_info[i].point;\n points[0]=point;\n bounds.x1=point.x;\n bounds.x2=point.x;\n direction=0;\n n=1;\n continue;\n }\n /*\n Line to.\n */\n next_direction=((path_info[i].point.y > point.y) ||\n ((path_info[i].point.y == point.y) &&\n (path_info[i].point.x > point.x))) ? 1 : -1;\n if ((points != (PointInfo *) NULL) && (direction != 0) &&\n (direction != next_direction))\n {\n /*\n New edge.\n */\n point=points[n-1];\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n number_points=16;\n points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n n=1;\n ghostline=MagickFalse;\n points[0]=point;\n bounds.x1=point.x;\n bounds.x2=point.x;\n edge++;\n }\n direction=next_direction;\n if (points == (PointInfo *) NULL)\n continue;\n if (n == (ssize_t) number_points)\n {\n number_points<<=1;\n points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n point=path_info[i].point;\n points[n]=point;\n if (point.x < bounds.x1)\n bounds.x1=point.x;\n if (point.x > bounds.x2)\n bounds.x2=point.x;\n n++;\n }\n if (points != (PointInfo *) NULL)\n {\n if (n < 2)\n points=(PointInfo *) RelinquishMagickMemory(points);\n else\n {\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n ghostline=MagickFalse;\n edge++;\n }\n }\n polygon_info->number_edges=edge;\n qsort(polygon_info->edges,(size_t) polygon_info->number_edges,\n sizeof(*polygon_info->edges),CompareEdges);\n if (IsEventLogging() != MagickFalse)\n LogPolygonInfo(polygon_info);\n return(polygon_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ C o n v e r t P r i m i t i v e T o P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector\n% path structure.\n%\n% The format of the ConvertPrimitiveToPath method is:\n%\n% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,\n% const PrimitiveInfo *primitive_info)\n%\n% A description of each parameter follows:\n%\n% o Method ConvertPrimitiveToPath returns a vector path structure of type\n% PathInfo.\n%\n% o draw_info: a structure of type DrawInfo.\n%\n% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.\n%\n%\n*/", "static void LogPathInfo(const PathInfo *path_info)\n{\n register const PathInfo\n *p;", " (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin vector-path\");\n for (p=path_info; p->code != EndCode; p++)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %g %g %s\",p->point.x,p->point.y,p->code == GhostlineCode ?\n \"moveto ghostline\" : p->code == OpenCode ? \"moveto open\" :\n p->code == MoveToCode ? \"moveto\" : p->code == LineToCode ? \"lineto\" :\n \"?\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end vector-path\");\n}", "static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)\n{\n PathInfo\n *path_info;", " PathInfoCode\n code;", " PointInfo\n p,\n q;", " register ssize_t\n i,\n n;", " ssize_t\n coordinates,\n start;", " /*\n Converts a PrimitiveInfo structure into a vector path structure.\n */\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n case ColorPrimitive:\n case ImagePrimitive:\n case PointPrimitive:\n case TextPrimitive:\n return((PathInfo *) NULL);\n default:\n break;\n }\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),\n sizeof(*path_info));\n if (path_info == (PathInfo *) NULL)\n return((PathInfo *) NULL);\n coordinates=0;\n n=0;\n p.x=(-1.0);\n p.y=(-1.0);\n q.x=(-1.0);\n q.y=(-1.0);\n start=0;\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n code=LineToCode;\n if (coordinates <= 0)\n {\n coordinates=(ssize_t) primitive_info[i].coordinates;\n p=primitive_info[i].point;\n start=n;\n code=MoveToCode;\n }\n coordinates--;\n /*\n Eliminate duplicate points.\n */\n if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||\n (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))\n {\n path_info[n].code=code;\n path_info[n].point=primitive_info[i].point;\n q=primitive_info[i].point;\n n++;\n }\n if (coordinates > 0)\n continue;\n if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) &&\n (fabs(p.y-primitive_info[i].point.y) < MagickEpsilon))\n continue;\n /*\n Mark the p point as open if it does not match the q.\n */\n path_info[start].code=OpenCode;\n path_info[n].code=GhostlineCode;\n path_info[n].point=primitive_info[i].point;\n n++;\n path_info[n].code=LineToCode;\n path_info[n].point=p;\n n++;\n }\n path_info[n].code=EndCode;\n path_info[n].point.x=0.0;\n path_info[n].point.y=0.0;\n if (IsEventLogging() != MagickFalse)\n LogPathInfo(path_info);\n return(path_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D e s t r o y D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyDrawInfo() deallocates memory associated with an DrawInfo\n% structure.\n%\n% The format of the DestroyDrawInfo method is:\n%\n% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)\n{\n if (draw_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n if (draw_info->primitive != (char *) NULL)\n draw_info->primitive=DestroyString(draw_info->primitive);\n if (draw_info->text != (char *) NULL)\n draw_info->text=DestroyString(draw_info->text);\n if (draw_info->geometry != (char *) NULL)\n draw_info->geometry=DestroyString(draw_info->geometry);\n if (draw_info->fill_pattern != (Image *) NULL)\n draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);\n if (draw_info->stroke_pattern != (Image *) NULL)\n draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);\n if (draw_info->font != (char *) NULL)\n draw_info->font=DestroyString(draw_info->font);\n if (draw_info->metrics != (char *) NULL)\n draw_info->metrics=DestroyString(draw_info->metrics);\n if (draw_info->family != (char *) NULL)\n draw_info->family=DestroyString(draw_info->family);\n if (draw_info->encoding != (char *) NULL)\n draw_info->encoding=DestroyString(draw_info->encoding);\n if (draw_info->density != (char *) NULL)\n draw_info->density=DestroyString(draw_info->density);\n if (draw_info->server_name != (char *) NULL)\n draw_info->server_name=(char *)\n RelinquishMagickMemory(draw_info->server_name);\n if (draw_info->dash_pattern != (double *) NULL)\n draw_info->dash_pattern=(double *) RelinquishMagickMemory(\n draw_info->dash_pattern);\n if (draw_info->gradient.stops != (StopInfo *) NULL)\n draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(\n draw_info->gradient.stops);\n if (draw_info->clip_mask != (char *) NULL)\n draw_info->clip_mask=DestroyString(draw_info->clip_mask);\n draw_info->signature=(~MagickCoreSignature);\n draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);\n return(draw_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D e s t r o y E d g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyEdge() destroys the specified polygon edge.\n%\n% The format of the DestroyEdge method is:\n%\n% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)\n%\n% A description of each parameter follows:\n%\n% o polygon_info: Specifies a pointer to an PolygonInfo structure.\n%\n% o edge: the polygon edge number to destroy.\n%\n*/\nstatic size_t DestroyEdge(PolygonInfo *polygon_info,\n const size_t edge)\n{\n assert(edge < polygon_info->number_edges);\n polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(\n polygon_info->edges[edge].points);\n polygon_info->number_edges--;\n if (edge < polygon_info->number_edges)\n (void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,\n (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));\n return(polygon_info->number_edges);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D e s t r o y P o l y g o n I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyPolygonInfo() destroys the PolygonInfo data structure.\n%\n% The format of the DestroyPolygonInfo method is:\n%\n% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)\n%\n% A description of each parameter follows:\n%\n% o polygon_info: Specifies a pointer to an PolygonInfo structure.\n%\n*/\nstatic PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)\n{\n register ssize_t\n i;", " for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n polygon_info->edges[i].points=(PointInfo *)\n RelinquishMagickMemory(polygon_info->edges[i].points);\n polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);\n return((PolygonInfo *) RelinquishMagickMemory(polygon_info));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w A f f i n e I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawAffineImage() composites the source over the destination image as\n% dictated by the affine transform.\n%\n% The format of the DrawAffineImage method is:\n%\n% MagickBooleanType DrawAffineImage(Image *image,const Image *source,\n% const AffineMatrix *affine,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o source: the source image.\n%\n% o affine: the affine transform.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,\n const double y,const SegmentInfo *edge)\n{\n double\n intercept,\n z;", " register double\n x;", " SegmentInfo\n inverse_edge;", " /*\n Determine left and right edges.\n */\n inverse_edge.x1=edge->x1;\n inverse_edge.y1=edge->y1;\n inverse_edge.x2=edge->x2;\n inverse_edge.y2=edge->y2;\n z=affine->ry*y+affine->tx;\n if (affine->sx >= MagickEpsilon)\n {\n intercept=(-z/affine->sx);\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z+(double) image->columns)/affine->sx;\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if (affine->sx < -MagickEpsilon)\n {\n intercept=(-z+(double) image->columns)/affine->sx;\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z/affine->sx);\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))\n {\n inverse_edge.x2=edge->x1;\n return(inverse_edge);\n }\n /*\n Determine top and bottom edges.\n */\n z=affine->sy*y+affine->ty;\n if (affine->rx >= MagickEpsilon)\n {\n intercept=(-z/affine->rx);\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z+(double) image->rows)/affine->rx;\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if (affine->rx < -MagickEpsilon)\n {\n intercept=(-z+(double) image->rows)/affine->rx;\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z/affine->rx);\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))\n {\n inverse_edge.x2=edge->x2;\n return(inverse_edge);\n }\n return(inverse_edge);\n}", "static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)\n{\n AffineMatrix\n inverse_affine;", " double\n determinant;", " determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*\n affine->ry);\n inverse_affine.sx=determinant*affine->sy;\n inverse_affine.rx=determinant*(-affine->rx);\n inverse_affine.ry=determinant*(-affine->ry);\n inverse_affine.sy=determinant*affine->sx;\n inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*\n inverse_affine.ry;\n inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*\n inverse_affine.sy;\n return(inverse_affine);\n}", "MagickExport MagickBooleanType DrawAffineImage(Image *image,\n const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)\n{\n AffineMatrix\n inverse_affine;", " CacheView\n *image_view,\n *source_view;", " MagickBooleanType\n status;", " PixelInfo\n zero;", " PointInfo\n extent[4],\n min,\n max;", " register ssize_t\n i;", " SegmentInfo\n edge;", " ssize_t\n start,\n stop,\n y;", " /*\n Determine bounding box.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(source != (const Image *) NULL);\n assert(source->signature == MagickCoreSignature);\n assert(affine != (AffineMatrix *) NULL);\n extent[0].x=0.0;\n extent[0].y=0.0;\n extent[1].x=(double) source->columns-1.0;\n extent[1].y=0.0;\n extent[2].x=(double) source->columns-1.0;\n extent[2].y=(double) source->rows-1.0;\n extent[3].x=0.0;\n extent[3].y=(double) source->rows-1.0;\n for (i=0; i < 4; i++)\n {\n PointInfo\n point;", " point=extent[i];\n extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;\n extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;\n }\n min=extent[0];\n max=extent[0];\n for (i=1; i < 4; i++)\n {\n if (min.x > extent[i].x)\n min.x=extent[i].x;\n if (min.y > extent[i].y)\n min.y=extent[i].y;\n if (max.x < extent[i].x)\n max.x=extent[i].x;\n if (max.y < extent[i].y)\n max.y=extent[i].y;\n }\n /*\n Affine transform image.\n */\n if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)\n return(MagickFalse);\n status=MagickTrue;\n edge.x1=MagickMax(min.x,0.0);\n edge.y1=MagickMax(min.y,0.0);\n edge.x2=MagickMin(max.x,(double) image->columns-1.0);\n edge.y2=MagickMin(max.y,(double) image->rows-1.0);\n inverse_affine=InverseAffineMatrix(affine);\n GetPixelInfo(image,&zero);\n start=(ssize_t) ceil(edge.y1-0.5);\n stop=(ssize_t) floor(edge.y2+0.5);\n source_view=AcquireVirtualCacheView(source,exception);\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(source,image,1,1)\n#endif\n for (y=start; y <= stop; y++)\n {\n PixelInfo\n composite,\n pixel;", " PointInfo\n point;", " register ssize_t\n x;", " register Quantum\n *magick_restrict q;", " SegmentInfo\n inverse_edge;", " ssize_t\n x_offset;", " inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);\n if (inverse_edge.x2 < inverse_edge.x1)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-\n 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),\n 1,exception);\n if (q == (Quantum *) NULL)\n continue;\n pixel=zero;\n composite=zero;\n x_offset=0;\n for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)\n {\n point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+\n inverse_affine.tx;\n point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+\n inverse_affine.ty;\n (void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,\n point.x,point.y,&pixel,exception);\n GetPixelInfoPixel(image,q,&composite);\n CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,\n &composite);\n SetPixelViaPixelInfo(image,&composite,q);\n x_offset++;\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n source_view=DestroyCacheView(source_view);\n image_view=DestroyCacheView(image_view);\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w B o u n d i n g R e c t a n g l e s %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawBoundingRectangles() draws the bounding rectangles on the image. This\n% is only useful for developers debugging the rendering algorithm.\n%\n% The format of the DrawBoundingRectangles method is:\n%\n% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,\n% PolygonInfo *polygon_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o polygon_info: Specifies a pointer to a PolygonInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,\n const PolygonInfo *polygon_info,ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " double\n mid;", " PointInfo\n end,\n resolution,\n start;", " PrimitiveInfo\n primitive_info[6];", " register ssize_t\n i;", " SegmentInfo\n bounds;", " ssize_t\n coordinates;", " clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,&clone_info->fill,\n exception);\n resolution.x=DefaultResolution;\n resolution.y=DefaultResolution;\n if (clone_info->density != (char *) NULL)\n {\n GeometryInfo\n geometry_info;", " MagickStatusType\n flags;", " flags=ParseGeometry(clone_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == MagickFalse)\n resolution.y=resolution.x;\n }\n mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*\n clone_info->stroke_width/2.0;\n bounds.x1=0.0;\n bounds.y1=0.0;\n bounds.x2=0.0;\n bounds.y2=0.0;\n if (polygon_info != (PolygonInfo *) NULL)\n {\n bounds=polygon_info->edges[0].bounds;\n for (i=1; i < (ssize_t) polygon_info->number_edges; i++)\n {\n if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)\n bounds.x1=polygon_info->edges[i].bounds.x1;\n if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)\n bounds.y1=polygon_info->edges[i].bounds.y1;\n if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)\n bounds.x2=polygon_info->edges[i].bounds.x2;\n if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)\n bounds.y2=polygon_info->edges[i].bounds.y2;\n }\n bounds.x1-=mid;\n bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)\n image->columns ? (double) image->columns-1 : bounds.x1;\n bounds.y1-=mid;\n bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)\n image->rows ? (double) image->rows-1 : bounds.y1;\n bounds.x2+=mid;\n bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)\n image->columns ? (double) image->columns-1 : bounds.x2;\n bounds.y2+=mid;\n bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)\n image->rows ? (double) image->rows-1 : bounds.y2;\n for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n {\n if (polygon_info->edges[i].direction != 0)\n (void) QueryColorCompliance(\"red\",AllCompliance,&clone_info->stroke,\n exception);\n else\n (void) QueryColorCompliance(\"green\",AllCompliance,&clone_info->stroke,\n exception);\n start.x=(double) (polygon_info->edges[i].bounds.x1-mid);\n start.y=(double) (polygon_info->edges[i].bounds.y1-mid);\n end.x=(double) (polygon_info->edges[i].bounds.x2+mid);\n end.y=(double) (polygon_info->edges[i].bounds.y2+mid);\n primitive_info[0].primitive=RectanglePrimitive;\n TraceRectangle(primitive_info,start,end);\n primitive_info[0].method=ReplaceMethod;\n coordinates=(ssize_t) primitive_info[0].coordinates;\n primitive_info[coordinates].primitive=UndefinedPrimitive;\n (void) DrawPrimitive(image,clone_info,primitive_info,exception);\n }\n }\n (void) QueryColorCompliance(\"blue\",AllCompliance,&clone_info->stroke,\n exception);\n start.x=(double) (bounds.x1-mid);\n start.y=(double) (bounds.y1-mid);\n end.x=(double) (bounds.x2+mid);\n end.y=(double) (bounds.y2+mid);\n primitive_info[0].primitive=RectanglePrimitive;\n TraceRectangle(primitive_info,start,end);\n primitive_info[0].method=ReplaceMethod;\n coordinates=(ssize_t) primitive_info[0].coordinates;\n primitive_info[coordinates].primitive=UndefinedPrimitive;\n (void) DrawPrimitive(image,clone_info,primitive_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w C l i p P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawClipPath() draws the clip path on the image mask.\n%\n% The format of the DrawClipPath method is:\n%\n% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,\n% const char *name,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o name: the name of the clip path.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nMagickExport MagickBooleanType DrawClipPath(Image *image,\n const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];", " Image\n *clip_mask;", " const char\n *value;", " DrawInfo\n *clone_info;", " MagickStatusType\n status;", " assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n (void) FormatLocaleString(filename,MagickPathExtent,\"%s\",name);\n value=GetImageArtifact(image,filename);\n if (value == (const char *) NULL)\n return(MagickFalse);\n clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);\n if (clip_mask == (Image *) NULL)\n return(MagickFalse);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,\n &clip_mask->background_color,exception);", " clip_mask->background_color.alpha=(Quantum) TransparentAlpha;", " (void) SetImageBackgroundColor(clip_mask,exception);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"\\nbegin clip-path %s\",\n draw_info->clip_mask);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->primitive,value);\n (void) QueryColorCompliance(\"#ffffff\",AllCompliance,&clone_info->fill,\n exception);\n clone_info->clip_mask=(char *) NULL;\n status=NegateImage(clip_mask,MagickFalse,exception);\n (void) SetImageMask(image,ReadPixelMask,clip_mask,exception);\n clip_mask=DestroyImage(clip_mask);\n status&=DrawImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end clip-path\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w D a s h P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the\n% image while respecting the dash offset and dash pattern attributes.\n%\n% The format of the DrawDashPolygon method is:\n%\n% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,\n% const PrimitiveInfo *primitive_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o image: the image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " double\n length,\n maximum_length,\n offset,\n scale,\n total_length;", " MagickStatusType\n status;", " PrimitiveInfo\n *dash_polygon;", " register ssize_t\n i;", " register double\n dx,\n dy;", " size_t\n number_vertices;", " ssize_t\n j,\n n;", " assert(draw_info != (const DrawInfo *) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin draw-dash\");\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n number_vertices=(size_t) i;\n dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (2UL*number_vertices+1UL),sizeof(*dash_polygon));\n if (dash_polygon == (PrimitiveInfo *) NULL)\n return(MagickFalse);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->miterlimit=0;\n dash_polygon[0]=primitive_info[0];\n scale=ExpandAffine(&draw_info->affine);\n length=scale*(draw_info->dash_pattern[0]-0.5);\n offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;\n j=1;\n for (n=0; offset > 0.0; j=0)\n {\n if (draw_info->dash_pattern[n] <= 0.0)\n break;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n if (offset > length)\n {\n offset-=length;\n n++;\n length=scale*(draw_info->dash_pattern[n]+0.5);\n continue;\n }\n if (offset < length)\n {\n length-=offset;\n offset=0.0;\n break;\n }\n offset=0.0;\n n++;\n }\n status=MagickTrue;\n maximum_length=0.0;\n total_length=0.0;", " for (i=1; (i < number_vertices) && (length >= 0.0); i++)", " {\n dx=primitive_info[i].point.x-primitive_info[i-1].point.x;\n dy=primitive_info[i].point.y-primitive_info[i-1].point.y;\n maximum_length=hypot((double) dx,dy);\n if (length == 0.0)\n {\n n++;\n if (draw_info->dash_pattern[n] == 0.0)\n n=0;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n }\n for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )\n {\n total_length+=length;\n if ((n & 0x01) != 0)\n {\n dash_polygon[0]=primitive_info[0];\n dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*\n total_length/maximum_length);\n dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*\n total_length/maximum_length);\n j=1;\n }\n else\n {\n if ((j+1) > (ssize_t) (2*number_vertices))\n break;\n dash_polygon[j]=primitive_info[i-1];\n dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*\n total_length/maximum_length);\n dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*\n total_length/maximum_length);\n dash_polygon[j].coordinates=1;\n j++;\n dash_polygon[0].coordinates=(size_t) j;\n dash_polygon[j].primitive=UndefinedPrimitive;\n status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);\n }\n n++;\n if (draw_info->dash_pattern[n] == 0.0)\n n=0;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n }\n length-=(maximum_length-total_length);\n if ((n & 0x01) != 0)\n continue;\n dash_polygon[j]=primitive_info[i];\n dash_polygon[j].coordinates=1;\n j++;\n }\n if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))\n {\n dash_polygon[j]=primitive_info[i-1];\n dash_polygon[j].point.x+=MagickEpsilon;\n dash_polygon[j].point.y+=MagickEpsilon;\n dash_polygon[j].coordinates=1;\n j++;\n dash_polygon[0].coordinates=(size_t) j;\n dash_polygon[j].primitive=UndefinedPrimitive;\n status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);\n }\n dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-dash\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawImage() draws a graphic primitive on your image. The primitive\n% may be represented as a string or filename. Precede the filename with an\n% \"at\" sign (@) and the contents of the file are drawn on the image. You\n% can affect how text is drawn by setting one or more members of the draw\n% info structure.\n%\n% The format of the DrawImage method is:\n%\n% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline MagickBooleanType IsPoint(const char *point)\n{\n char\n *p;", " double\n value;", " value=StringToDouble(point,&p);\n return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);\n}", "static inline void TracePoint(PrimitiveInfo *primitive_info,\n const PointInfo point)\n{\n primitive_info->coordinates=1;\n primitive_info->point=point;\n}", "MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,\n ExceptionInfo *exception)\n{\n#define RenderImageTag \"Render/Image\"", " AffineMatrix\n affine,\n current;", " char\n keyword[MagickPathExtent],\n geometry[MagickPathExtent],\n pattern[MagickPathExtent],\n *primitive,\n *token;", " const char\n *q;", " DrawInfo\n **graphic_context;", " MagickBooleanType\n proceed;", " MagickStatusType\n status;", " double\n angle,\n factor,\n primitive_extent;", " PointInfo\n point;", " PrimitiveInfo\n *primitive_info;", " PrimitiveType\n primitive_type;", " register const char\n *p;", " register ssize_t\n i,\n x;", " SegmentInfo\n bounds;", " size_t\n extent,\n length,\n number_points,\n number_stops;", " ssize_t\n j,\n k,\n n;", " StopInfo\n *stops;", " /*\n Ensure the annotation info is valid.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n if ((draw_info->primitive == (char *) NULL) ||\n (*draw_info->primitive == '\\0'))\n return(MagickFalse);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"begin draw-image\");\n if (*draw_info->primitive != '@')\n primitive=AcquireString(draw_info->primitive);\n else\n primitive=FileToString(draw_info->primitive+1,~0UL,exception);\n if (primitive == (char *) NULL)\n return(MagickFalse);\n primitive_extent=(double) strlen(primitive);\n (void) SetImageArtifact(image,\"MVG\",primitive);\n n=0;\n number_stops=0;\n stops=(StopInfo *) NULL;\n /*\n Allocate primitive info memory.\n */\n graphic_context=(DrawInfo **) AcquireMagickMemory(\n sizeof(*graphic_context));\n if (graphic_context == (DrawInfo **) NULL)\n {\n primitive=DestroyString(primitive);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n number_points=6553;\n primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n primitive=DestroyString(primitive);\n for ( ; n >= 0; n--)\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n graphic_context[n]->viewbox=image->page;\n if ((image->page.width == 0) || (image->page.height == 0))\n {\n graphic_context[n]->viewbox.width=image->columns;\n graphic_context[n]->viewbox.height=image->rows;\n }\n token=AcquireString(primitive);\n extent=strlen(token)+MagickPathExtent;\n if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)\n return(MagickFalse);\n status=MagickTrue;\n for (q=primitive; *q != '\\0'; )\n {\n /*\n Interpret graphic primitive.\n */", " GetNextToken(q,&q,extent,keyword);", " if (*keyword == '\\0')\n break;\n if (*keyword == '#')\n {\n /*\n Comment.\n */\n while ((*q != '\\n') && (*q != '\\0'))\n q++;\n continue;\n }\n p=q-strlen(keyword)-1;\n primitive_type=UndefinedPrimitive;\n current=graphic_context[n]->affine;\n GetAffineMatrix(&affine);\n switch (*keyword)\n {\n case ';':\n break;\n case 'a':\n case 'A':\n {\n if (LocaleCompare(\"affine\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.sx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.rx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ry=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.sy=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.tx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ty=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"alpha\",keyword) == 0)\n {\n primitive_type=AlphaPrimitive;\n break;\n }\n if (LocaleCompare(\"arc\",keyword) == 0)\n {\n primitive_type=ArcPrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(\"bezier\",keyword) == 0)\n {\n primitive_type=BezierPrimitive;\n break;\n }\n if (LocaleCompare(\"border-color\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->border_color,exception);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(\"clip-path\",keyword) == 0)\n {\n /*\n Create clip mask.\n */\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->clip_mask,token);\n (void) DrawClipPath(image,graphic_context[n],\n graphic_context[n]->clip_mask,exception);\n break;\n }\n if (LocaleCompare(\"clip-rule\",keyword) == 0)\n {\n ssize_t\n fill_rule;", " GetNextToken(q,&q,extent,token);\n fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,\n token);\n if (fill_rule == -1)\n status=MagickFalse;\n else\n graphic_context[n]->fill_rule=(FillRule) fill_rule;\n break;\n }\n if (LocaleCompare(\"clip-units\",keyword) == 0)\n {\n ssize_t\n clip_units;", " GetNextToken(q,&q,extent,token);\n clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,\n token);\n if (clip_units == -1)\n {\n status=MagickFalse;\n break;\n }\n graphic_context[n]->clip_units=(ClipPathUnits) clip_units;\n if (clip_units == ObjectBoundingBox)\n {\n GetAffineMatrix(&current);\n affine.sx=draw_info->bounds.x2;\n affine.sy=draw_info->bounds.y2;\n affine.tx=draw_info->bounds.x1;\n affine.ty=draw_info->bounds.y1;\n break;\n }\n break;\n }\n if (LocaleCompare(\"circle\",keyword) == 0)\n {\n primitive_type=CirclePrimitive;\n break;\n }\n if (LocaleCompare(\"color\",keyword) == 0)\n {\n primitive_type=ColorPrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(\"decorate\",keyword) == 0)\n {\n ssize_t\n decorate;", " GetNextToken(q,&q,extent,token);\n decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,\n token);\n if (decorate == -1)\n status=MagickFalse;\n else\n graphic_context[n]->decorate=(DecorationType) decorate;\n break;\n }\n if (LocaleCompare(\"density\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->density,token);\n break;\n }\n if (LocaleCompare(\"direction\",keyword) == 0)\n {\n ssize_t\n direction;", " GetNextToken(q,&q,extent,token);\n direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,\n token);\n if (direction == -1)\n status=MagickFalse;\n else\n graphic_context[n]->direction=(DirectionType) direction;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(\"ellipse\",keyword) == 0)\n {\n primitive_type=EllipsePrimitive;\n break;\n }\n if (LocaleCompare(\"encoding\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->encoding,token);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'f':\n case 'F':\n {\n if (LocaleCompare(\"fill\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(pattern,MagickPathExtent,\"%s\",token);\n if (GetImageArtifact(image,pattern) != (const char *) NULL)\n (void) DrawPatternPath(image,draw_info,token,\n &graphic_context[n]->fill_pattern,exception);\n else\n {\n status&=QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->fill,exception);\n if (status == MagickFalse)\n {\n ImageInfo\n *pattern_info;", " pattern_info=AcquireImageInfo();\n (void) CopyMagickString(pattern_info->filename,token,\n MagickPathExtent);\n graphic_context[n]->fill_pattern=ReadImage(pattern_info,\n exception);\n CatchException(exception);\n pattern_info=DestroyImageInfo(pattern_info);\n }\n }\n break;\n }\n if (LocaleCompare(\"fill-opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->fill.alpha=(double) QuantumRange*\n factor*StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"fill-rule\",keyword) == 0)\n {\n ssize_t\n fill_rule;", " GetNextToken(q,&q,extent,token);\n fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,\n token);\n if (fill_rule == -1)\n status=MagickFalse;\n else\n graphic_context[n]->fill_rule=(FillRule) fill_rule;\n break;\n }\n if (LocaleCompare(\"font\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->font,token);\n if (LocaleCompare(\"none\",token) == 0)\n graphic_context[n]->font=(char *)\n RelinquishMagickMemory(graphic_context[n]->font);\n break;\n }\n if (LocaleCompare(\"font-family\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->family,token);\n break;\n }\n if (LocaleCompare(\"font-size\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"font-stretch\",keyword) == 0)\n {\n ssize_t\n stretch;", " GetNextToken(q,&q,extent,token);\n stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);\n if (stretch == -1)\n status=MagickFalse;\n else\n graphic_context[n]->stretch=(StretchType) stretch;\n break;\n }\n if (LocaleCompare(\"font-style\",keyword) == 0)\n {\n ssize_t\n style;", " GetNextToken(q,&q,extent,token);\n style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);\n if (style == -1)\n status=MagickFalse;\n else\n graphic_context[n]->style=(StyleType) style;\n break;\n }\n if (LocaleCompare(\"font-weight\",keyword) == 0)\n {\n ssize_t\n weight;", " GetNextToken(q,&q,extent,token);\n weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);\n if (weight == -1)", " weight=StringToUnsignedLong(token);", " graphic_context[n]->weight=(size_t) weight;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(\"gradient-units\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"gravity\",keyword) == 0)\n {\n ssize_t\n gravity;", " GetNextToken(q,&q,extent,token);\n gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);\n if (gravity == -1)\n status=MagickFalse;\n else\n graphic_context[n]->gravity=(GravityType) gravity;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(\"image\",keyword) == 0)\n {\n ssize_t\n compose;", " primitive_type=ImagePrimitive;\n GetNextToken(q,&q,extent,token);\n compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);\n if (compose == -1)\n status=MagickFalse;\n else\n graphic_context[n]->compose=(CompositeOperator) compose;\n break;\n }\n if (LocaleCompare(\"interline-spacing\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->interline_spacing=StringToDouble(token,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(\"interword-spacing\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->interword_spacing=StringToDouble(token,\n (char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'k':\n case 'K':\n {\n if (LocaleCompare(\"kerning\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->kerning=StringToDouble(token,(char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'l':\n case 'L':\n {\n if (LocaleCompare(\"line\",keyword) == 0)\n primitive_type=LinePrimitive;\n else\n status=MagickFalse;\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(\"offset\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0-\n QuantumScale*graphic_context[n]->alpha)*factor*\n StringToDouble(token,(char **) NULL))));\n graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha;\n graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(\"path\",keyword) == 0)\n {\n primitive_type=PathPrimitive;\n break;\n }\n if (LocaleCompare(\"point\",keyword) == 0)\n {\n primitive_type=PointPrimitive;\n break;\n }\n if (LocaleCompare(\"polyline\",keyword) == 0)\n {\n primitive_type=PolylinePrimitive;\n break;\n }\n if (LocaleCompare(\"polygon\",keyword) == 0)\n {\n primitive_type=PolygonPrimitive;\n break;\n }\n if (LocaleCompare(\"pop\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(\"clip-path\",token) == 0)\n break;\n if (LocaleCompare(\"defs\",token) == 0)\n break;\n if (LocaleCompare(\"gradient\",token) == 0)\n break;\n if (LocaleCompare(\"graphic-context\",token) == 0)\n {\n if (n <= 0)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n DrawError,\"UnbalancedGraphicContextPushPop\",\"`%s'\",token);\n n=0;\n break;\n }\n if (graphic_context[n]->clip_mask != (char *) NULL)\n if (LocaleCompare(graphic_context[n]->clip_mask,\n graphic_context[n-1]->clip_mask) != 0)\n (void) SetImageMask(image,ReadPixelMask,(Image *) NULL,\n exception);\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n n--;\n break;\n }\n if (LocaleCompare(\"pattern\",token) == 0)\n break;\n status=MagickFalse;\n break;\n }\n if (LocaleCompare(\"push\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(\"clip-path\",token) == 0)\n {\n char\n name[MagickPathExtent];", " GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(name,MagickPathExtent,\"%s\",token);\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"clip-path\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n (void) SetImageArtifact(image,name,token);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"gradient\",token) == 0)\n {\n char\n key[2*MagickPathExtent],\n name[MagickPathExtent],\n type[MagickPathExtent];", " SegmentInfo\n segment;", " GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(name,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(type,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n segment.x1=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.y1=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.x2=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.y2=StringToDouble(token,(char **) NULL);\n if (LocaleCompare(type,\"radial\") == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n }\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"gradient\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n bounds.x1=graphic_context[n]->affine.sx*segment.x1+\n graphic_context[n]->affine.ry*segment.y1+\n graphic_context[n]->affine.tx;\n bounds.y1=graphic_context[n]->affine.rx*segment.x1+\n graphic_context[n]->affine.sy*segment.y1+\n graphic_context[n]->affine.ty;\n bounds.x2=graphic_context[n]->affine.sx*segment.x2+\n graphic_context[n]->affine.ry*segment.y2+\n graphic_context[n]->affine.tx;\n bounds.y2=graphic_context[n]->affine.rx*segment.x2+\n graphic_context[n]->affine.sy*segment.y2+\n graphic_context[n]->affine.ty;\n (void) FormatLocaleString(key,MagickPathExtent,\"%s\",name);\n (void) SetImageArtifact(image,key,token);\n (void) FormatLocaleString(key,MagickPathExtent,\"%s-type\",name);\n (void) SetImageArtifact(image,key,type);", " (void) FormatLocaleString(key,MagickPathExtent,\"%s-geometry\",name);", " (void) FormatLocaleString(geometry,MagickPathExtent,\n \"%gx%g%+.15g%+.15g\",\n MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),\n MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),\n bounds.x1,bounds.y1);\n (void) SetImageArtifact(image,key,geometry);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"pattern\",token) == 0)\n {\n char\n key[2*MagickPathExtent],\n name[MagickPathExtent];", " RectangleInfo\n pattern_bounds;", " GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(name,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n pattern_bounds.x=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.y=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.width=(size_t) floor(StringToDouble(token,\n (char **) NULL)+0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.height=(size_t) floor(StringToDouble(token,\n (char **) NULL)+0.5);\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"pattern\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n (void) FormatLocaleString(key,MagickPathExtent,\"%s\",name);\n (void) SetImageArtifact(image,key,token);\n (void) FormatLocaleString(key,MagickPathExtent,\"%s-geometry\",\n name);\n (void) FormatLocaleString(geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double)pattern_bounds.width,\n (double)pattern_bounds.height,(double)pattern_bounds.x,\n (double)pattern_bounds.y);\n (void) SetImageArtifact(image,key,geometry);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"graphic-context\",token) == 0)\n {\n n++;\n graphic_context=(DrawInfo **) ResizeQuantumMemory(\n graphic_context,(size_t) (n+1),sizeof(*graphic_context));\n if (graphic_context == (DrawInfo **) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,\n graphic_context[n-1]);\n break;\n }\n if (LocaleCompare(\"defs\",token) == 0)\n break;\n status=MagickFalse;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(\"rectangle\",keyword) == 0)\n {\n primitive_type=RectanglePrimitive;\n break;\n }\n if (LocaleCompare(\"rotate\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));\n affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));\n affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));\n affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));\n break;\n }\n if (LocaleCompare(\"roundRectangle\",keyword) == 0)\n {\n primitive_type=RoundRectanglePrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(\"scale\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.sx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.sy=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"skewX\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.ry=sin(DegreesToRadians(angle));\n break;\n }\n if (LocaleCompare(\"skewY\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.rx=(-tan(DegreesToRadians(angle)/2.0));\n break;\n }\n if (LocaleCompare(\"stop-color\",keyword) == 0)\n {\n PixelInfo\n stop_color;", " number_stops++;\n if (number_stops == 1)\n stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));\n else if (number_stops > 2)\n stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,\n sizeof(*stops));\n if (stops == (StopInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,&stop_color,\n exception);\n stops[number_stops-1].color=stop_color;\n GetNextToken(q,&q,extent,token);\n stops[number_stops-1].offset=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(pattern,MagickPathExtent,\"%s\",token);\n if (GetImageArtifact(image,pattern) != (const char *) NULL)\n (void) DrawPatternPath(image,draw_info,token,\n &graphic_context[n]->stroke_pattern,exception);\n else\n {\n status&=QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->stroke,exception);\n if (status == MagickFalse)\n {\n ImageInfo\n *pattern_info;", " pattern_info=AcquireImageInfo();\n (void) CopyMagickString(pattern_info->filename,token,\n MagickPathExtent);\n graphic_context[n]->stroke_pattern=ReadImage(pattern_info,\n exception);\n CatchException(exception);\n pattern_info=DestroyImageInfo(pattern_info);\n }\n }\n break;\n }\n if (LocaleCompare(\"stroke-antialias\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->stroke_antialias=\n StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n break;\n }\n if (LocaleCompare(\"stroke-dasharray\",keyword) == 0)\n {\n if (graphic_context[n]->dash_pattern != (double *) NULL)\n graphic_context[n]->dash_pattern=(double *)\n RelinquishMagickMemory(graphic_context[n]->dash_pattern);\n if (IsPoint(q) != MagickFalse)\n {\n const char\n *r;", " r=q;\n GetNextToken(r,&r,extent,token);\n if (*token == ',')\n GetNextToken(r,&r,extent,token);\n for (x=0; IsPoint(token) != MagickFalse; x++)\n {\n GetNextToken(r,&r,extent,token);\n if (*token == ',')\n GetNextToken(r,&r,extent,token);\n }\n graphic_context[n]->dash_pattern=(double *)\n AcquireQuantumMemory((size_t) (2UL*x+1UL),\n sizeof(*graphic_context[n]->dash_pattern));\n if (graphic_context[n]->dash_pattern == (double *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n for (j=0; j < x; j++)\n {\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->dash_pattern[j]=StringToDouble(token,\n (char **) NULL);\n if (graphic_context[n]->dash_pattern[j] < 0.0)\n status=MagickFalse;\n }\n if ((x & 0x01) != 0)\n for ( ; j < (2*x); j++)\n graphic_context[n]->dash_pattern[j]=\n graphic_context[n]->dash_pattern[j-x];\n graphic_context[n]->dash_pattern[j]=0.0;\n break;\n }\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"stroke-dashoffset\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->dash_offset=StringToDouble(token,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke-linecap\",keyword) == 0)\n {\n ssize_t\n linecap;", " GetNextToken(q,&q,extent,token);\n linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);\n if (linecap == -1)\n status=MagickFalse;\n else\n graphic_context[n]->linecap=(LineCap) linecap;\n break;\n }\n if (LocaleCompare(\"stroke-linejoin\",keyword) == 0)\n {\n ssize_t\n linejoin;", " GetNextToken(q,&q,extent,token);\n linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,\n token);\n if (linejoin == -1)\n status=MagickFalse;\n else\n graphic_context[n]->linejoin=(LineJoin) linejoin;\n break;\n }\n if (LocaleCompare(\"stroke-miterlimit\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->miterlimit=StringToUnsignedLong(token);\n break;\n }\n if (LocaleCompare(\"stroke-opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->stroke.alpha=(double) QuantumRange*\n factor*StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke-width\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->stroke_width=StringToDouble(token,\n (char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(\"text\",keyword) == 0)\n {\n primitive_type=TextPrimitive;\n break;\n }\n if (LocaleCompare(\"text-align\",keyword) == 0)\n {\n ssize_t\n align;", " GetNextToken(q,&q,extent,token);\n align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);\n if (align == -1)\n status=MagickFalse;\n else\n graphic_context[n]->align=(AlignType) align;\n break;\n }\n if (LocaleCompare(\"text-anchor\",keyword) == 0)\n {\n ssize_t\n align;", " GetNextToken(q,&q,extent,token);\n align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);\n if (align == -1)\n status=MagickFalse;\n else\n graphic_context[n]->align=(AlignType) align;\n break;\n }\n if (LocaleCompare(\"text-antialias\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->text_antialias=\n StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n break;\n }\n if (LocaleCompare(\"text-undercolor\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->undercolor,exception);\n break;\n }\n if (LocaleCompare(\"translate\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.tx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ty=StringToDouble(token,(char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'v':\n case 'V':\n {\n if (LocaleCompare(\"viewbox\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(\n token,(char **) NULL)+0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(\n token,(char **) NULL)+0.5);\n break;\n }\n status=MagickFalse;\n break;\n }\n default:\n {\n status=MagickFalse;\n break;\n }\n }\n if (status == MagickFalse)\n break;\n if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||\n (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))\n {\n graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;\n graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;\n graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;\n graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;\n graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+\n current.tx;\n graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+\n current.ty;\n }\n if (primitive_type == UndefinedPrimitive)\n {\n if (*q == '\\0')\n {\n if (number_stops > 1)\n {\n GradientType\n type;", " type=LinearGradient;\n if (draw_info->gradient.type == RadialGradient)\n type=RadialGradient;\n (void) GradientImage(image,type,PadSpread,stops,number_stops,\n exception);\n }\n if (number_stops > 0)\n stops=(StopInfo *) RelinquishMagickMemory(stops);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %.*s\",\n (int) (q-p),p);\n continue;\n }\n /*\n Parse the primitive attributes.\n */\n i=0;\n j=0;\n primitive_info[0].point.x=0.0;\n primitive_info[0].point.y=0.0;\n for (x=0; *q != '\\0'; x++)\n {\n /*\n Define points.\n */\n if (IsPoint(q) == MagickFalse)\n break;\n GetNextToken(q,&q,extent,token);\n point.x=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n point.y=StringToDouble(token,(char **) NULL);\n GetNextToken(q,(const char **) NULL,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n primitive_info[i].primitive=primitive_type;\n primitive_info[i].point=point;\n primitive_info[i].coordinates=0;\n primitive_info[i].method=FloodfillMethod;\n i++;\n if (i < (ssize_t) number_points)\n continue;\n number_points<<=1;\n primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,\n (size_t) number_points,sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n break;\n }\n }\n primitive_info[j].primitive=primitive_type;\n primitive_info[j].coordinates=(size_t) x;\n primitive_info[j].method=FloodfillMethod;\n primitive_info[j].text=(char *) NULL;\n /*\n Circumscribe primitive within a circle.\n */\n bounds.x1=primitive_info[j].point.x;\n bounds.y1=primitive_info[j].point.y;\n bounds.x2=primitive_info[j].point.x;\n bounds.y2=primitive_info[j].point.y;\n for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)\n {\n point=primitive_info[j+k].point;\n if (point.x < bounds.x1)\n bounds.x1=point.x;\n if (point.y < bounds.y1)\n bounds.y1=point.y;\n if (point.x > bounds.x2)\n bounds.x2=point.x;\n if (point.y > bounds.y2)\n bounds.y2=point.y;\n }\n /*\n Speculate how many points our primitive might consume.\n */\n length=primitive_info[j].coordinates;\n switch (primitive_type)\n {\n case RectanglePrimitive:\n {\n length*=5;\n break;\n }\n case RoundRectanglePrimitive:\n {\n double\n alpha,\n beta,\n radius;", " alpha=bounds.x2-bounds.x1;\n beta=bounds.y2-bounds.y1;\n radius=hypot((double) alpha,(double) beta);\n length*=5;\n length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;\n break;\n }\n case BezierPrimitive:\n {\n if (primitive_info[j].coordinates > 107)\n (void) ThrowMagickException(exception,GetMagickModule(),DrawError,\n \"TooManyBezierCoordinates\",\"`%s'\",token);\n length=BezierQuantum*primitive_info[j].coordinates;\n break;\n }\n case PathPrimitive:\n {\n char\n *s,\n *t;", " GetNextToken(q,&q,extent,token);\n length=1;\n t=token;\n for (s=token; *s != '\\0'; s=t)\n {\n double\n value;", " value=StringToDouble(s,&t);\n (void) value;\n if (s == t)\n {\n t++;\n continue;\n }\n length++;\n }\n length=length*BezierQuantum/2;\n break;\n }\n case CirclePrimitive:\n case ArcPrimitive:\n case EllipsePrimitive:\n {\n double\n alpha,\n beta,\n radius;", " alpha=bounds.x2-bounds.x1;\n beta=bounds.y2-bounds.y1;\n radius=hypot((double) alpha,(double) beta);\n length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;\n break;\n }\n default:\n break;\n }\n if ((size_t) (i+length) >= number_points)\n {\n /*\n Resize based on speculative points required by primitive.\n */\n number_points+=length+1;\n primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,\n (size_t) number_points,sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n }\n switch (primitive_type)\n {\n case PointPrimitive:\n default:\n {\n if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n TracePoint(primitive_info+j,primitive_info[j].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case LinePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceLine(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case RectanglePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceRectangle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case RoundRectanglePrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n status=MagickFalse;\n break;\n }\n TraceRoundRectangle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case ArcPrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n primitive_type=UndefinedPrimitive;\n break;\n }\n TraceArc(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case EllipsePrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n status=MagickFalse;\n break;\n }\n TraceEllipse(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case CirclePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceCircle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case PolylinePrimitive:\n break;\n case PolygonPrimitive:\n {\n primitive_info[i]=primitive_info[j];\n primitive_info[i].coordinates=0;\n primitive_info[j].coordinates++;\n i++;\n break;\n }\n case BezierPrimitive:\n {\n if (primitive_info[j].coordinates < 3)\n {\n status=MagickFalse;\n break;\n }\n TraceBezier(primitive_info+j,primitive_info[j].coordinates);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case PathPrimitive:\n {\n i=(ssize_t) (j+TracePath(primitive_info+j,token));\n break;\n }\n case AlphaPrimitive:\n case ColorPrimitive:\n {\n ssize_t\n method;", " if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n GetNextToken(q,&q,extent,token);\n method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);\n if (method == -1)\n status=MagickFalse;\n else\n primitive_info[j].method=(PaintMethod) method;\n break;\n }\n case TextPrimitive:\n {\n if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n if (*token != ',')\n GetNextToken(q,&q,extent,token);\n primitive_info[j].text=AcquireString(token);\n break;\n }\n case ImagePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n GetNextToken(q,&q,extent,token);\n primitive_info[j].text=AcquireString(token);\n break;\n }\n }\n if (primitive_info == (PrimitiveInfo *) NULL)\n break;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %.*s\",(int) (q-p),p);\n if (status == MagickFalse)\n break;\n primitive_info[i].primitive=UndefinedPrimitive;\n if (i == 0)\n continue;\n /*\n Transform points.\n */\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n point=primitive_info[i].point;\n primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+\n graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;\n primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+\n graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;\n point=primitive_info[i].point;\n if (point.x < graphic_context[n]->bounds.x1)\n graphic_context[n]->bounds.x1=point.x;\n if (point.y < graphic_context[n]->bounds.y1)\n graphic_context[n]->bounds.y1=point.y;\n if (point.x > graphic_context[n]->bounds.x2)\n graphic_context[n]->bounds.x2=point.x;\n if (point.y > graphic_context[n]->bounds.y2)\n graphic_context[n]->bounds.y2=point.y;\n if (primitive_info[i].primitive == ImagePrimitive)\n break;\n if (i >= (ssize_t) number_points)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n }\n if (graphic_context[n]->render != MagickFalse)\n {\n if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&\n (LocaleCompare(graphic_context[n]->clip_mask,\n graphic_context[n-1]->clip_mask) != 0))\n status&=DrawClipPath(image,graphic_context[n],\n graphic_context[n]->clip_mask,exception);\n status&=DrawPrimitive(image,graphic_context[n],primitive_info,\n exception);\n }\n if (primitive_info->text != (char *) NULL)\n primitive_info->text=(char *) RelinquishMagickMemory(\n primitive_info->text);\n proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)\n primitive_extent);\n if (proceed == MagickFalse)\n break;\n if (status == 0)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end draw-image\");\n /*\n Relinquish resources.\n */\n token=DestroyString(token);\n if (primitive_info != (PrimitiveInfo *) NULL)\n primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);\n primitive=DestroyString(primitive);\n for ( ; n >= 0; n--)\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);\n if (status == MagickFalse)\n ThrowBinaryException(DrawError,\"NonconformingDrawingPrimitiveDefinition\",\n keyword);\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w G r a d i e n t I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawGradientImage() draws a linear gradient on the image.\n%\n% The format of the DrawGradientImage method is:\n%\n% MagickBooleanType DrawGradientImage(Image *image,\n% const DrawInfo *draw_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline double GetStopColorOffset(const GradientInfo *gradient,\n const ssize_t x,const ssize_t y)\n{\n switch (gradient->type)\n {\n case UndefinedGradient:\n case LinearGradient:\n {\n double\n gamma,\n length,\n offset,\n scale;", " PointInfo\n p,\n q;", " const SegmentInfo\n *gradient_vector;", " gradient_vector=(&gradient->gradient_vector);\n p.x=gradient_vector->x2-gradient_vector->x1;\n p.y=gradient_vector->y2-gradient_vector->y1;\n q.x=(double) x-gradient_vector->x1;\n q.y=(double) y-gradient_vector->y1;\n length=sqrt(q.x*q.x+q.y*q.y);\n gamma=sqrt(p.x*p.x+p.y*p.y)*length;\n gamma=PerceptibleReciprocal(gamma);\n scale=p.x*q.x+p.y*q.y;\n offset=gamma*scale*length;\n return(offset);\n }\n case RadialGradient:\n {\n PointInfo\n v;", " if (gradient->spread == RepeatSpread)\n {\n v.x=(double) x-gradient->center.x;\n v.y=(double) y-gradient->center.y;\n return(sqrt(v.x*v.x+v.y*v.y));\n }\n v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(\n gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(\n gradient->angle))))/gradient->radii.x;\n v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(\n gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(\n gradient->angle))))/gradient->radii.y;\n return(sqrt(v.x*v.x+v.y*v.y));\n }\n }\n return(0.0);\n}", "static int StopInfoCompare(const void *x,const void *y)\n{\n StopInfo\n *stop_1,\n *stop_2;", " stop_1=(StopInfo *) x;\n stop_2=(StopInfo *) y;\n if (stop_1->offset > stop_2->offset)\n return(1);\n if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon)\n return(0);\n return(-1);\n}", "MagickExport MagickBooleanType DrawGradientImage(Image *image,\n const DrawInfo *draw_info,ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " const GradientInfo\n *gradient;", " const SegmentInfo\n *gradient_vector;", " double\n length;", " MagickBooleanType\n status;", " PixelInfo\n zero;", " PointInfo\n point;", " RectangleInfo\n bounding_box;", " ssize_t\n y;", " /*\n Draw linear or radial gradient on image.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n gradient=(&draw_info->gradient);\n qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),\n StopInfoCompare);\n gradient_vector=(&gradient->gradient_vector);\n point.x=gradient_vector->x2-gradient_vector->x1;\n point.y=gradient_vector->y2-gradient_vector->y1;\n length=sqrt(point.x*point.x+point.y*point.y);\n bounding_box=gradient->bounding_box;\n status=MagickTrue;\n GetPixelInfo(image,&zero);\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)\n {\n PixelInfo\n composite,\n pixel;", " double\n alpha,\n offset;", " register Quantum\n *magick_restrict q;", " register ssize_t\n i,\n x;", " ssize_t\n j;", " if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n pixel=zero;\n composite=zero;\n offset=GetStopColorOffset(gradient,0,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n switch (gradient->spread)\n {\n case UndefinedSpread:\n case PadSpread:\n {\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n }\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if ((offset < 0.0) || (i == 0))\n composite=gradient->stops[0].color;\n else\n if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n case ReflectSpread:\n {\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n }\n if (offset < 0.0)\n offset=(-offset);\n if ((ssize_t) fmod(offset,2.0) == 0)\n offset=fmod(offset,1.0);\n else\n offset=1.0-fmod(offset,1.0);\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if (i == 0)\n composite=gradient->stops[0].color;\n else\n if (i == (ssize_t) gradient->number_stops)\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n case RepeatSpread:\n {\n MagickBooleanType\n antialias;", " double\n repeat;", " antialias=MagickFalse;\n repeat=0.0;\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type == LinearGradient)\n {\n repeat=fmod(offset,length);\n if (repeat < 0.0)\n repeat=length-fmod(-repeat,length);\n else\n repeat=fmod(offset,length);\n antialias=(repeat < length) && ((repeat+1.0) > length) ?\n MagickTrue : MagickFalse;\n offset=repeat/length;\n }\n else\n {\n repeat=fmod(offset,gradient->radius);\n if (repeat < 0.0)\n repeat=gradient->radius-fmod(-repeat,gradient->radius);\n else\n repeat=fmod(offset,gradient->radius);\n antialias=repeat+1.0 > gradient->radius ? MagickTrue :\n MagickFalse;\n offset=repeat/gradient->radius;\n }\n }\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if (i == 0)\n composite=gradient->stops[0].color;\n else\n if (i == (ssize_t) gradient->number_stops)\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n if (antialias != MagickFalse)\n {\n if (gradient->type == LinearGradient)\n alpha=length-repeat;\n else\n alpha=gradient->radius-repeat;\n i=0;\n j=(ssize_t) gradient->number_stops-1L;\n }\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n }\n CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,\n &pixel);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w P a t t e r n P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPatternPath() draws a pattern.\n%\n% The format of the DrawPatternPath method is:\n%\n% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,\n% const char *name,Image **pattern,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o name: the pattern name.\n%\n% o image: the image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nMagickExport MagickBooleanType DrawPatternPath(Image *image,\n const DrawInfo *draw_info,const char *name,Image **pattern,\n ExceptionInfo *exception)\n{\n char\n property[MagickPathExtent];", " const char\n *geometry,\n *path,\n *type;", " DrawInfo\n *clone_info;", " ImageInfo\n *image_info;", " MagickBooleanType\n status;", " assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n assert(name != (const char *) NULL);\n (void) FormatLocaleString(property,MagickPathExtent,\"%s\",name);\n path=GetImageArtifact(image,property);\n if (path == (const char *) NULL)\n return(MagickFalse);\n (void) FormatLocaleString(property,MagickPathExtent,\"%s-geometry\",name);\n geometry=GetImageArtifact(image,property);\n if (geometry == (const char *) NULL)\n return(MagickFalse);\n if ((*pattern) != (Image *) NULL)\n *pattern=DestroyImage(*pattern);\n image_info=AcquireImageInfo();\n image_info->size=AcquireString(geometry);\n *pattern=AcquireImage(image_info,exception);\n image_info=DestroyImageInfo(image_info);\n (void) QueryColorCompliance(\"#000000ff\",AllCompliance,\n &(*pattern)->background_color,exception);\n (void) SetImageBackgroundColor(*pattern,exception);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"begin pattern-path %s %s\",name,geometry);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->fill_pattern=NewImageList();\n clone_info->stroke_pattern=NewImageList();\n (void) FormatLocaleString(property,MagickPathExtent,\"%s-type\",name);\n type=GetImageArtifact(image,property);\n if (type != (const char *) NULL)\n clone_info->gradient.type=(GradientType) ParseCommandOption(\n MagickGradientOptions,MagickFalse,type);\n (void) CloneString(&clone_info->primitive,path);\n status=DrawImage(*pattern,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end pattern-path\");\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w P o l y g o n P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPolygonPrimitive() draws a polygon on the image.\n%\n% The format of the DrawPolygonPrimitive method is:\n%\n% MagickBooleanType DrawPolygonPrimitive(Image *image,\n% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)\n{\n register ssize_t\n i;", " assert(polygon_info != (PolygonInfo **) NULL);\n for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)\n if (polygon_info[i] != (PolygonInfo *) NULL)\n polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);\n polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);\n return(polygon_info);\n}", "static PolygonInfo **AcquirePolygonThreadSet(\n const PrimitiveInfo *primitive_info)\n{\n PathInfo\n *magick_restrict path_info;", " PolygonInfo\n **polygon_info;", " register ssize_t\n i;", " size_t\n number_threads;", " number_threads=(size_t) GetMagickResourceLimit(ThreadResource);\n polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,\n sizeof(*polygon_info));\n if (polygon_info == (PolygonInfo **) NULL)\n return((PolygonInfo **) NULL);\n (void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));\n path_info=ConvertPrimitiveToPath(primitive_info);\n if (path_info == (PathInfo *) NULL)\n return(DestroyPolygonThreadSet(polygon_info));\n for (i=0; i < (ssize_t) number_threads; i++)\n {\n polygon_info[i]=ConvertPathToPolygon(path_info);\n if (polygon_info[i] == (PolygonInfo *) NULL)\n return(DestroyPolygonThreadSet(polygon_info));\n }\n path_info=(PathInfo *) RelinquishMagickMemory(path_info);\n return(polygon_info);\n}", "static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,\n const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,\n const ssize_t y,double *stroke_alpha)\n{\n double\n alpha,\n beta,\n distance,\n subpath_alpha;", " PointInfo\n delta;", " register const PointInfo\n *q;", " register EdgeInfo\n *p;", " register ssize_t\n i;", " ssize_t\n j,\n winding_number;", " /*\n Compute fill & stroke opacity for this (x,y) point.\n */\n *stroke_alpha=0.0;\n subpath_alpha=0.0;\n p=polygon_info->edges;\n for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)\n {\n if ((double) y <= (p->bounds.y1-mid-0.5))\n break;\n if ((double) y > (p->bounds.y2+mid+0.5))\n {\n (void) DestroyEdge(polygon_info,(size_t) j);\n continue;\n }\n if (((double) x <= (p->bounds.x1-mid-0.5)) ||\n ((double) x > (p->bounds.x2+mid+0.5)))\n continue;\n i=(ssize_t) MagickMax((double) p->highwater,1.0);\n for ( ; i < (ssize_t) p->number_points; i++)\n {\n if ((double) y <= (p->points[i-1].y-mid-0.5))\n break;\n if ((double) y > (p->points[i].y+mid+0.5))\n continue;\n if (p->scanline != (double) y)\n {\n p->scanline=(double) y;\n p->highwater=(size_t) i;\n }\n /*\n Compute distance between a point and an edge.\n */\n q=p->points+i-1;\n delta.x=(q+1)->x-q->x;\n delta.y=(q+1)->y-q->y;\n beta=delta.x*(x-q->x)+delta.y*(y-q->y);\n if (beta < 0.0)\n {\n delta.x=(double) x-q->x;\n delta.y=(double) y-q->y;\n distance=delta.x*delta.x+delta.y*delta.y;\n }\n else\n {\n alpha=delta.x*delta.x+delta.y*delta.y;\n if (beta > alpha)\n {\n delta.x=(double) x-(q+1)->x;\n delta.y=(double) y-(q+1)->y;\n distance=delta.x*delta.x+delta.y*delta.y;\n }\n else\n {\n alpha=1.0/alpha;\n beta=delta.x*(y-q->y)-delta.y*(x-q->x);\n distance=alpha*beta*beta;\n }\n }\n /*\n Compute stroke & subpath opacity.\n */\n beta=0.0;\n if (p->ghostline == MagickFalse)\n {\n alpha=mid+0.5;\n if ((*stroke_alpha < 1.0) &&\n (distance <= ((alpha+0.25)*(alpha+0.25))))\n {\n alpha=mid-0.5;\n if (distance <= ((alpha+0.25)*(alpha+0.25)))\n *stroke_alpha=1.0;\n else\n {\n beta=1.0;\n if (distance != 1.0)\n beta=sqrt((double) distance);\n alpha=beta-mid-0.5;\n if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))\n *stroke_alpha=(alpha-0.25)*(alpha-0.25);\n }\n }\n }\n if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))\n continue;\n if (distance <= 0.0)\n {\n subpath_alpha=1.0;\n continue;\n }\n if (distance > 1.0)\n continue;\n if (beta == 0.0)\n {\n beta=1.0;\n if (distance != 1.0)\n beta=sqrt(distance);\n }\n alpha=beta-1.0;\n if (subpath_alpha < (alpha*alpha))\n subpath_alpha=alpha*alpha;\n }\n }\n /*\n Compute fill opacity.\n */\n if (fill == MagickFalse)\n return(0.0);\n if (subpath_alpha >= 1.0)\n return(1.0);\n /*\n Determine winding number.\n */\n winding_number=0;\n p=polygon_info->edges;\n for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)\n {\n if ((double) y <= p->bounds.y1)\n break;\n if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))\n continue;\n if ((double) x > p->bounds.x2)\n {\n winding_number+=p->direction ? 1 : -1;\n continue;\n }\n i=(ssize_t) MagickMax((double) p->highwater,1.0);\n for ( ; i < (ssize_t) p->number_points; i++)\n if ((double) y <= p->points[i].y)\n break;\n q=p->points+i-1;\n if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))\n winding_number+=p->direction ? 1 : -1;\n }\n if (fill_rule != NonZeroRule)\n {\n if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)\n return(1.0);\n }\n else\n if (MagickAbsoluteValue(winding_number) != 0)\n return(1.0);\n return(subpath_alpha);\n}", "static MagickBooleanType DrawPolygonPrimitive(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " MagickBooleanType\n fill,\n status;", " double\n mid;", " PolygonInfo\n **magick_restrict polygon_info;", " register EdgeInfo\n *p;", " register ssize_t\n i;", " SegmentInfo\n bounds;", " ssize_t\n start_y,\n stop_y,\n y;", " /*\n Compute bounding box.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n assert(primitive_info != (PrimitiveInfo *) NULL);\n if (primitive_info->coordinates == 0)\n return(MagickTrue);\n polygon_info=AcquirePolygonThreadSet(primitive_info);\n if (polygon_info == (PolygonInfo **) NULL)\n return(MagickFalse);\nDisableMSCWarning(4127)\n if (0)\n DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);\nRestoreMSCWarning\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin draw-polygon\");\n fill=(primitive_info->method == FillToBorderMethod) ||\n (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n bounds=polygon_info[0]->edges[0].bounds;\n for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)\n {\n p=polygon_info[0]->edges+i;\n if (p->bounds.x1 < bounds.x1)\n bounds.x1=p->bounds.x1;\n if (p->bounds.y1 < bounds.y1)\n bounds.y1=p->bounds.y1;\n if (p->bounds.x2 > bounds.x2)\n bounds.x2=p->bounds.x2;\n if (p->bounds.y2 > bounds.y2)\n bounds.y2=p->bounds.y2;\n }\n bounds.x1-=(mid+1.0);\n bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=\n image->columns ? (double) image->columns-1 : bounds.x1;\n bounds.y1-=(mid+1.0);\n bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=\n image->rows ? (double) image->rows-1 : bounds.y1;\n bounds.x2+=(mid+1.0);\n bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=\n image->columns ? (double) image->columns-1 : bounds.x2;\n bounds.y2+=(mid+1.0);\n bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=\n image->rows ? (double) image->rows-1 : bounds.y2;\n status=MagickTrue;\n image_view=AcquireAuthenticCacheView(image,exception);\n if ((primitive_info->coordinates == 1) ||\n (polygon_info[0]->number_edges == 0))\n {\n /*\n Draw point.\n */\n start_y=(ssize_t) ceil(bounds.y1-0.5);\n stop_y=(ssize_t) floor(bounds.y2+0.5);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=start_y; y <= stop_y; y++)\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " register ssize_t\n x;", " register Quantum\n *magick_restrict q;", " ssize_t\n start_x,\n stop_x;", " if (status == MagickFalse)\n continue;\n start_x=(ssize_t) ceil(bounds.x1-0.5);\n stop_x=(ssize_t) floor(bounds.x2+0.5);\n x=start_x;\n q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n GetPixelInfo(image,&pixel);\n for ( ; x <= stop_x; x++)\n {\n if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&\n (y == (ssize_t) ceil(primitive_info->point.y-0.5)))\n {\n GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n }\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n polygon_info=DestroyPolygonThreadSet(polygon_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" end draw-polygon\");\n return(status);\n }\n /*\n Draw polygon or line.\n */\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n start_y=(ssize_t) ceil(bounds.y1-0.5);\n stop_y=(ssize_t) floor(bounds.y2+0.5);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=start_y; y <= stop_y; y++)\n {\n const int\n id = GetOpenMPThreadId();", " double\n fill_alpha,\n stroke_alpha;", " PixelInfo\n fill_color,\n stroke_color;", " register Quantum\n *magick_restrict q;", " register ssize_t\n x;", " ssize_t\n start_x,\n stop_x;", " if (status == MagickFalse)\n continue;\n start_x=(ssize_t) ceil(bounds.x1-0.5);\n stop_x=(ssize_t) floor(bounds.x2+0.5);\n q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+1),1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=start_x; x <= stop_x; x++)\n {\n /*\n Fill and/or stroke.\n */\n fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,\n x,y,&stroke_alpha);\n if (draw_info->stroke_antialias == MagickFalse)\n {\n fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;\n stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;\n }\n GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);\n fill_alpha=fill_alpha*fill_color.alpha;\n CompositePixelOver(image,&fill_color,fill_alpha,q,(double)\n GetPixelAlpha(image,q),q);\n GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);\n stroke_alpha=stroke_alpha*stroke_color.alpha;\n CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n polygon_info=DestroyPolygonThreadSet(polygon_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-polygon\");\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.\n%\n% The format of the DrawPrimitive method is:\n%\n% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,\n% PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)\n{\n const char\n *methods[] =\n {\n \"point\",\n \"replace\",\n \"floodfill\",\n \"filltoborder\",\n \"reset\",\n \"?\"\n };", " PointInfo\n p,\n q,\n point;", " register ssize_t\n i,\n x;", " ssize_t\n coordinates,\n y;", " x=(ssize_t) ceil(primitive_info->point.x-0.5);\n y=(ssize_t) ceil(primitive_info->point.y-0.5);\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"AlphaPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case ColorPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"ColorPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case ImagePrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"ImagePrimitive %.20g,%.20g\",(double) x,(double) y);\n return;\n }\n case PointPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"PointPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case TextPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"TextPrimitive %.20g,%.20g\",(double) x,(double) y);\n return;\n }\n default:\n break;\n }\n coordinates=0;\n p=primitive_info[0].point;\n q.x=(-1.0);\n q.y=(-1.0);\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n point=primitive_info[i].point;\n if (coordinates <= 0)\n {\n coordinates=(ssize_t) primitive_info[i].coordinates;\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin open (%.20g)\",(double) coordinates);\n p=point;\n }\n point=primitive_info[i].point;\n if ((fabs(q.x-point.x) >= MagickEpsilon) ||\n (fabs(q.y-point.y) >= MagickEpsilon))\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %.20g: %.18g,%.18g\",(double) coordinates,point.x,point.y);\n else\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %.20g: %g %g (duplicate)\",(double) coordinates,point.x,point.y);\n q=point;\n coordinates--;\n if (coordinates > 0)\n continue;\n if ((fabs(p.x-point.x) >= MagickEpsilon) ||\n (fabs(p.y-point.y) >= MagickEpsilon))\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end last (%.20g)\",\n (double) coordinates);\n else\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end open (%.20g)\",\n (double) coordinates);\n }\n}", "MagickExport MagickBooleanType DrawPrimitive(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " MagickStatusType\n status;", " register ssize_t\n i,\n x;", " ssize_t\n y;", " if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin draw-primitive\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" affine: %g %g %g %g %g %g\",draw_info->affine.sx,\n draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,\n draw_info->affine.tx,draw_info->affine.ty);\n }\n if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&\n ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||\n (IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))\n (void) SetImageColorspace(image,sRGBColorspace,exception);\n status=MagickTrue;\n x=(ssize_t) ceil(primitive_info->point.x-0.5);\n y=(ssize_t) ceil(primitive_info->point.y-0.5);\n image_view=AcquireAuthenticCacheView(image,exception);\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;", " register Quantum\n *q;", " q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel,\n target;", " (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n ChannelType\n channel_mask;", " PixelInfo\n target;", " (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n channel_mask=SetImageChannelMask(image,AlphaChannel);\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n (void) SetImageChannelMask(image,channel_mask);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ColorPrimitive:\n {\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;", " register Quantum\n *q;", " q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetPixelInfo(image,&pixel);\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel,\n target;", " (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n PixelInfo\n target;", " (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ImagePrimitive:\n {\n AffineMatrix\n affine;", " char\n composite_geometry[MagickPathExtent];", " Image\n *composite_image;", " ImageInfo\n *clone_info;", " RectangleInfo\n geometry;", " ssize_t\n x1,\n y1;", " if (primitive_info->text == (char *) NULL)\n break;\n clone_info=AcquireImageInfo();\n if (LocaleNCompare(primitive_info->text,\"data:\",5) == 0)\n composite_image=ReadInlineImage(clone_info,primitive_info->text,\n exception);\n else\n {\n (void) CopyMagickString(clone_info->filename,primitive_info->text,\n MagickPathExtent);\n composite_image=ReadImage(clone_info,exception);\n }\n clone_info=DestroyImageInfo(clone_info);\n if (composite_image == (Image *) NULL)\n break;\n (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)\n NULL,(void *) NULL);\n x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);\n y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);\n if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||\n ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))\n {\n /*\n Resize image.\n */\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%gx%g!\",primitive_info[1].point.x,primitive_info[1].point.y);\n composite_image->filter=image->filter;\n (void) TransformImage(&composite_image,(char *) NULL,\n composite_geometry,exception);\n }\n if (composite_image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,\n exception);\n if (draw_info->alpha != OpaqueAlpha)\n (void) SetImageAlpha(composite_image,draw_info->alpha,exception);\n SetGeometry(image,&geometry);\n image->gravity=draw_info->gravity;\n geometry.x=x;\n geometry.y=y;\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) composite_image->columns,(double)\n composite_image->rows,(double) geometry.x,(double) geometry.y);\n (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);\n affine=draw_info->affine;\n affine.tx=(double) geometry.x;\n affine.ty=(double) geometry.y;\n composite_image->interpolate=image->interpolate;\n if (draw_info->compose == OverCompositeOp)\n (void) DrawAffineImage(image,composite_image,&affine,exception);\n else\n (void) CompositeImage(image,composite_image,draw_info->compose,\n MagickTrue,geometry.x,geometry.y,exception);\n composite_image=DestroyImage(composite_image);\n break;\n }\n case PointPrimitive:\n {\n PixelInfo\n fill_color;", " register Quantum\n *q;", " if ((y < 0) || (y >= (ssize_t) image->rows))\n break;\n if ((x < 0) || (x >= (ssize_t) image->columns))\n break;\n q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&fill_color,exception);\n CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,\n (double) GetPixelAlpha(image,q),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case TextPrimitive:\n {\n char\n geometry[MagickPathExtent];", " DrawInfo\n *clone_info;", " if (primitive_info->text == (char *) NULL)\n break;\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->text,primitive_info->text);\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%+f%+f\",\n primitive_info->point.x,primitive_info->point.y);\n (void) CloneString(&clone_info->geometry,geometry);\n status&=AnnotateImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n break;\n }\n default:\n {\n double\n mid,\n scale;", " DrawInfo\n *clone_info;", " if (IsEventLogging() != MagickFalse)\n LogPrimitiveInfo(primitive_info);\n scale=ExpandAffine(&draw_info->affine);\n if ((draw_info->dash_pattern != (double *) NULL) &&\n (draw_info->dash_pattern[0] != 0.0) &&\n ((scale*draw_info->stroke_width) >= MagickEpsilon) &&\n (draw_info->stroke.alpha != (Quantum) TransparentAlpha))\n {\n /*\n Draw dash polygon.\n */\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;", " clone_info->stroke.alpha=(Quantum) TransparentAlpha;", " status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n (void) DrawDashPolygon(draw_info,primitive_info,image,exception);\n break;\n }\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n if ((mid > 1.0) &&\n ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||\n (draw_info->stroke_pattern != (Image *) NULL)))\n {\n MagickBooleanType\n closed_path;", " /*\n Draw strokes while respecting line cap/join attributes.\n */\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n closed_path=\n (primitive_info[i-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[i-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n i=(ssize_t) primitive_info[0].coordinates;\n if ((((draw_info->linecap == RoundCap) ||\n (closed_path != MagickFalse)) &&\n (draw_info->linejoin == RoundJoin)) ||\n (primitive_info[i].primitive != UndefinedPrimitive))\n {\n (void) DrawPolygonPrimitive(image,draw_info,primitive_info,\n exception);\n break;\n }\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;", " clone_info->stroke.alpha=(Quantum) TransparentAlpha;", " status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);\n break;\n }\n status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);\n break;\n }\n }\n image_view=DestroyCacheView(image_view);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-primitive\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w S t r o k e P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on\n% the image while respecting the line cap and join attributes.\n%\n% The format of the DrawStrokePolygon method is:\n%\n% MagickBooleanType DrawStrokePolygon(Image *image,\n% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n%\n*/", "static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n{\n PrimitiveInfo\n linecap[5];", " register ssize_t\n i;", " for (i=0; i < 4; i++)\n linecap[i]=(*primitive_info);\n linecap[0].coordinates=4;\n linecap[1].point.x+=(double) (10.0*MagickEpsilon);\n linecap[2].point.x+=(double) (10.0*MagickEpsilon);\n linecap[2].point.y+=(double) (10.0*MagickEpsilon);\n linecap[3].point.y+=(double) (10.0*MagickEpsilon);\n linecap[4].primitive=UndefinedPrimitive;\n (void) DrawPolygonPrimitive(image,draw_info,linecap,exception);\n}", "static MagickBooleanType DrawStrokePolygon(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " MagickBooleanType\n closed_path;", " MagickStatusType\n status;", " PrimitiveInfo\n *stroke_polygon;", " register const PrimitiveInfo\n *p,\n *q;", " /*\n Draw stroked polygon.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin draw-stroke-polygon\");\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->fill=draw_info->stroke;\n if (clone_info->fill_pattern != (Image *) NULL)\n clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);\n if (clone_info->stroke_pattern != (Image *) NULL)\n clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,\n MagickTrue,exception);", " clone_info->stroke.alpha=(Quantum) TransparentAlpha;", " clone_info->stroke_width=0.0;\n clone_info->fill_rule=NonZeroRule;\n status=MagickTrue;\n for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)\n {\n stroke_polygon=TraceStrokePolygon(draw_info,p);\n status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);\n if (status == 0)\n break;\n stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);\n q=p+p->coordinates-1;\n closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?\n MagickTrue : MagickFalse;\n if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))\n {\n DrawRoundLinecap(image,draw_info,p,exception);\n DrawRoundLinecap(image,draw_info,q,exception);\n }\n }\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" end draw-stroke-polygon\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% G e t A f f i n e M a t r i x %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GetAffineMatrix() returns an AffineMatrix initialized to the identity\n% matrix.\n%\n% The format of the GetAffineMatrix method is:\n%\n% void GetAffineMatrix(AffineMatrix *affine_matrix)\n%\n% A description of each parameter follows:\n%\n% o affine_matrix: the affine matrix.\n%\n*/\nMagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)\n{\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(affine_matrix != (AffineMatrix *) NULL);\n (void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));\n affine_matrix->sx=1.0;\n affine_matrix->sy=1.0;\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ G e t D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GetDrawInfo() initializes draw_info to default values from image_info.\n%\n% The format of the GetDrawInfo method is:\n%\n% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info..\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)\n{\n const char\n *option;", " ExceptionInfo\n *exception;", " ImageInfo\n *clone_info;", " /*\n Initialize draw attributes.\n */\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(draw_info != (DrawInfo *) NULL);\n (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));\n clone_info=CloneImageInfo(image_info);\n GetAffineMatrix(&draw_info->affine);\n exception=AcquireExceptionInfo();\n (void) QueryColorCompliance(\"#000F\",AllCompliance,&draw_info->fill,\n exception);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,&draw_info->stroke,\n exception);\n draw_info->stroke_width=1.0;\n draw_info->alpha=OpaqueAlpha;\n draw_info->fill_rule=EvenOddRule;\n draw_info->linecap=ButtCap;\n draw_info->linejoin=MiterJoin;\n draw_info->miterlimit=10;\n draw_info->decorate=NoDecoration;\n draw_info->pointsize=12.0;", " draw_info->undercolor.alpha=(Quantum) TransparentAlpha;", " draw_info->compose=OverCompositeOp;\n draw_info->render=MagickTrue;\n draw_info->debug=IsEventLogging();\n draw_info->stroke_antialias=clone_info->antialias;\n if (clone_info->font != (char *) NULL)\n draw_info->font=AcquireString(clone_info->font);\n if (clone_info->density != (char *) NULL)\n draw_info->density=AcquireString(clone_info->density);\n draw_info->text_antialias=clone_info->antialias;\n if (clone_info->pointsize != 0.0)\n draw_info->pointsize=clone_info->pointsize;\n draw_info->border_color=clone_info->border_color;\n if (clone_info->server_name != (char *) NULL)\n draw_info->server_name=AcquireString(clone_info->server_name);\n option=GetImageOption(clone_info,\"direction\");\n if (option != (const char *) NULL)\n draw_info->direction=(DirectionType) ParseCommandOption(\n MagickDirectionOptions,MagickFalse,option);\n else\n draw_info->direction=UndefinedDirection;\n option=GetImageOption(clone_info,\"encoding\");\n if (option != (const char *) NULL)\n (void) CloneString(&draw_info->encoding,option);\n option=GetImageOption(clone_info,\"family\");\n if (option != (const char *) NULL)\n (void) CloneString(&draw_info->family,option);\n option=GetImageOption(clone_info,\"fill\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,\n exception);\n option=GetImageOption(clone_info,\"gravity\");\n if (option != (const char *) NULL)\n draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,\n MagickFalse,option);\n option=GetImageOption(clone_info,\"interline-spacing\");\n if (option != (const char *) NULL)\n draw_info->interline_spacing=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"interword-spacing\");\n if (option != (const char *) NULL)\n draw_info->interword_spacing=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"kerning\");\n if (option != (const char *) NULL)\n draw_info->kerning=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"stroke\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,\n exception);\n option=GetImageOption(clone_info,\"strokewidth\");\n if (option != (const char *) NULL)\n draw_info->stroke_width=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"style\");\n if (option != (const char *) NULL)\n draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,\n MagickFalse,option);\n option=GetImageOption(clone_info,\"undercolor\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,\n exception);\n option=GetImageOption(clone_info,\"weight\");\n if (option != (const char *) NULL)\n {\n ssize_t\n weight;", " weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);\n if (weight == -1)", " weight=StringToUnsignedLong(option);", " draw_info->weight=(size_t) weight;\n }\n exception=DestroyExceptionInfo(exception);\n draw_info->signature=MagickCoreSignature;\n clone_info=DestroyImageInfo(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ P e r m u t a t e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Permutate() returns the permuation of the (n,k).\n%\n% The format of the Permutate method is:\n%\n% void Permutate(ssize_t n,ssize_t k)\n%\n% A description of each parameter follows:\n%\n% o n:\n%\n% o k:\n%\n%\n*/\nstatic inline double Permutate(const ssize_t n,const ssize_t k)\n{\n double\n r;", " register ssize_t\n i;", " r=1.0;\n for (i=k+1; i <= n; i++)\n r*=i;\n for (i=1; i <= (n-k); i++)\n r/=i;\n return(r);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ T r a c e P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% TracePrimitive is a collection of methods for generating graphic\n% primitives such as arcs, ellipses, paths, etc.\n%\n*/", "static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end,const PointInfo degrees)\n{\n PointInfo\n center,\n radii;", " center.x=0.5*(end.x+start.x);\n center.y=0.5*(end.y+start.y);\n radii.x=fabs(center.x-start.x);\n radii.y=fabs(center.y-start.y);\n TraceEllipse(primitive_info,center,radii,degrees);\n}", "static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end,const PointInfo arc,const double angle,\n const MagickBooleanType large_arc,const MagickBooleanType sweep)\n{\n double\n alpha,\n beta,\n delta,\n factor,\n gamma,\n theta;", " PointInfo\n center,\n points[3],\n radii;", " register double\n cosine,\n sine;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " size_t\n arc_segments;", " if ((start.x == end.x) && (start.y == end.y))\n {\n TracePoint(primitive_info,end);\n return;\n }\n radii.x=fabs(arc.x);\n radii.y=fabs(arc.y);\n if ((radii.x == 0.0) || (radii.y == 0.0))\n {\n TraceLine(primitive_info,start,end);\n return;\n }\n cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));\n sine=sin(DegreesToRadians(fmod((double) angle,360.0)));\n center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);\n center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);\n delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/\n (radii.y*radii.y);\n if (delta < MagickEpsilon)\n {\n TraceLine(primitive_info,start,end);\n return;\n }\n if (delta > 1.0)\n {\n radii.x*=sqrt((double) delta);\n radii.y*=sqrt((double) delta);\n }\n points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);\n points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);\n points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);\n points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);\n alpha=points[1].x-points[0].x;\n beta=points[1].y-points[0].y;\n factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;\n if (factor <= 0.0)\n factor=0.0;\n else\n {\n factor=sqrt((double) factor);\n if (sweep == large_arc)\n factor=(-factor);\n }\n center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);\n center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);\n alpha=atan2(points[0].y-center.y,points[0].x-center.x);\n theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;\n if ((theta < 0.0) && (sweep != MagickFalse))\n theta+=(double) (2.0*MagickPI);\n else\n if ((theta > 0.0) && (sweep == MagickFalse))\n theta-=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+\n MagickEpsilon))));\n p=primitive_info;\n for (i=0; i < (ssize_t) arc_segments; i++)\n {\n beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));\n gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*\n sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/\n sin(fmod((double) beta,DegreesToRadians(360.0)));\n points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/\n arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+\n (double) i*theta/arc_segments),DegreesToRadians(360.0))));\n points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/\n arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+\n (double) i*theta/arc_segments),DegreesToRadians(360.0))));\n points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*\n theta/arc_segments),DegreesToRadians(360.0))));\n points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*\n theta/arc_segments),DegreesToRadians(360.0))));\n points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)\n (i+1)*theta/arc_segments),DegreesToRadians(360.0))));\n points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)\n (i+1)*theta/arc_segments),DegreesToRadians(360.0))));\n p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;\n p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;\n (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*\n points[0].y);\n (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*\n points[0].y);\n (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*\n points[1].y);\n (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*\n points[1].y);\n (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*\n points[2].y);\n (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*\n points[2].y);\n if (i == (ssize_t) (arc_segments-1))\n (p+3)->point=end;\n TraceBezier(p,4);\n p+=p->coordinates;\n }\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceBezier(PrimitiveInfo *primitive_info,\n const size_t number_coordinates)\n{\n double\n alpha,\n *coefficients,\n weight;", " PointInfo\n end,\n point,\n *points;", " register PrimitiveInfo\n *p;", " register ssize_t\n i,\n j;", " size_t\n control_points,\n quantum;", " /*\n Allocate coeficients.\n */\n quantum=number_coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n for (j=i+1; j < (ssize_t) number_coordinates; j++)\n {\n alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n }\n }\n quantum=(size_t) MagickMin((double) quantum/number_coordinates,\n (double) BezierQuantum);\n control_points=quantum*number_coordinates;\n coefficients=(double *) AcquireQuantumMemory((size_t)\n number_coordinates,sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,\n sizeof(*points));\n if ((coefficients == (double *) NULL) ||\n (points == (PointInfo *) NULL))\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n /*\n Compute bezier points.\n */\n end=primitive_info[number_coordinates-1].point;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);\n weight=0.0;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n p=primitive_info;\n point.x=0.0;\n point.y=0.0;\n alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);\n for (j=0; j < (ssize_t) number_coordinates; j++)\n {\n point.x+=alpha*coefficients[j]*p->point.x;\n point.y+=alpha*coefficients[j]*p->point.y;\n alpha*=weight/(1.0-weight);\n p++;\n }\n points[i]=point;\n weight+=1.0/control_points;\n }\n /*\n Bezier curves are just short segmented polys.\n */\n p=primitive_info;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n TracePoint(p,points[i]);\n p+=p->coordinates;\n }\n TracePoint(p,end);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n}", "static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n double\n alpha,\n beta,\n radius;", " PointInfo\n offset,\n degrees;", " alpha=end.x-start.x;\n beta=end.y-start.y;\n radius=hypot((double) alpha,(double) beta);\n offset.x=(double) radius;\n offset.y=(double) radius;\n degrees.x=0.0;\n degrees.y=360.0;\n TraceEllipse(primitive_info,start,offset,degrees);\n}", "static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo stop,const PointInfo degrees)\n{\n double\n delta,\n step,\n y;", " PointInfo\n angle,\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " /*\n Ellipses are just short segmented polys.\n */\n if ((stop.x == 0.0) && (stop.y == 0.0))\n {\n TracePoint(primitive_info,start);\n return;\n }\n delta=2.0/MagickMax(stop.x,stop.y);\n step=(double) (MagickPI/8.0);\n if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0)))\n step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5)));\n angle.x=DegreesToRadians(degrees.x);\n y=degrees.y;\n while (y < degrees.x)\n y+=360.0;\n angle.y=(double) DegreesToRadians(y);\n for (p=primitive_info; angle.x < angle.y; angle.x+=step)\n {\n point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;\n point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n }\n point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;\n point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n TracePoint(primitive_info,start);\n if ((fabs(start.x-end.x) < MagickEpsilon) &&\n (fabs(start.y-end.y) < MagickEpsilon))\n {\n primitive_info->primitive=PointPrimitive;\n primitive_info->coordinates=1;\n return;\n }\n TracePoint(primitive_info+1,end);\n (primitive_info+1)->primitive=primitive_info->primitive;\n primitive_info->coordinates=2;\n}", "static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)\n{\n char\n token[MagickPathExtent];", " const char\n *p;", " int\n attribute,\n last_attribute;", " double\n x,\n y;", " PointInfo\n end = {0.0, 0.0},\n points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },\n point = {0.0, 0.0},\n start = {0.0, 0.0};", " PrimitiveType\n primitive_type;", " register PrimitiveInfo\n *q;", " register ssize_t\n i;", " size_t\n number_coordinates,\n z_count;", " attribute=0;\n number_coordinates=0;\n z_count=0;\n primitive_type=primitive_info->primitive;\n q=primitive_info;\n for (p=path; *p != '\\0'; )\n {\n while (isspace((int) ((unsigned char) *p)) != 0)\n p++;\n if (*p == '\\0')\n break;\n last_attribute=attribute;\n attribute=(int) (*p++);\n switch (attribute)\n {\n case 'a':\n case 'A':\n {\n MagickBooleanType\n large_arc,\n sweep;", " double\n angle;", " PointInfo\n arc;", " /*\n Compute arc points.\n */\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n arc.x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n arc.y=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n angle=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'A' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'A' ? y : point.y+y);\n TraceArcPath(q,point,end,arc,angle,large_arc,sweep);\n q+=q->coordinates;\n point=end;\n while (isspace((int) ((unsigned char) *p)) != 0)\n p++;\n if (*p == ',')\n p++;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'c':\n case 'C':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=point;\n for (i=1; i < 4; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'C' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'C' ? y : point.y+y);\n points[i]=end;\n }\n for (i=0; i < 4; i++)\n (q+i)->point=points[i];\n TraceBezier(q,4);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'H':\n case 'h':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'H' ? x: point.x+x);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'l':\n case 'L':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'L' ? x : point.x+x);\n point.y=(double) (attribute == (int) 'L' ? y : point.y+y);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'M':\n case 'm':\n {\n if (q != primitive_info)\n {\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n primitive_info=q;\n }\n i=0;\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'M' ? x : point.x+x);\n point.y=(double) (attribute == (int) 'M' ? y : point.y+y);\n if (i == 0)\n start=point;\n i++;\n TracePoint(q,point);\n q+=q->coordinates;\n if ((i != 0) && (attribute == (int) 'M'))\n {\n TracePoint(q,point);\n q+=q->coordinates;\n }\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'q':\n case 'Q':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=point;\n for (i=1; i < 3; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n if (*p == ',')\n p++;\n end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);\n points[i]=end;\n }\n for (i=0; i < 3; i++)\n (q+i)->point=points[i];\n TraceBezier(q,3);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 's':\n case 'S':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=points[3];\n points[1].x=2.0*points[3].x-points[2].x;\n points[1].y=2.0*points[3].y-points[2].y;\n for (i=2; i < 4; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n if (*p == ',')\n p++;\n end.x=(double) (attribute == (int) 'S' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'S' ? y : point.y+y);\n points[i]=end;\n }\n if (strchr(\"CcSs\",last_attribute) == (char *) NULL)\n {\n points[0]=point;\n points[1]=point;\n }\n for (i=0; i < 4; i++)\n (q+i)->point=points[i];\n TraceBezier(q,4);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 't':\n case 'T':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=points[2];\n points[1].x=2.0*points[2].x-points[1].x;\n points[1].y=2.0*points[2].y-points[1].y;\n for (i=2; i < 3; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'T' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'T' ? y : point.y+y);\n points[i]=end;\n }\n if (strchr(\"QqTt\",last_attribute) == (char *) NULL)\n {\n points[0]=point;\n points[1]=point;\n }\n for (i=0; i < 3; i++)\n (q+i)->point=points[i];\n TraceBezier(q,3);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'v':\n case 'V':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.y=(double) (attribute == (int) 'V' ? y : point.y+y);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'z':\n case 'Z':\n {\n point=start;\n TracePoint(q,point);\n q+=q->coordinates;\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n primitive_info=q;\n z_count++;\n break;\n }\n default:\n {\n if (isalpha((int) ((unsigned char) attribute)) != 0)\n (void) FormatLocaleFile(stderr,\"attribute not recognized: %c\\n\",\n attribute);\n break;\n }\n }\n }\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n q--;\n q->primitive=primitive_type;\n if (z_count > 1)\n q->method=FillToBorderMethod;\n }\n q=primitive_info;\n return(number_coordinates);\n}", "static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n PointInfo\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " p=primitive_info;\n TracePoint(p,start);\n p+=p->coordinates;\n point.x=start.x;\n point.y=end.y;\n TracePoint(p,point);\n p+=p->coordinates;\n TracePoint(p,end);\n p+=p->coordinates;\n point.x=end.x;\n point.y=start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n TracePoint(p,start);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceRoundRectangle(PrimitiveInfo *primitive_info,\n const PointInfo start,const PointInfo end,PointInfo arc)\n{\n PointInfo\n degrees,\n offset,\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " p=primitive_info;\n offset.x=fabs(end.x-start.x);\n offset.y=fabs(end.y-start.y);\n if (arc.x > (0.5*offset.x))\n arc.x=0.5*offset.x;\n if (arc.y > (0.5*offset.y))\n arc.y=0.5*offset.y;\n point.x=start.x+offset.x-arc.x;\n point.y=start.y+arc.y;\n degrees.x=270.0;\n degrees.y=360.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+offset.x-arc.x;\n point.y=start.y+offset.y-arc.y;\n degrees.x=0.0;\n degrees.y=90.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+arc.x;\n point.y=start.y+offset.y-arc.y;\n degrees.x=90.0;\n degrees.y=180.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+arc.x;\n point.y=start.y+arc.y;\n degrees.x=180.0;\n degrees.y=270.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n TracePoint(p,primitive_info->point);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceSquareLinecap(PrimitiveInfo *primitive_info,\n const size_t number_vertices,const double offset)\n{\n double\n distance;", " register double\n dx,\n dy;", " register ssize_t\n i;", " ssize_t\n j;", " dx=0.0;\n dy=0.0;\n for (i=1; i < (ssize_t) number_vertices; i++)\n {\n dx=primitive_info[0].point.x-primitive_info[i].point.x;\n dy=primitive_info[0].point.y-primitive_info[i].point.y;\n if ((fabs((double) dx) >= MagickEpsilon) ||\n (fabs((double) dy) >= MagickEpsilon))\n break;\n }\n if (i == (ssize_t) number_vertices)\n i=(ssize_t) number_vertices-1L;\n distance=hypot((double) dx,(double) dy);\n primitive_info[0].point.x=(double) (primitive_info[i].point.x+\n dx*(distance+offset)/distance);\n primitive_info[0].point.y=(double) (primitive_info[i].point.y+\n dy*(distance+offset)/distance);\n for (j=(ssize_t) number_vertices-2; j >= 0; j--)\n {\n dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;\n dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;\n if ((fabs((double) dx) >= MagickEpsilon) ||\n (fabs((double) dy) >= MagickEpsilon))\n break;\n }\n distance=hypot((double) dx,(double) dy);\n primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+\n dx*(distance+offset)/distance);\n primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+\n dy*(distance+offset)/distance);\n}", "static inline double DrawEpsilonReciprocal(const double x)\n{\n#define DrawEpsilon (1.0e-6)", " double sign = x < 0.0 ? -1.0 : 1.0;\n return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));\n}", "static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info)\n{\n typedef struct _LineSegment\n {\n double\n p,\n q;\n } LineSegment;", " LineSegment\n dx,\n dy,\n inverse_slope,\n slope,\n theta;", " MagickBooleanType\n closed_path;", " double\n delta_theta,\n dot_product,\n mid,\n miterlimit;", " PointInfo\n box_p[5],\n box_q[5],\n center,\n offset,\n *path_p,\n *path_q;", " PrimitiveInfo\n *polygon_primitive,\n *stroke_polygon;", " register ssize_t\n i;", " size_t\n arc_segments,\n max_strokes,\n number_vertices;", " ssize_t\n j,\n n,\n p,\n q;", " /*\n Allocate paths.\n */\n number_vertices=primitive_info->coordinates;\n max_strokes=2*number_vertices+6*BezierQuantum+360;\n path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_q));\n polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n number_vertices+2UL,sizeof(*polygon_primitive));\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||\n (polygon_primitive == (PrimitiveInfo *) NULL))\n return((PrimitiveInfo *) NULL);\n (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)\n number_vertices*sizeof(*polygon_primitive));\n closed_path=\n (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n if ((draw_info->linejoin == RoundJoin) ||\n ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))\n {\n polygon_primitive[number_vertices]=primitive_info[1];\n number_vertices++;\n }\n polygon_primitive[number_vertices].primitive=UndefinedPrimitive;\n /*\n Compute the slope for the first line segment, p.\n */\n dx.p=0.0;\n dy.p=0.0;\n for (n=1; n < (ssize_t) number_vertices; n++)\n {\n dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;\n dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;\n if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))\n break;\n }\n if (n == (ssize_t) number_vertices)\n n=(ssize_t) number_vertices-1L;\n slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;\n inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*\n mid*mid);\n if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))\n TraceSquareLinecap(polygon_primitive,number_vertices,mid);\n offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));\n offset.y=(double) (offset.x*inverse_slope.p);\n if ((dy.p*offset.x-dx.p*offset.y) > 0.0)\n {\n box_p[0].x=polygon_primitive[0].point.x-offset.x;\n box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;\n box_p[1].x=polygon_primitive[n].point.x-offset.x;\n box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;\n box_q[0].x=polygon_primitive[0].point.x+offset.x;\n box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;\n box_q[1].x=polygon_primitive[n].point.x+offset.x;\n box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;\n }\n else\n {\n box_p[0].x=polygon_primitive[0].point.x+offset.x;\n box_p[0].y=polygon_primitive[0].point.y+offset.y;\n box_p[1].x=polygon_primitive[n].point.x+offset.x;\n box_p[1].y=polygon_primitive[n].point.y+offset.y;\n box_q[0].x=polygon_primitive[0].point.x-offset.x;\n box_q[0].y=polygon_primitive[0].point.y-offset.y;\n box_q[1].x=polygon_primitive[n].point.x-offset.x;\n box_q[1].y=polygon_primitive[n].point.y-offset.y;\n }\n /*\n Create strokes for the line join attribute: bevel, miter, round.\n */\n p=0;\n q=0;\n path_q[p++]=box_q[0];\n path_p[q++]=box_p[0];\n for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)\n {\n /*\n Compute the slope for this line segment, q.\n */\n dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;\n dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;\n dot_product=dx.q*dx.q+dy.q*dy.q;\n if (dot_product < 0.25)\n continue;\n slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;\n inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));\n offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));\n offset.y=(double) (offset.x*inverse_slope.q);\n dot_product=dy.q*offset.x-dx.q*offset.y;\n if (dot_product > 0.0)\n {\n box_p[2].x=polygon_primitive[n].point.x-offset.x;\n box_p[2].y=polygon_primitive[n].point.y-offset.y;\n box_p[3].x=polygon_primitive[i].point.x-offset.x;\n box_p[3].y=polygon_primitive[i].point.y-offset.y;\n box_q[2].x=polygon_primitive[n].point.x+offset.x;\n box_q[2].y=polygon_primitive[n].point.y+offset.y;\n box_q[3].x=polygon_primitive[i].point.x+offset.x;\n box_q[3].y=polygon_primitive[i].point.y+offset.y;\n }\n else\n {\n box_p[2].x=polygon_primitive[n].point.x+offset.x;\n box_p[2].y=polygon_primitive[n].point.y+offset.y;\n box_p[3].x=polygon_primitive[i].point.x+offset.x;\n box_p[3].y=polygon_primitive[i].point.y+offset.y;\n box_q[2].x=polygon_primitive[n].point.x-offset.x;\n box_q[2].y=polygon_primitive[n].point.y-offset.y;\n box_q[3].x=polygon_primitive[i].point.x-offset.x;\n box_q[3].y=polygon_primitive[i].point.y-offset.y;\n }\n if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)\n {\n box_p[4]=box_p[1];\n box_q[4]=box_q[1];\n }\n else\n {\n box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+\n box_p[3].y)/(slope.p-slope.q));\n box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);\n box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+\n box_q[3].y)/(slope.p-slope.q));\n box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);\n }\n if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))\n {", " max_strokes+=6*BezierQuantum+360;\n path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes,\n sizeof(*path_q));\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))\n {\n polygon_primitive=(PrimitiveInfo *)\n RelinquishMagickMemory(polygon_primitive);\n return((PrimitiveInfo *) NULL);\n }", " }\n dot_product=dx.q*dy.p-dx.p*dy.q;\n if (dot_product <= 0.0)\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);\n theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);\n if (theta.q < theta.p)\n theta.q+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_q[q].x=box_q[1].x;\n path_q[q].y=box_q[1].y;\n q++;\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_q[q].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_q[q].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n q++;\n }\n path_q[q++]=box_q[2];\n break;\n }\n default:\n break;\n }\n else\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);\n theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);\n if (theta.p < theta.q)\n theta.p+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_p[p++]=box_p[1];\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_p[p].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_p[p].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n p++;\n }\n path_p[p++]=box_p[2];\n break;\n }\n default:\n break;\n }\n slope.p=slope.q;\n inverse_slope.p=inverse_slope.q;\n box_p[0]=box_p[2];\n box_p[1]=box_p[3];\n box_q[0]=box_q[2];\n box_q[1]=box_q[3];\n dx.p=dx.q;\n dy.p=dy.q;\n n=i;\n }\n path_p[p++]=box_p[1];\n path_q[q++]=box_q[1];\n /*\n Trace stroked polygon.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));\n if (stroke_polygon != (PrimitiveInfo *) NULL)\n {\n for (i=0; i < (ssize_t) p; i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_p[i];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n }\n for ( ; i < (ssize_t) (p+q+closed_path); i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[p+closed_path].point;\n i++;\n }\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n stroke_polygon[i].primitive=UndefinedPrimitive;\n stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);\n }\n path_p=(PointInfo *) RelinquishMagickMemory(path_p);\n path_q=(PointInfo *) RelinquishMagickMemory(path_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);\n return(stroke_polygon);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [0, 6060], "buggy_code_start_loc": [0, 1434], "filenames": ["ChangeLog", "MagickCore/draw.c"], "fixing_code_end_loc": [4, 6073], "fixing_code_start_loc": [1, 1434], "message": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "FEF4935E-1F84-4394-A897-30F56CDC0B1A", "versionEndExcluding": null, "versionEndIncluding": "6.9.3-0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.0-0:*:*:*:*:*:*:*", "matchCriteriaId": "3B7CCC6B-C66E-48E2-BA1E-CBF6421B4FEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-0:*:*:*:*:*:*:*", "matchCriteriaId": "693C9F8F-A8C1-4D06-8F31-E085E16E701C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-1:*:*:*:*:*:*:*", "matchCriteriaId": "6D3D3DFC-8459-41BA-BF3E-AE84E48FCEE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file."}, {"lang": "es", "value": "La funci\u00f3n DrawDashPolygon en MagickCore/draw.c en ImageMagick en versiones anteriores a 6.9.4-0 y 7.x en versiones anteriores a 7.0.1-2 no maneja correctamente los c\u00e1lculos de ciertos v\u00e9rtices de datos integrados, lo que permite a atacantes remotos provocar una denegaci\u00f3n de servicio (desbordamiento de buffer y ca\u00edda de aplicaci\u00f3n) o posiblemente tener otro impacto no especificado a trav\u00e9s de un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2016-4562", "lastModified": "2016-09-23T02:00:17.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-06-04T16:59:00.140", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.imagemagick.org/script/changelog.php"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.oracle.com/technetwork/topics/security/bulletinjul2016-3090568.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}, "type": "CWE-119"}
122
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% DDDD RRRR AAA W W %\n% D D R R A A W W %\n% D D RRRR AAAAA W W W %\n% D D R RN A A WW WW %\n% DDDD R R A A W W %\n% %\n% %\n% MagickCore Image Drawing Methods %\n% %\n% %\n% Software Design %\n% Cristy %\n% July 1998 %\n% %\n% %\n% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% http://www.imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon\n% rendering code based on Paul Heckbert's \"Concave Polygon Scan Conversion\",\n% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent\n% (www.appligent.com) contributed the dash pattern, linecap stroking\n% algorithm, and minor rendering improvements.\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/annotate.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/cache-view.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/color.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/composite.h\"\n#include \"MagickCore/composite-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/draw.h\"\n#include \"MagickCore/draw-private.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/gem.h\"\n#include \"MagickCore/geometry.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/paint.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/pixel-private.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/resample.h\"\n#include \"MagickCore/resample-private.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#include \"MagickCore/token.h\"\n#include \"MagickCore/transform-private.h\"\n#include \"MagickCore/utility.h\"\n\f\n/*\n Define declarations.\n*/\n#define BezierQuantum 200\n\f\n/*\n Typedef declarations.\n*/\ntypedef struct _EdgeInfo\n{\n SegmentInfo\n bounds;", " double\n scanline;", " PointInfo\n *points;", " size_t\n number_points;", " ssize_t\n direction;", " MagickBooleanType\n ghostline;", " size_t\n highwater;\n} EdgeInfo;", "typedef struct _ElementInfo\n{\n double\n cx,\n cy,\n major,\n minor,\n angle;\n} ElementInfo;", "typedef struct _PolygonInfo\n{\n EdgeInfo\n *edges;", " size_t\n number_edges;\n} PolygonInfo;", "typedef enum\n{\n MoveToCode,\n OpenCode,\n GhostlineCode,\n LineToCode,\n EndCode\n} PathInfoCode;", "typedef struct _PathInfo\n{\n PointInfo\n point;", " PathInfoCode\n code;\n} PathInfo;\n\f\n/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,\n ExceptionInfo *);", "static PrimitiveInfo\n *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);", "static size_t\n TracePath(PrimitiveInfo *,const char *);", "static void\n TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),\n TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,\n const double,const MagickBooleanType,const MagickBooleanType),\n TraceBezier(PrimitiveInfo *,const size_t),\n TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,\n const PointInfo),\n TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),\n TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,\n PointInfo),\n TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% A c q u i r e D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% AcquireDrawInfo() returns a DrawInfo structure properly initialized.\n%\n% The format of the AcquireDrawInfo method is:\n%\n% DrawInfo *AcquireDrawInfo(void)\n%\n*/\nMagickExport DrawInfo *AcquireDrawInfo(void)\n{\n DrawInfo\n *draw_info;", " draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));\n if (draw_info == (DrawInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n GetDrawInfo((ImageInfo *) NULL,draw_info);\n return(draw_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% C l o n e D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL\n% is specified, a new DrawInfo structure is created initialized to default\n% values.\n%\n% The format of the CloneDrawInfo method is:\n%\n% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,\n% const DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,\n const DrawInfo *draw_info)\n{\n DrawInfo\n *clone_info;", " ExceptionInfo\n *exception;", " clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));\n if (clone_info == (DrawInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n GetDrawInfo(image_info,clone_info);\n if (draw_info == (DrawInfo *) NULL)\n return(clone_info);\n exception=AcquireExceptionInfo();\n if (clone_info->primitive != (char *) NULL)\n (void) CloneString(&clone_info->primitive,draw_info->primitive);\n if (draw_info->geometry != (char *) NULL)\n (void) CloneString(&clone_info->geometry,draw_info->geometry);\n clone_info->viewbox=draw_info->viewbox;\n clone_info->affine=draw_info->affine;\n clone_info->gravity=draw_info->gravity;\n clone_info->fill=draw_info->fill;\n clone_info->stroke=draw_info->stroke;\n clone_info->stroke_width=draw_info->stroke_width;\n if (draw_info->fill_pattern != (Image *) NULL)\n clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,\n exception);\n if (draw_info->stroke_pattern != (Image *) NULL)\n clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,\n MagickTrue,exception);\n clone_info->stroke_antialias=draw_info->stroke_antialias;\n clone_info->text_antialias=draw_info->text_antialias;\n clone_info->fill_rule=draw_info->fill_rule;\n clone_info->linecap=draw_info->linecap;\n clone_info->linejoin=draw_info->linejoin;\n clone_info->miterlimit=draw_info->miterlimit;\n clone_info->dash_offset=draw_info->dash_offset;\n clone_info->decorate=draw_info->decorate;\n clone_info->compose=draw_info->compose;\n if (draw_info->text != (char *) NULL)\n (void) CloneString(&clone_info->text,draw_info->text);\n if (draw_info->font != (char *) NULL)\n (void) CloneString(&clone_info->font,draw_info->font);\n if (draw_info->metrics != (char *) NULL)\n (void) CloneString(&clone_info->metrics,draw_info->metrics);\n if (draw_info->family != (char *) NULL)\n (void) CloneString(&clone_info->family,draw_info->family);\n clone_info->style=draw_info->style;\n clone_info->stretch=draw_info->stretch;\n clone_info->weight=draw_info->weight;\n if (draw_info->encoding != (char *) NULL)\n (void) CloneString(&clone_info->encoding,draw_info->encoding);\n clone_info->pointsize=draw_info->pointsize;\n clone_info->kerning=draw_info->kerning;\n clone_info->interline_spacing=draw_info->interline_spacing;\n clone_info->interword_spacing=draw_info->interword_spacing;\n clone_info->direction=draw_info->direction;\n if (draw_info->density != (char *) NULL)\n (void) CloneString(&clone_info->density,draw_info->density);\n clone_info->align=draw_info->align;\n clone_info->undercolor=draw_info->undercolor;\n clone_info->border_color=draw_info->border_color;\n if (draw_info->server_name != (char *) NULL)\n (void) CloneString(&clone_info->server_name,draw_info->server_name);\n if (draw_info->dash_pattern != (double *) NULL)\n {\n register ssize_t\n x;", " for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;\n clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,\n sizeof(*clone_info->dash_pattern));\n if (clone_info->dash_pattern == (double *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\n \"UnableToAllocateDashPattern\");\n (void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,\n (size_t) (x+1)*sizeof(*clone_info->dash_pattern));\n }\n clone_info->gradient=draw_info->gradient;\n if (draw_info->gradient.stops != (StopInfo *) NULL)\n {\n size_t\n number_stops;", " number_stops=clone_info->gradient.number_stops;\n clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)\n number_stops,sizeof(*clone_info->gradient.stops));\n if (clone_info->gradient.stops == (StopInfo *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\n \"UnableToAllocateDashPattern\");\n (void) CopyMagickMemory(clone_info->gradient.stops,\n draw_info->gradient.stops,(size_t) number_stops*\n sizeof(*clone_info->gradient.stops));\n }\n if (draw_info->clip_mask != (char *) NULL)\n (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);\n clone_info->bounds=draw_info->bounds;\n clone_info->clip_units=draw_info->clip_units;\n clone_info->render=draw_info->render;\n clone_info->alpha=draw_info->alpha;\n clone_info->element_reference=draw_info->element_reference;\n clone_info->debug=IsEventLogging();\n exception=DestroyExceptionInfo(exception);\n return(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ C o n v e r t P a t h T o P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ConvertPathToPolygon() converts a path to the more efficient sorted\n% rendering form.\n%\n% The format of the ConvertPathToPolygon method is:\n%\n% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,\n% const PathInfo *path_info)\n%\n% A description of each parameter follows:\n%\n% o Method ConvertPathToPolygon returns the path in a more efficient sorted\n% rendering form of type PolygonInfo.\n%\n% o draw_info: Specifies a pointer to an DrawInfo structure.\n%\n% o path_info: Specifies a pointer to an PathInfo structure.\n%\n%\n*/", "#if defined(__cplusplus) || defined(c_plusplus)\nextern \"C\" {\n#endif", "static int CompareEdges(const void *x,const void *y)\n{\n register const EdgeInfo\n *p,\n *q;", " /*\n Compare two edges.\n */\n p=(const EdgeInfo *) x;\n q=(const EdgeInfo *) y;\n if ((p->points[0].y-MagickEpsilon) > q->points[0].y)\n return(1);\n if ((p->points[0].y+MagickEpsilon) < q->points[0].y)\n return(-1);\n if ((p->points[0].x-MagickEpsilon) > q->points[0].x)\n return(1);\n if ((p->points[0].x+MagickEpsilon) < q->points[0].x)\n return(-1);\n if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-\n (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)\n return(1);\n return(-1);\n}", "#if defined(__cplusplus) || defined(c_plusplus)\n}\n#endif", "static void LogPolygonInfo(const PolygonInfo *polygon_info)\n{\n register EdgeInfo\n *p;", " register ssize_t\n i,\n j;", " (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin active-edge\");\n p=polygon_info->edges;\n for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" edge %.20g:\",\n (double) i);\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" direction: %s\",\n p->direction != MagickFalse ? \"down\" : \"up\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" ghostline: %s\",\n p->ghostline != MagickFalse ? \"transparent\" : \"opaque\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" bounds: %g %g - %g %g\",p->bounds.x1,p->bounds.y1,\n p->bounds.x2,p->bounds.y2);\n for (j=0; j < (ssize_t) p->number_points; j++)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %g %g\",\n p->points[j].x,p->points[j].y);\n p++;\n }\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end active-edge\");\n}", "static void ReversePoints(PointInfo *points,const size_t number_points)\n{\n PointInfo\n point;", " register ssize_t\n i;", " for (i=0; i < (ssize_t) (number_points >> 1); i++)\n {\n point=points[i];\n points[i]=points[number_points-(i+1)];\n points[number_points-(i+1)]=point;\n }\n}", "static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)\n{\n long\n direction,\n next_direction;", " PointInfo\n point,\n *points;", " PolygonInfo\n *polygon_info;", " SegmentInfo\n bounds;", " register ssize_t\n i,\n n;", " MagickBooleanType\n ghostline;", " size_t\n edge,\n number_edges,\n number_points;", " /*\n Convert a path to the more efficient sorted rendering form.\n */\n polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));\n if (polygon_info == (PolygonInfo *) NULL)\n return((PolygonInfo *) NULL);\n number_edges=16;\n polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n direction=0;\n edge=0;\n ghostline=MagickFalse;\n n=0;\n number_points=0;\n points=(PointInfo *) NULL;\n (void) ResetMagickMemory(&point,0,sizeof(point));\n (void) ResetMagickMemory(&bounds,0,sizeof(bounds));\n for (i=0; path_info[i].code != EndCode; i++)\n {\n if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||\n (path_info[i].code == GhostlineCode))\n {\n /*\n Move to.\n */\n if ((points != (PointInfo *) NULL) && (n >= 2))\n {\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n points=(PointInfo *) NULL;\n ghostline=MagickFalse;\n edge++;\n }\n if (points == (PointInfo *) NULL)\n {\n number_points=16;\n points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;\n point=path_info[i].point;\n points[0]=point;\n bounds.x1=point.x;\n bounds.x2=point.x;\n direction=0;\n n=1;\n continue;\n }\n /*\n Line to.\n */\n next_direction=((path_info[i].point.y > point.y) ||\n ((path_info[i].point.y == point.y) &&\n (path_info[i].point.x > point.x))) ? 1 : -1;\n if ((points != (PointInfo *) NULL) && (direction != 0) &&\n (direction != next_direction))\n {\n /*\n New edge.\n */\n point=points[n-1];\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n number_points=16;\n points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n n=1;\n ghostline=MagickFalse;\n points[0]=point;\n bounds.x1=point.x;\n bounds.x2=point.x;\n edge++;\n }\n direction=next_direction;\n if (points == (PointInfo *) NULL)\n continue;\n if (n == (ssize_t) number_points)\n {\n number_points<<=1;\n points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,\n sizeof(*points));\n if (points == (PointInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n point=path_info[i].point;\n points[n]=point;\n if (point.x < bounds.x1)\n bounds.x1=point.x;\n if (point.x > bounds.x2)\n bounds.x2=point.x;\n n++;\n }\n if (points != (PointInfo *) NULL)\n {\n if (n < 2)\n points=(PointInfo *) RelinquishMagickMemory(points);\n else\n {\n if (edge == number_edges)\n {\n number_edges<<=1;\n polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(\n polygon_info->edges,(size_t) number_edges,\n sizeof(*polygon_info->edges));\n if (polygon_info->edges == (EdgeInfo *) NULL)\n return((PolygonInfo *) NULL);\n }\n polygon_info->edges[edge].number_points=(size_t) n;\n polygon_info->edges[edge].scanline=(-1.0);\n polygon_info->edges[edge].highwater=0;\n polygon_info->edges[edge].ghostline=ghostline;\n polygon_info->edges[edge].direction=(ssize_t) (direction > 0);\n if (direction < 0)\n ReversePoints(points,(size_t) n);\n polygon_info->edges[edge].points=points;\n polygon_info->edges[edge].bounds=bounds;\n polygon_info->edges[edge].bounds.y1=points[0].y;\n polygon_info->edges[edge].bounds.y2=points[n-1].y;\n ghostline=MagickFalse;\n edge++;\n }\n }\n polygon_info->number_edges=edge;\n qsort(polygon_info->edges,(size_t) polygon_info->number_edges,\n sizeof(*polygon_info->edges),CompareEdges);\n if (IsEventLogging() != MagickFalse)\n LogPolygonInfo(polygon_info);\n return(polygon_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ C o n v e r t P r i m i t i v e T o P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector\n% path structure.\n%\n% The format of the ConvertPrimitiveToPath method is:\n%\n% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,\n% const PrimitiveInfo *primitive_info)\n%\n% A description of each parameter follows:\n%\n% o Method ConvertPrimitiveToPath returns a vector path structure of type\n% PathInfo.\n%\n% o draw_info: a structure of type DrawInfo.\n%\n% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.\n%\n%\n*/", "static void LogPathInfo(const PathInfo *path_info)\n{\n register const PathInfo\n *p;", " (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin vector-path\");\n for (p=path_info; p->code != EndCode; p++)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %g %g %s\",p->point.x,p->point.y,p->code == GhostlineCode ?\n \"moveto ghostline\" : p->code == OpenCode ? \"moveto open\" :\n p->code == MoveToCode ? \"moveto\" : p->code == LineToCode ? \"lineto\" :\n \"?\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end vector-path\");\n}", "static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)\n{\n PathInfo\n *path_info;", " PathInfoCode\n code;", " PointInfo\n p,\n q;", " register ssize_t\n i,\n n;", " ssize_t\n coordinates,\n start;", " /*\n Converts a PrimitiveInfo structure into a vector path structure.\n */\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n case ColorPrimitive:\n case ImagePrimitive:\n case PointPrimitive:\n case TextPrimitive:\n return((PathInfo *) NULL);\n default:\n break;\n }\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),\n sizeof(*path_info));\n if (path_info == (PathInfo *) NULL)\n return((PathInfo *) NULL);\n coordinates=0;\n n=0;\n p.x=(-1.0);\n p.y=(-1.0);\n q.x=(-1.0);\n q.y=(-1.0);\n start=0;\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n code=LineToCode;\n if (coordinates <= 0)\n {\n coordinates=(ssize_t) primitive_info[i].coordinates;\n p=primitive_info[i].point;\n start=n;\n code=MoveToCode;\n }\n coordinates--;\n /*\n Eliminate duplicate points.\n */\n if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||\n (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))\n {\n path_info[n].code=code;\n path_info[n].point=primitive_info[i].point;\n q=primitive_info[i].point;\n n++;\n }\n if (coordinates > 0)\n continue;\n if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) &&\n (fabs(p.y-primitive_info[i].point.y) < MagickEpsilon))\n continue;\n /*\n Mark the p point as open if it does not match the q.\n */\n path_info[start].code=OpenCode;\n path_info[n].code=GhostlineCode;\n path_info[n].point=primitive_info[i].point;\n n++;\n path_info[n].code=LineToCode;\n path_info[n].point=p;\n n++;\n }\n path_info[n].code=EndCode;\n path_info[n].point.x=0.0;\n path_info[n].point.y=0.0;\n if (IsEventLogging() != MagickFalse)\n LogPathInfo(path_info);\n return(path_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D e s t r o y D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyDrawInfo() deallocates memory associated with an DrawInfo\n% structure.\n%\n% The format of the DestroyDrawInfo method is:\n%\n% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)\n{\n if (draw_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n if (draw_info->primitive != (char *) NULL)\n draw_info->primitive=DestroyString(draw_info->primitive);\n if (draw_info->text != (char *) NULL)\n draw_info->text=DestroyString(draw_info->text);\n if (draw_info->geometry != (char *) NULL)\n draw_info->geometry=DestroyString(draw_info->geometry);\n if (draw_info->fill_pattern != (Image *) NULL)\n draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);\n if (draw_info->stroke_pattern != (Image *) NULL)\n draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);\n if (draw_info->font != (char *) NULL)\n draw_info->font=DestroyString(draw_info->font);\n if (draw_info->metrics != (char *) NULL)\n draw_info->metrics=DestroyString(draw_info->metrics);\n if (draw_info->family != (char *) NULL)\n draw_info->family=DestroyString(draw_info->family);\n if (draw_info->encoding != (char *) NULL)\n draw_info->encoding=DestroyString(draw_info->encoding);\n if (draw_info->density != (char *) NULL)\n draw_info->density=DestroyString(draw_info->density);\n if (draw_info->server_name != (char *) NULL)\n draw_info->server_name=(char *)\n RelinquishMagickMemory(draw_info->server_name);\n if (draw_info->dash_pattern != (double *) NULL)\n draw_info->dash_pattern=(double *) RelinquishMagickMemory(\n draw_info->dash_pattern);\n if (draw_info->gradient.stops != (StopInfo *) NULL)\n draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(\n draw_info->gradient.stops);\n if (draw_info->clip_mask != (char *) NULL)\n draw_info->clip_mask=DestroyString(draw_info->clip_mask);\n draw_info->signature=(~MagickCoreSignature);\n draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);\n return(draw_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D e s t r o y E d g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyEdge() destroys the specified polygon edge.\n%\n% The format of the DestroyEdge method is:\n%\n% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)\n%\n% A description of each parameter follows:\n%\n% o polygon_info: Specifies a pointer to an PolygonInfo structure.\n%\n% o edge: the polygon edge number to destroy.\n%\n*/\nstatic size_t DestroyEdge(PolygonInfo *polygon_info,\n const size_t edge)\n{\n assert(edge < polygon_info->number_edges);\n polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(\n polygon_info->edges[edge].points);\n polygon_info->number_edges--;\n if (edge < polygon_info->number_edges)\n (void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,\n (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));\n return(polygon_info->number_edges);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D e s t r o y P o l y g o n I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DestroyPolygonInfo() destroys the PolygonInfo data structure.\n%\n% The format of the DestroyPolygonInfo method is:\n%\n% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)\n%\n% A description of each parameter follows:\n%\n% o polygon_info: Specifies a pointer to an PolygonInfo structure.\n%\n*/\nstatic PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)\n{\n register ssize_t\n i;", " for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n polygon_info->edges[i].points=(PointInfo *)\n RelinquishMagickMemory(polygon_info->edges[i].points);\n polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);\n return((PolygonInfo *) RelinquishMagickMemory(polygon_info));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w A f f i n e I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawAffineImage() composites the source over the destination image as\n% dictated by the affine transform.\n%\n% The format of the DrawAffineImage method is:\n%\n% MagickBooleanType DrawAffineImage(Image *image,const Image *source,\n% const AffineMatrix *affine,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o source: the source image.\n%\n% o affine: the affine transform.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,\n const double y,const SegmentInfo *edge)\n{\n double\n intercept,\n z;", " register double\n x;", " SegmentInfo\n inverse_edge;", " /*\n Determine left and right edges.\n */\n inverse_edge.x1=edge->x1;\n inverse_edge.y1=edge->y1;\n inverse_edge.x2=edge->x2;\n inverse_edge.y2=edge->y2;\n z=affine->ry*y+affine->tx;\n if (affine->sx >= MagickEpsilon)\n {\n intercept=(-z/affine->sx);\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z+(double) image->columns)/affine->sx;\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if (affine->sx < -MagickEpsilon)\n {\n intercept=(-z+(double) image->columns)/affine->sx;\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z/affine->sx);\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))\n {\n inverse_edge.x2=edge->x1;\n return(inverse_edge);\n }\n /*\n Determine top and bottom edges.\n */\n z=affine->sy*y+affine->ty;\n if (affine->rx >= MagickEpsilon)\n {\n intercept=(-z/affine->rx);\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z+(double) image->rows)/affine->rx;\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if (affine->rx < -MagickEpsilon)\n {\n intercept=(-z+(double) image->rows)/affine->rx;\n x=intercept;\n if (x > inverse_edge.x1)\n inverse_edge.x1=x;\n intercept=(-z/affine->rx);\n x=intercept;\n if (x < inverse_edge.x2)\n inverse_edge.x2=x;\n }\n else\n if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))\n {\n inverse_edge.x2=edge->x2;\n return(inverse_edge);\n }\n return(inverse_edge);\n}", "static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)\n{\n AffineMatrix\n inverse_affine;", " double\n determinant;", " determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*\n affine->ry);\n inverse_affine.sx=determinant*affine->sy;\n inverse_affine.rx=determinant*(-affine->rx);\n inverse_affine.ry=determinant*(-affine->ry);\n inverse_affine.sy=determinant*affine->sx;\n inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*\n inverse_affine.ry;\n inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*\n inverse_affine.sy;\n return(inverse_affine);\n}", "MagickExport MagickBooleanType DrawAffineImage(Image *image,\n const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)\n{\n AffineMatrix\n inverse_affine;", " CacheView\n *image_view,\n *source_view;", " MagickBooleanType\n status;", " PixelInfo\n zero;", " PointInfo\n extent[4],\n min,\n max;", " register ssize_t\n i;", " SegmentInfo\n edge;", " ssize_t\n start,\n stop,\n y;", " /*\n Determine bounding box.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(source != (const Image *) NULL);\n assert(source->signature == MagickCoreSignature);\n assert(affine != (AffineMatrix *) NULL);\n extent[0].x=0.0;\n extent[0].y=0.0;\n extent[1].x=(double) source->columns-1.0;\n extent[1].y=0.0;\n extent[2].x=(double) source->columns-1.0;\n extent[2].y=(double) source->rows-1.0;\n extent[3].x=0.0;\n extent[3].y=(double) source->rows-1.0;\n for (i=0; i < 4; i++)\n {\n PointInfo\n point;", " point=extent[i];\n extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;\n extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;\n }\n min=extent[0];\n max=extent[0];\n for (i=1; i < 4; i++)\n {\n if (min.x > extent[i].x)\n min.x=extent[i].x;\n if (min.y > extent[i].y)\n min.y=extent[i].y;\n if (max.x < extent[i].x)\n max.x=extent[i].x;\n if (max.y < extent[i].y)\n max.y=extent[i].y;\n }\n /*\n Affine transform image.\n */\n if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)\n return(MagickFalse);\n status=MagickTrue;\n edge.x1=MagickMax(min.x,0.0);\n edge.y1=MagickMax(min.y,0.0);\n edge.x2=MagickMin(max.x,(double) image->columns-1.0);\n edge.y2=MagickMin(max.y,(double) image->rows-1.0);\n inverse_affine=InverseAffineMatrix(affine);\n GetPixelInfo(image,&zero);\n start=(ssize_t) ceil(edge.y1-0.5);\n stop=(ssize_t) floor(edge.y2+0.5);\n source_view=AcquireVirtualCacheView(source,exception);\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(source,image,1,1)\n#endif\n for (y=start; y <= stop; y++)\n {\n PixelInfo\n composite,\n pixel;", " PointInfo\n point;", " register ssize_t\n x;", " register Quantum\n *magick_restrict q;", " SegmentInfo\n inverse_edge;", " ssize_t\n x_offset;", " inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);\n if (inverse_edge.x2 < inverse_edge.x1)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-\n 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),\n 1,exception);\n if (q == (Quantum *) NULL)\n continue;\n pixel=zero;\n composite=zero;\n x_offset=0;\n for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)\n {\n point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+\n inverse_affine.tx;\n point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+\n inverse_affine.ty;\n (void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,\n point.x,point.y,&pixel,exception);\n GetPixelInfoPixel(image,q,&composite);\n CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,\n &composite);\n SetPixelViaPixelInfo(image,&composite,q);\n x_offset++;\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n source_view=DestroyCacheView(source_view);\n image_view=DestroyCacheView(image_view);\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w B o u n d i n g R e c t a n g l e s %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawBoundingRectangles() draws the bounding rectangles on the image. This\n% is only useful for developers debugging the rendering algorithm.\n%\n% The format of the DrawBoundingRectangles method is:\n%\n% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,\n% PolygonInfo *polygon_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o polygon_info: Specifies a pointer to a PolygonInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,\n const PolygonInfo *polygon_info,ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " double\n mid;", " PointInfo\n end,\n resolution,\n start;", " PrimitiveInfo\n primitive_info[6];", " register ssize_t\n i;", " SegmentInfo\n bounds;", " ssize_t\n coordinates;", " clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,&clone_info->fill,\n exception);\n resolution.x=DefaultResolution;\n resolution.y=DefaultResolution;\n if (clone_info->density != (char *) NULL)\n {\n GeometryInfo\n geometry_info;", " MagickStatusType\n flags;", " flags=ParseGeometry(clone_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == MagickFalse)\n resolution.y=resolution.x;\n }\n mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*\n clone_info->stroke_width/2.0;\n bounds.x1=0.0;\n bounds.y1=0.0;\n bounds.x2=0.0;\n bounds.y2=0.0;\n if (polygon_info != (PolygonInfo *) NULL)\n {\n bounds=polygon_info->edges[0].bounds;\n for (i=1; i < (ssize_t) polygon_info->number_edges; i++)\n {\n if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)\n bounds.x1=polygon_info->edges[i].bounds.x1;\n if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)\n bounds.y1=polygon_info->edges[i].bounds.y1;\n if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)\n bounds.x2=polygon_info->edges[i].bounds.x2;\n if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)\n bounds.y2=polygon_info->edges[i].bounds.y2;\n }\n bounds.x1-=mid;\n bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)\n image->columns ? (double) image->columns-1 : bounds.x1;\n bounds.y1-=mid;\n bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)\n image->rows ? (double) image->rows-1 : bounds.y1;\n bounds.x2+=mid;\n bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)\n image->columns ? (double) image->columns-1 : bounds.x2;\n bounds.y2+=mid;\n bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)\n image->rows ? (double) image->rows-1 : bounds.y2;\n for (i=0; i < (ssize_t) polygon_info->number_edges; i++)\n {\n if (polygon_info->edges[i].direction != 0)\n (void) QueryColorCompliance(\"red\",AllCompliance,&clone_info->stroke,\n exception);\n else\n (void) QueryColorCompliance(\"green\",AllCompliance,&clone_info->stroke,\n exception);\n start.x=(double) (polygon_info->edges[i].bounds.x1-mid);\n start.y=(double) (polygon_info->edges[i].bounds.y1-mid);\n end.x=(double) (polygon_info->edges[i].bounds.x2+mid);\n end.y=(double) (polygon_info->edges[i].bounds.y2+mid);\n primitive_info[0].primitive=RectanglePrimitive;\n TraceRectangle(primitive_info,start,end);\n primitive_info[0].method=ReplaceMethod;\n coordinates=(ssize_t) primitive_info[0].coordinates;\n primitive_info[coordinates].primitive=UndefinedPrimitive;\n (void) DrawPrimitive(image,clone_info,primitive_info,exception);\n }\n }\n (void) QueryColorCompliance(\"blue\",AllCompliance,&clone_info->stroke,\n exception);\n start.x=(double) (bounds.x1-mid);\n start.y=(double) (bounds.y1-mid);\n end.x=(double) (bounds.x2+mid);\n end.y=(double) (bounds.y2+mid);\n primitive_info[0].primitive=RectanglePrimitive;\n TraceRectangle(primitive_info,start,end);\n primitive_info[0].method=ReplaceMethod;\n coordinates=(ssize_t) primitive_info[0].coordinates;\n primitive_info[coordinates].primitive=UndefinedPrimitive;\n (void) DrawPrimitive(image,clone_info,primitive_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w C l i p P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawClipPath() draws the clip path on the image mask.\n%\n% The format of the DrawClipPath method is:\n%\n% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,\n% const char *name,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o name: the name of the clip path.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nMagickExport MagickBooleanType DrawClipPath(Image *image,\n const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];", " Image\n *clip_mask;", " const char\n *value;", " DrawInfo\n *clone_info;", " MagickStatusType\n status;", " assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n (void) FormatLocaleString(filename,MagickPathExtent,\"%s\",name);\n value=GetImageArtifact(image,filename);\n if (value == (const char *) NULL)\n return(MagickFalse);\n clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);\n if (clip_mask == (Image *) NULL)\n return(MagickFalse);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,\n &clip_mask->background_color,exception);", " clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha;", " (void) SetImageBackgroundColor(clip_mask,exception);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"\\nbegin clip-path %s\",\n draw_info->clip_mask);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->primitive,value);\n (void) QueryColorCompliance(\"#ffffff\",AllCompliance,&clone_info->fill,\n exception);\n clone_info->clip_mask=(char *) NULL;\n status=NegateImage(clip_mask,MagickFalse,exception);\n (void) SetImageMask(image,ReadPixelMask,clip_mask,exception);\n clip_mask=DestroyImage(clip_mask);\n status&=DrawImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end clip-path\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w D a s h P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the\n% image while respecting the dash offset and dash pattern attributes.\n%\n% The format of the DrawDashPolygon method is:\n%\n% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,\n% const PrimitiveInfo *primitive_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o image: the image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " double\n length,\n maximum_length,\n offset,\n scale,\n total_length;", " MagickStatusType\n status;", " PrimitiveInfo\n *dash_polygon;", " register ssize_t\n i;", " register double\n dx,\n dy;", " size_t\n number_vertices;", " ssize_t\n j,\n n;", " assert(draw_info != (const DrawInfo *) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin draw-dash\");\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n number_vertices=(size_t) i;\n dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (2UL*number_vertices+1UL),sizeof(*dash_polygon));\n if (dash_polygon == (PrimitiveInfo *) NULL)\n return(MagickFalse);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->miterlimit=0;\n dash_polygon[0]=primitive_info[0];\n scale=ExpandAffine(&draw_info->affine);\n length=scale*(draw_info->dash_pattern[0]-0.5);\n offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;\n j=1;\n for (n=0; offset > 0.0; j=0)\n {\n if (draw_info->dash_pattern[n] <= 0.0)\n break;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n if (offset > length)\n {\n offset-=length;\n n++;\n length=scale*(draw_info->dash_pattern[n]+0.5);\n continue;\n }\n if (offset < length)\n {\n length-=offset;\n offset=0.0;\n break;\n }\n offset=0.0;\n n++;\n }\n status=MagickTrue;\n maximum_length=0.0;\n total_length=0.0;", " for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)", " {\n dx=primitive_info[i].point.x-primitive_info[i-1].point.x;\n dy=primitive_info[i].point.y-primitive_info[i-1].point.y;\n maximum_length=hypot((double) dx,dy);\n if (length == 0.0)\n {\n n++;\n if (draw_info->dash_pattern[n] == 0.0)\n n=0;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n }\n for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )\n {\n total_length+=length;\n if ((n & 0x01) != 0)\n {\n dash_polygon[0]=primitive_info[0];\n dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*\n total_length/maximum_length);\n dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*\n total_length/maximum_length);\n j=1;\n }\n else\n {\n if ((j+1) > (ssize_t) (2*number_vertices))\n break;\n dash_polygon[j]=primitive_info[i-1];\n dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*\n total_length/maximum_length);\n dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*\n total_length/maximum_length);\n dash_polygon[j].coordinates=1;\n j++;\n dash_polygon[0].coordinates=(size_t) j;\n dash_polygon[j].primitive=UndefinedPrimitive;\n status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);\n }\n n++;\n if (draw_info->dash_pattern[n] == 0.0)\n n=0;\n length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));\n }\n length-=(maximum_length-total_length);\n if ((n & 0x01) != 0)\n continue;\n dash_polygon[j]=primitive_info[i];\n dash_polygon[j].coordinates=1;\n j++;\n }\n if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))\n {\n dash_polygon[j]=primitive_info[i-1];\n dash_polygon[j].point.x+=MagickEpsilon;\n dash_polygon[j].point.y+=MagickEpsilon;\n dash_polygon[j].coordinates=1;\n j++;\n dash_polygon[0].coordinates=(size_t) j;\n dash_polygon[j].primitive=UndefinedPrimitive;\n status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);\n }\n dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-dash\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawImage() draws a graphic primitive on your image. The primitive\n% may be represented as a string or filename. Precede the filename with an\n% \"at\" sign (@) and the contents of the file are drawn on the image. You\n% can affect how text is drawn by setting one or more members of the draw\n% info structure.\n%\n% The format of the DrawImage method is:\n%\n% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline MagickBooleanType IsPoint(const char *point)\n{\n char\n *p;", " double\n value;", " value=StringToDouble(point,&p);\n return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);\n}", "static inline void TracePoint(PrimitiveInfo *primitive_info,\n const PointInfo point)\n{\n primitive_info->coordinates=1;\n primitive_info->point=point;\n}", "MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,\n ExceptionInfo *exception)\n{\n#define RenderImageTag \"Render/Image\"", " AffineMatrix\n affine,\n current;", " char\n keyword[MagickPathExtent],\n geometry[MagickPathExtent],\n pattern[MagickPathExtent],\n *primitive,\n *token;", " const char\n *q;", " DrawInfo\n **graphic_context;", " MagickBooleanType\n proceed;", " MagickStatusType\n status;", " double\n angle,\n factor,\n primitive_extent;", " PointInfo\n point;", " PrimitiveInfo\n *primitive_info;", " PrimitiveType\n primitive_type;", " register const char\n *p;", " register ssize_t\n i,\n x;", " SegmentInfo\n bounds;", " size_t\n extent,\n length,\n number_points,\n number_stops;", " ssize_t\n j,\n k,\n n;", " StopInfo\n *stops;", " /*\n Ensure the annotation info is valid.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n if ((draw_info->primitive == (char *) NULL) ||\n (*draw_info->primitive == '\\0'))\n return(MagickFalse);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"begin draw-image\");\n if (*draw_info->primitive != '@')\n primitive=AcquireString(draw_info->primitive);\n else\n primitive=FileToString(draw_info->primitive+1,~0UL,exception);\n if (primitive == (char *) NULL)\n return(MagickFalse);\n primitive_extent=(double) strlen(primitive);\n (void) SetImageArtifact(image,\"MVG\",primitive);\n n=0;\n number_stops=0;\n stops=(StopInfo *) NULL;\n /*\n Allocate primitive info memory.\n */\n graphic_context=(DrawInfo **) AcquireMagickMemory(\n sizeof(*graphic_context));\n if (graphic_context == (DrawInfo **) NULL)\n {\n primitive=DestroyString(primitive);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n number_points=6553;\n primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,\n sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n primitive=DestroyString(primitive);\n for ( ; n >= 0; n--)\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n graphic_context[n]->viewbox=image->page;\n if ((image->page.width == 0) || (image->page.height == 0))\n {\n graphic_context[n]->viewbox.width=image->columns;\n graphic_context[n]->viewbox.height=image->rows;\n }\n token=AcquireString(primitive);\n extent=strlen(token)+MagickPathExtent;\n if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)\n return(MagickFalse);\n status=MagickTrue;\n for (q=primitive; *q != '\\0'; )\n {\n /*\n Interpret graphic primitive.\n */", " GetNextToken(q,&q,MagickPathExtent,keyword);", " if (*keyword == '\\0')\n break;\n if (*keyword == '#')\n {\n /*\n Comment.\n */\n while ((*q != '\\n') && (*q != '\\0'))\n q++;\n continue;\n }\n p=q-strlen(keyword)-1;\n primitive_type=UndefinedPrimitive;\n current=graphic_context[n]->affine;\n GetAffineMatrix(&affine);\n switch (*keyword)\n {\n case ';':\n break;\n case 'a':\n case 'A':\n {\n if (LocaleCompare(\"affine\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.sx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.rx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ry=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.sy=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.tx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ty=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"alpha\",keyword) == 0)\n {\n primitive_type=AlphaPrimitive;\n break;\n }\n if (LocaleCompare(\"arc\",keyword) == 0)\n {\n primitive_type=ArcPrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'b':\n case 'B':\n {\n if (LocaleCompare(\"bezier\",keyword) == 0)\n {\n primitive_type=BezierPrimitive;\n break;\n }\n if (LocaleCompare(\"border-color\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->border_color,exception);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'c':\n case 'C':\n {\n if (LocaleCompare(\"clip-path\",keyword) == 0)\n {\n /*\n Create clip mask.\n */\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->clip_mask,token);\n (void) DrawClipPath(image,graphic_context[n],\n graphic_context[n]->clip_mask,exception);\n break;\n }\n if (LocaleCompare(\"clip-rule\",keyword) == 0)\n {\n ssize_t\n fill_rule;", " GetNextToken(q,&q,extent,token);\n fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,\n token);\n if (fill_rule == -1)\n status=MagickFalse;\n else\n graphic_context[n]->fill_rule=(FillRule) fill_rule;\n break;\n }\n if (LocaleCompare(\"clip-units\",keyword) == 0)\n {\n ssize_t\n clip_units;", " GetNextToken(q,&q,extent,token);\n clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,\n token);\n if (clip_units == -1)\n {\n status=MagickFalse;\n break;\n }\n graphic_context[n]->clip_units=(ClipPathUnits) clip_units;\n if (clip_units == ObjectBoundingBox)\n {\n GetAffineMatrix(&current);\n affine.sx=draw_info->bounds.x2;\n affine.sy=draw_info->bounds.y2;\n affine.tx=draw_info->bounds.x1;\n affine.ty=draw_info->bounds.y1;\n break;\n }\n break;\n }\n if (LocaleCompare(\"circle\",keyword) == 0)\n {\n primitive_type=CirclePrimitive;\n break;\n }\n if (LocaleCompare(\"color\",keyword) == 0)\n {\n primitive_type=ColorPrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'd':\n case 'D':\n {\n if (LocaleCompare(\"decorate\",keyword) == 0)\n {\n ssize_t\n decorate;", " GetNextToken(q,&q,extent,token);\n decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,\n token);\n if (decorate == -1)\n status=MagickFalse;\n else\n graphic_context[n]->decorate=(DecorationType) decorate;\n break;\n }\n if (LocaleCompare(\"density\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->density,token);\n break;\n }\n if (LocaleCompare(\"direction\",keyword) == 0)\n {\n ssize_t\n direction;", " GetNextToken(q,&q,extent,token);\n direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,\n token);\n if (direction == -1)\n status=MagickFalse;\n else\n graphic_context[n]->direction=(DirectionType) direction;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'e':\n case 'E':\n {\n if (LocaleCompare(\"ellipse\",keyword) == 0)\n {\n primitive_type=EllipsePrimitive;\n break;\n }\n if (LocaleCompare(\"encoding\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->encoding,token);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'f':\n case 'F':\n {\n if (LocaleCompare(\"fill\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(pattern,MagickPathExtent,\"%s\",token);\n if (GetImageArtifact(image,pattern) != (const char *) NULL)\n (void) DrawPatternPath(image,draw_info,token,\n &graphic_context[n]->fill_pattern,exception);\n else\n {\n status&=QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->fill,exception);\n if (status == MagickFalse)\n {\n ImageInfo\n *pattern_info;", " pattern_info=AcquireImageInfo();\n (void) CopyMagickString(pattern_info->filename,token,\n MagickPathExtent);\n graphic_context[n]->fill_pattern=ReadImage(pattern_info,\n exception);\n CatchException(exception);\n pattern_info=DestroyImageInfo(pattern_info);\n }\n }\n break;\n }\n if (LocaleCompare(\"fill-opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->fill.alpha=(double) QuantumRange*\n factor*StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"fill-rule\",keyword) == 0)\n {\n ssize_t\n fill_rule;", " GetNextToken(q,&q,extent,token);\n fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,\n token);\n if (fill_rule == -1)\n status=MagickFalse;\n else\n graphic_context[n]->fill_rule=(FillRule) fill_rule;\n break;\n }\n if (LocaleCompare(\"font\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->font,token);\n if (LocaleCompare(\"none\",token) == 0)\n graphic_context[n]->font=(char *)\n RelinquishMagickMemory(graphic_context[n]->font);\n break;\n }\n if (LocaleCompare(\"font-family\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) CloneString(&graphic_context[n]->family,token);\n break;\n }\n if (LocaleCompare(\"font-size\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"font-stretch\",keyword) == 0)\n {\n ssize_t\n stretch;", " GetNextToken(q,&q,extent,token);\n stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);\n if (stretch == -1)\n status=MagickFalse;\n else\n graphic_context[n]->stretch=(StretchType) stretch;\n break;\n }\n if (LocaleCompare(\"font-style\",keyword) == 0)\n {\n ssize_t\n style;", " GetNextToken(q,&q,extent,token);\n style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);\n if (style == -1)\n status=MagickFalse;\n else\n graphic_context[n]->style=(StyleType) style;\n break;\n }\n if (LocaleCompare(\"font-weight\",keyword) == 0)\n {\n ssize_t\n weight;", " GetNextToken(q,&q,extent,token);\n weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);\n if (weight == -1)", " weight=(ssize_t) StringToUnsignedLong(token);", " graphic_context[n]->weight=(size_t) weight;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'g':\n case 'G':\n {\n if (LocaleCompare(\"gradient-units\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"gravity\",keyword) == 0)\n {\n ssize_t\n gravity;", " GetNextToken(q,&q,extent,token);\n gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);\n if (gravity == -1)\n status=MagickFalse;\n else\n graphic_context[n]->gravity=(GravityType) gravity;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'i':\n case 'I':\n {\n if (LocaleCompare(\"image\",keyword) == 0)\n {\n ssize_t\n compose;", " primitive_type=ImagePrimitive;\n GetNextToken(q,&q,extent,token);\n compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);\n if (compose == -1)\n status=MagickFalse;\n else\n graphic_context[n]->compose=(CompositeOperator) compose;\n break;\n }\n if (LocaleCompare(\"interline-spacing\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->interline_spacing=StringToDouble(token,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(\"interword-spacing\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->interword_spacing=StringToDouble(token,\n (char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'k':\n case 'K':\n {\n if (LocaleCompare(\"kerning\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->kerning=StringToDouble(token,(char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'l':\n case 'L':\n {\n if (LocaleCompare(\"line\",keyword) == 0)\n primitive_type=LinePrimitive;\n else\n status=MagickFalse;\n break;\n }\n case 'o':\n case 'O':\n {\n if (LocaleCompare(\"offset\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0-\n QuantumScale*graphic_context[n]->alpha)*factor*\n StringToDouble(token,(char **) NULL))));\n graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha;\n graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'p':\n case 'P':\n {\n if (LocaleCompare(\"path\",keyword) == 0)\n {\n primitive_type=PathPrimitive;\n break;\n }\n if (LocaleCompare(\"point\",keyword) == 0)\n {\n primitive_type=PointPrimitive;\n break;\n }\n if (LocaleCompare(\"polyline\",keyword) == 0)\n {\n primitive_type=PolylinePrimitive;\n break;\n }\n if (LocaleCompare(\"polygon\",keyword) == 0)\n {\n primitive_type=PolygonPrimitive;\n break;\n }\n if (LocaleCompare(\"pop\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(\"clip-path\",token) == 0)\n break;\n if (LocaleCompare(\"defs\",token) == 0)\n break;\n if (LocaleCompare(\"gradient\",token) == 0)\n break;\n if (LocaleCompare(\"graphic-context\",token) == 0)\n {\n if (n <= 0)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n DrawError,\"UnbalancedGraphicContextPushPop\",\"`%s'\",token);\n n=0;\n break;\n }\n if (graphic_context[n]->clip_mask != (char *) NULL)\n if (LocaleCompare(graphic_context[n]->clip_mask,\n graphic_context[n-1]->clip_mask) != 0)\n (void) SetImageMask(image,ReadPixelMask,(Image *) NULL,\n exception);\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n n--;\n break;\n }\n if (LocaleCompare(\"pattern\",token) == 0)\n break;\n status=MagickFalse;\n break;\n }\n if (LocaleCompare(\"push\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(\"clip-path\",token) == 0)\n {\n char\n name[MagickPathExtent];", " GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(name,MagickPathExtent,\"%s\",token);\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"clip-path\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n (void) SetImageArtifact(image,name,token);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"gradient\",token) == 0)\n {\n char\n key[2*MagickPathExtent],\n name[MagickPathExtent],\n type[MagickPathExtent];", " SegmentInfo\n segment;", " GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(name,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(type,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n segment.x1=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.y1=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.x2=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n segment.y2=StringToDouble(token,(char **) NULL);\n if (LocaleCompare(type,\"radial\") == 0)\n {\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n }\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"gradient\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n bounds.x1=graphic_context[n]->affine.sx*segment.x1+\n graphic_context[n]->affine.ry*segment.y1+\n graphic_context[n]->affine.tx;\n bounds.y1=graphic_context[n]->affine.rx*segment.x1+\n graphic_context[n]->affine.sy*segment.y1+\n graphic_context[n]->affine.ty;\n bounds.x2=graphic_context[n]->affine.sx*segment.x2+\n graphic_context[n]->affine.ry*segment.y2+\n graphic_context[n]->affine.tx;\n bounds.y2=graphic_context[n]->affine.rx*segment.x2+\n graphic_context[n]->affine.sy*segment.y2+\n graphic_context[n]->affine.ty;\n (void) FormatLocaleString(key,MagickPathExtent,\"%s\",name);\n (void) SetImageArtifact(image,key,token);\n (void) FormatLocaleString(key,MagickPathExtent,\"%s-type\",name);\n (void) SetImageArtifact(image,key,type);", " (void) FormatLocaleString(key,MagickPathExtent,\"%s-geometry\",\n name);", " (void) FormatLocaleString(geometry,MagickPathExtent,\n \"%gx%g%+.15g%+.15g\",\n MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),\n MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),\n bounds.x1,bounds.y1);\n (void) SetImageArtifact(image,key,geometry);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"pattern\",token) == 0)\n {\n char\n key[2*MagickPathExtent],\n name[MagickPathExtent];", " RectangleInfo\n pattern_bounds;", " GetNextToken(q,&q,extent,token);\n (void) CopyMagickString(name,token,MagickPathExtent);\n GetNextToken(q,&q,extent,token);\n pattern_bounds.x=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.y=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.width=(size_t) floor(StringToDouble(token,\n (char **) NULL)+0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n pattern_bounds.height=(size_t) floor(StringToDouble(token,\n (char **) NULL)+0.5);\n for (p=q; *q != '\\0'; )\n {\n GetNextToken(q,&q,extent,token);\n if (LocaleCompare(token,\"pop\") != 0)\n continue;\n GetNextToken(q,(const char **) NULL,extent,token);\n if (LocaleCompare(token,\"pattern\") != 0)\n continue;\n break;\n }\n (void) CopyMagickString(token,p,(size_t) (q-p-4+1));\n (void) FormatLocaleString(key,MagickPathExtent,\"%s\",name);\n (void) SetImageArtifact(image,key,token);\n (void) FormatLocaleString(key,MagickPathExtent,\"%s-geometry\",\n name);\n (void) FormatLocaleString(geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double)pattern_bounds.width,\n (double)pattern_bounds.height,(double)pattern_bounds.x,\n (double)pattern_bounds.y);\n (void) SetImageArtifact(image,key,geometry);\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"graphic-context\",token) == 0)\n {\n n++;\n graphic_context=(DrawInfo **) ResizeQuantumMemory(\n graphic_context,(size_t) (n+1),sizeof(*graphic_context));\n if (graphic_context == (DrawInfo **) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,\n graphic_context[n-1]);\n break;\n }\n if (LocaleCompare(\"defs\",token) == 0)\n break;\n status=MagickFalse;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'r':\n case 'R':\n {\n if (LocaleCompare(\"rectangle\",keyword) == 0)\n {\n primitive_type=RectanglePrimitive;\n break;\n }\n if (LocaleCompare(\"rotate\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));\n affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));\n affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));\n affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));\n break;\n }\n if (LocaleCompare(\"roundRectangle\",keyword) == 0)\n {\n primitive_type=RoundRectanglePrimitive;\n break;\n }\n status=MagickFalse;\n break;\n }\n case 's':\n case 'S':\n {\n if (LocaleCompare(\"scale\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.sx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.sy=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"skewX\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.ry=sin(DegreesToRadians(angle));\n break;\n }\n if (LocaleCompare(\"skewY\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n angle=StringToDouble(token,(char **) NULL);\n affine.rx=(-tan(DegreesToRadians(angle)/2.0));\n break;\n }\n if (LocaleCompare(\"stop-color\",keyword) == 0)\n {\n PixelInfo\n stop_color;", " number_stops++;\n if (number_stops == 1)\n stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));\n else if (number_stops > 2)\n stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,\n sizeof(*stops));\n if (stops == (StopInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,&stop_color,\n exception);\n stops[number_stops-1].color=stop_color;\n GetNextToken(q,&q,extent,token);\n stops[number_stops-1].offset=StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) FormatLocaleString(pattern,MagickPathExtent,\"%s\",token);\n if (GetImageArtifact(image,pattern) != (const char *) NULL)\n (void) DrawPatternPath(image,draw_info,token,\n &graphic_context[n]->stroke_pattern,exception);\n else\n {\n status&=QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->stroke,exception);\n if (status == MagickFalse)\n {\n ImageInfo\n *pattern_info;", " pattern_info=AcquireImageInfo();\n (void) CopyMagickString(pattern_info->filename,token,\n MagickPathExtent);\n graphic_context[n]->stroke_pattern=ReadImage(pattern_info,\n exception);\n CatchException(exception);\n pattern_info=DestroyImageInfo(pattern_info);\n }\n }\n break;\n }\n if (LocaleCompare(\"stroke-antialias\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->stroke_antialias=\n StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n break;\n }\n if (LocaleCompare(\"stroke-dasharray\",keyword) == 0)\n {\n if (graphic_context[n]->dash_pattern != (double *) NULL)\n graphic_context[n]->dash_pattern=(double *)\n RelinquishMagickMemory(graphic_context[n]->dash_pattern);\n if (IsPoint(q) != MagickFalse)\n {\n const char\n *r;", " r=q;\n GetNextToken(r,&r,extent,token);\n if (*token == ',')\n GetNextToken(r,&r,extent,token);\n for (x=0; IsPoint(token) != MagickFalse; x++)\n {\n GetNextToken(r,&r,extent,token);\n if (*token == ',')\n GetNextToken(r,&r,extent,token);\n }\n graphic_context[n]->dash_pattern=(double *)\n AcquireQuantumMemory((size_t) (2UL*x+1UL),\n sizeof(*graphic_context[n]->dash_pattern));\n if (graphic_context[n]->dash_pattern == (double *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n for (j=0; j < x; j++)\n {\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->dash_pattern[j]=StringToDouble(token,\n (char **) NULL);\n if (graphic_context[n]->dash_pattern[j] < 0.0)\n status=MagickFalse;\n }\n if ((x & 0x01) != 0)\n for ( ; j < (2*x); j++)\n graphic_context[n]->dash_pattern[j]=\n graphic_context[n]->dash_pattern[j-x];\n graphic_context[n]->dash_pattern[j]=0.0;\n break;\n }\n GetNextToken(q,&q,extent,token);\n break;\n }\n if (LocaleCompare(\"stroke-dashoffset\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->dash_offset=StringToDouble(token,\n (char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke-linecap\",keyword) == 0)\n {\n ssize_t\n linecap;", " GetNextToken(q,&q,extent,token);\n linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);\n if (linecap == -1)\n status=MagickFalse;\n else\n graphic_context[n]->linecap=(LineCap) linecap;\n break;\n }\n if (LocaleCompare(\"stroke-linejoin\",keyword) == 0)\n {\n ssize_t\n linejoin;", " GetNextToken(q,&q,extent,token);\n linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,\n token);\n if (linejoin == -1)\n status=MagickFalse;\n else\n graphic_context[n]->linejoin=(LineJoin) linejoin;\n break;\n }\n if (LocaleCompare(\"stroke-miterlimit\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->miterlimit=StringToUnsignedLong(token);\n break;\n }\n if (LocaleCompare(\"stroke-opacity\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;\n graphic_context[n]->stroke.alpha=(double) QuantumRange*\n factor*StringToDouble(token,(char **) NULL);\n break;\n }\n if (LocaleCompare(\"stroke-width\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->stroke_width=StringToDouble(token,\n (char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 't':\n case 'T':\n {\n if (LocaleCompare(\"text\",keyword) == 0)\n {\n primitive_type=TextPrimitive;\n break;\n }\n if (LocaleCompare(\"text-align\",keyword) == 0)\n {\n ssize_t\n align;", " GetNextToken(q,&q,extent,token);\n align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);\n if (align == -1)\n status=MagickFalse;\n else\n graphic_context[n]->align=(AlignType) align;\n break;\n }\n if (LocaleCompare(\"text-anchor\",keyword) == 0)\n {\n ssize_t\n align;", " GetNextToken(q,&q,extent,token);\n align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);\n if (align == -1)\n status=MagickFalse;\n else\n graphic_context[n]->align=(AlignType) align;\n break;\n }\n if (LocaleCompare(\"text-antialias\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->text_antialias=\n StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n break;\n }\n if (LocaleCompare(\"text-undercolor\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n (void) QueryColorCompliance(token,AllCompliance,\n &graphic_context[n]->undercolor,exception);\n break;\n }\n if (LocaleCompare(\"translate\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n affine.tx=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n affine.ty=StringToDouble(token,(char **) NULL);\n break;\n }\n status=MagickFalse;\n break;\n }\n case 'v':\n case 'V':\n {\n if (LocaleCompare(\"viewbox\",keyword) == 0)\n {\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,\n (char **) NULL)-0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(\n token,(char **) NULL)+0.5);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(\n token,(char **) NULL)+0.5);\n break;\n }\n status=MagickFalse;\n break;\n }\n default:\n {\n status=MagickFalse;\n break;\n }\n }\n if (status == MagickFalse)\n break;\n if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||\n (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))\n {\n graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;\n graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;\n graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;\n graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;\n graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+\n current.tx;\n graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+\n current.ty;\n }\n if (primitive_type == UndefinedPrimitive)\n {\n if (*q == '\\0')\n {\n if (number_stops > 1)\n {\n GradientType\n type;", " type=LinearGradient;\n if (draw_info->gradient.type == RadialGradient)\n type=RadialGradient;\n (void) GradientImage(image,type,PadSpread,stops,number_stops,\n exception);\n }\n if (number_stops > 0)\n stops=(StopInfo *) RelinquishMagickMemory(stops);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %.*s\",\n (int) (q-p),p);\n continue;\n }\n /*\n Parse the primitive attributes.\n */\n i=0;\n j=0;\n primitive_info[0].point.x=0.0;\n primitive_info[0].point.y=0.0;\n for (x=0; *q != '\\0'; x++)\n {\n /*\n Define points.\n */\n if (IsPoint(q) == MagickFalse)\n break;\n GetNextToken(q,&q,extent,token);\n point.x=StringToDouble(token,(char **) NULL);\n GetNextToken(q,&q,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n point.y=StringToDouble(token,(char **) NULL);\n GetNextToken(q,(const char **) NULL,extent,token);\n if (*token == ',')\n GetNextToken(q,&q,extent,token);\n primitive_info[i].primitive=primitive_type;\n primitive_info[i].point=point;\n primitive_info[i].coordinates=0;\n primitive_info[i].method=FloodfillMethod;\n i++;\n if (i < (ssize_t) number_points)\n continue;\n number_points<<=1;\n primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,\n (size_t) number_points,sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n break;\n }\n }\n primitive_info[j].primitive=primitive_type;\n primitive_info[j].coordinates=(size_t) x;\n primitive_info[j].method=FloodfillMethod;\n primitive_info[j].text=(char *) NULL;\n /*\n Circumscribe primitive within a circle.\n */\n bounds.x1=primitive_info[j].point.x;\n bounds.y1=primitive_info[j].point.y;\n bounds.x2=primitive_info[j].point.x;\n bounds.y2=primitive_info[j].point.y;\n for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)\n {\n point=primitive_info[j+k].point;\n if (point.x < bounds.x1)\n bounds.x1=point.x;\n if (point.y < bounds.y1)\n bounds.y1=point.y;\n if (point.x > bounds.x2)\n bounds.x2=point.x;\n if (point.y > bounds.y2)\n bounds.y2=point.y;\n }\n /*\n Speculate how many points our primitive might consume.\n */\n length=primitive_info[j].coordinates;\n switch (primitive_type)\n {\n case RectanglePrimitive:\n {\n length*=5;\n break;\n }\n case RoundRectanglePrimitive:\n {\n double\n alpha,\n beta,\n radius;", " alpha=bounds.x2-bounds.x1;\n beta=bounds.y2-bounds.y1;\n radius=hypot((double) alpha,(double) beta);\n length*=5;\n length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;\n break;\n }\n case BezierPrimitive:\n {\n if (primitive_info[j].coordinates > 107)\n (void) ThrowMagickException(exception,GetMagickModule(),DrawError,\n \"TooManyBezierCoordinates\",\"`%s'\",token);\n length=BezierQuantum*primitive_info[j].coordinates;\n break;\n }\n case PathPrimitive:\n {\n char\n *s,\n *t;", " GetNextToken(q,&q,extent,token);\n length=1;\n t=token;\n for (s=token; *s != '\\0'; s=t)\n {\n double\n value;", " value=StringToDouble(s,&t);\n (void) value;\n if (s == t)\n {\n t++;\n continue;\n }\n length++;\n }\n length=length*BezierQuantum/2;\n break;\n }\n case CirclePrimitive:\n case ArcPrimitive:\n case EllipsePrimitive:\n {\n double\n alpha,\n beta,\n radius;", " alpha=bounds.x2-bounds.x1;\n beta=bounds.y2-bounds.y1;\n radius=hypot((double) alpha,(double) beta);\n length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;\n break;\n }\n default:\n break;\n }\n if ((size_t) (i+length) >= number_points)\n {\n /*\n Resize based on speculative points required by primitive.\n */\n number_points+=length+1;\n primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,\n (size_t) number_points,sizeof(*primitive_info));\n if (primitive_info == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\n image->filename);\n break;\n }\n }\n switch (primitive_type)\n {\n case PointPrimitive:\n default:\n {\n if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n TracePoint(primitive_info+j,primitive_info[j].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case LinePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceLine(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case RectanglePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceRectangle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case RoundRectanglePrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n status=MagickFalse;\n break;\n }\n TraceRoundRectangle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case ArcPrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n primitive_type=UndefinedPrimitive;\n break;\n }\n TraceArc(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case EllipsePrimitive:\n {\n if (primitive_info[j].coordinates != 3)\n {\n status=MagickFalse;\n break;\n }\n TraceEllipse(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point,primitive_info[j+2].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case CirclePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n TraceCircle(primitive_info+j,primitive_info[j].point,\n primitive_info[j+1].point);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case PolylinePrimitive:\n break;\n case PolygonPrimitive:\n {\n primitive_info[i]=primitive_info[j];\n primitive_info[i].coordinates=0;\n primitive_info[j].coordinates++;\n i++;\n break;\n }\n case BezierPrimitive:\n {\n if (primitive_info[j].coordinates < 3)\n {\n status=MagickFalse;\n break;\n }\n TraceBezier(primitive_info+j,primitive_info[j].coordinates);\n i=(ssize_t) (j+primitive_info[j].coordinates);\n break;\n }\n case PathPrimitive:\n {\n i=(ssize_t) (j+TracePath(primitive_info+j,token));\n break;\n }\n case AlphaPrimitive:\n case ColorPrimitive:\n {\n ssize_t\n method;", " if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n GetNextToken(q,&q,extent,token);\n method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);\n if (method == -1)\n status=MagickFalse;\n else\n primitive_info[j].method=(PaintMethod) method;\n break;\n }\n case TextPrimitive:\n {\n if (primitive_info[j].coordinates != 1)\n {\n status=MagickFalse;\n break;\n }\n if (*token != ',')\n GetNextToken(q,&q,extent,token);\n primitive_info[j].text=AcquireString(token);\n break;\n }\n case ImagePrimitive:\n {\n if (primitive_info[j].coordinates != 2)\n {\n status=MagickFalse;\n break;\n }\n GetNextToken(q,&q,extent,token);\n primitive_info[j].text=AcquireString(token);\n break;\n }\n }\n if (primitive_info == (PrimitiveInfo *) NULL)\n break;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" %.*s\",(int) (q-p),p);\n if (status == MagickFalse)\n break;\n primitive_info[i].primitive=UndefinedPrimitive;\n if (i == 0)\n continue;\n /*\n Transform points.\n */\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n point=primitive_info[i].point;\n primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+\n graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;\n primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+\n graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;\n point=primitive_info[i].point;\n if (point.x < graphic_context[n]->bounds.x1)\n graphic_context[n]->bounds.x1=point.x;\n if (point.y < graphic_context[n]->bounds.y1)\n graphic_context[n]->bounds.y1=point.y;\n if (point.x > graphic_context[n]->bounds.x2)\n graphic_context[n]->bounds.x2=point.x;\n if (point.y > graphic_context[n]->bounds.y2)\n graphic_context[n]->bounds.y2=point.y;\n if (primitive_info[i].primitive == ImagePrimitive)\n break;\n if (i >= (ssize_t) number_points)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n }\n if (graphic_context[n]->render != MagickFalse)\n {\n if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&\n (LocaleCompare(graphic_context[n]->clip_mask,\n graphic_context[n-1]->clip_mask) != 0))\n status&=DrawClipPath(image,graphic_context[n],\n graphic_context[n]->clip_mask,exception);\n status&=DrawPrimitive(image,graphic_context[n],primitive_info,\n exception);\n }\n if (primitive_info->text != (char *) NULL)\n primitive_info->text=(char *) RelinquishMagickMemory(\n primitive_info->text);\n proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)\n primitive_extent);\n if (proceed == MagickFalse)\n break;\n if (status == 0)\n break;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end draw-image\");\n /*\n Relinquish resources.\n */\n token=DestroyString(token);\n if (primitive_info != (PrimitiveInfo *) NULL)\n primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);\n primitive=DestroyString(primitive);\n for ( ; n >= 0; n--)\n graphic_context[n]=DestroyDrawInfo(graphic_context[n]);\n graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);\n if (status == MagickFalse)\n ThrowBinaryException(DrawError,\"NonconformingDrawingPrimitiveDefinition\",\n keyword);\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w G r a d i e n t I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawGradientImage() draws a linear gradient on the image.\n%\n% The format of the DrawGradientImage method is:\n%\n% MagickBooleanType DrawGradientImage(Image *image,\n% const DrawInfo *draw_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline double GetStopColorOffset(const GradientInfo *gradient,\n const ssize_t x,const ssize_t y)\n{\n switch (gradient->type)\n {\n case UndefinedGradient:\n case LinearGradient:\n {\n double\n gamma,\n length,\n offset,\n scale;", " PointInfo\n p,\n q;", " const SegmentInfo\n *gradient_vector;", " gradient_vector=(&gradient->gradient_vector);\n p.x=gradient_vector->x2-gradient_vector->x1;\n p.y=gradient_vector->y2-gradient_vector->y1;\n q.x=(double) x-gradient_vector->x1;\n q.y=(double) y-gradient_vector->y1;\n length=sqrt(q.x*q.x+q.y*q.y);\n gamma=sqrt(p.x*p.x+p.y*p.y)*length;\n gamma=PerceptibleReciprocal(gamma);\n scale=p.x*q.x+p.y*q.y;\n offset=gamma*scale*length;\n return(offset);\n }\n case RadialGradient:\n {\n PointInfo\n v;", " if (gradient->spread == RepeatSpread)\n {\n v.x=(double) x-gradient->center.x;\n v.y=(double) y-gradient->center.y;\n return(sqrt(v.x*v.x+v.y*v.y));\n }\n v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(\n gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(\n gradient->angle))))/gradient->radii.x;\n v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(\n gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(\n gradient->angle))))/gradient->radii.y;\n return(sqrt(v.x*v.x+v.y*v.y));\n }\n }\n return(0.0);\n}", "static int StopInfoCompare(const void *x,const void *y)\n{\n StopInfo\n *stop_1,\n *stop_2;", " stop_1=(StopInfo *) x;\n stop_2=(StopInfo *) y;\n if (stop_1->offset > stop_2->offset)\n return(1);\n if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon)\n return(0);\n return(-1);\n}", "MagickExport MagickBooleanType DrawGradientImage(Image *image,\n const DrawInfo *draw_info,ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " const GradientInfo\n *gradient;", " const SegmentInfo\n *gradient_vector;", " double\n length;", " MagickBooleanType\n status;", " PixelInfo\n zero;", " PointInfo\n point;", " RectangleInfo\n bounding_box;", " ssize_t\n y;", " /*\n Draw linear or radial gradient on image.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n gradient=(&draw_info->gradient);\n qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),\n StopInfoCompare);\n gradient_vector=(&gradient->gradient_vector);\n point.x=gradient_vector->x2-gradient_vector->x1;\n point.y=gradient_vector->y2-gradient_vector->y1;\n length=sqrt(point.x*point.x+point.y*point.y);\n bounding_box=gradient->bounding_box;\n status=MagickTrue;\n GetPixelInfo(image,&zero);\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)\n {\n PixelInfo\n composite,\n pixel;", " double\n alpha,\n offset;", " register Quantum\n *magick_restrict q;", " register ssize_t\n i,\n x;", " ssize_t\n j;", " if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n pixel=zero;\n composite=zero;\n offset=GetStopColorOffset(gradient,0,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n switch (gradient->spread)\n {\n case UndefinedSpread:\n case PadSpread:\n {\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n }\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if ((offset < 0.0) || (i == 0))\n composite=gradient->stops[0].color;\n else\n if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n case ReflectSpread:\n {\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type != RadialGradient)\n offset/=length;\n }\n if (offset < 0.0)\n offset=(-offset);\n if ((ssize_t) fmod(offset,2.0) == 0)\n offset=fmod(offset,1.0);\n else\n offset=1.0-fmod(offset,1.0);\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if (i == 0)\n composite=gradient->stops[0].color;\n else\n if (i == (ssize_t) gradient->number_stops)\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n case RepeatSpread:\n {\n MagickBooleanType\n antialias;", " double\n repeat;", " antialias=MagickFalse;\n repeat=0.0;\n if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||\n (y != (ssize_t) ceil(gradient_vector->y1-0.5)))\n {\n offset=GetStopColorOffset(gradient,x,y);\n if (gradient->type == LinearGradient)\n {\n repeat=fmod(offset,length);\n if (repeat < 0.0)\n repeat=length-fmod(-repeat,length);\n else\n repeat=fmod(offset,length);\n antialias=(repeat < length) && ((repeat+1.0) > length) ?\n MagickTrue : MagickFalse;\n offset=repeat/length;\n }\n else\n {\n repeat=fmod(offset,gradient->radius);\n if (repeat < 0.0)\n repeat=gradient->radius-fmod(-repeat,gradient->radius);\n else\n repeat=fmod(offset,gradient->radius);\n antialias=repeat+1.0 > gradient->radius ? MagickTrue :\n MagickFalse;\n offset=repeat/gradient->radius;\n }\n }\n for (i=0; i < (ssize_t) gradient->number_stops; i++)\n if (offset < gradient->stops[i].offset)\n break;\n if (i == 0)\n composite=gradient->stops[0].color;\n else\n if (i == (ssize_t) gradient->number_stops)\n composite=gradient->stops[gradient->number_stops-1].color;\n else\n {\n j=i;\n i--;\n alpha=(offset-gradient->stops[i].offset)/\n (gradient->stops[j].offset-gradient->stops[i].offset);\n if (antialias != MagickFalse)\n {\n if (gradient->type == LinearGradient)\n alpha=length-repeat;\n else\n alpha=gradient->radius-repeat;\n i=0;\n j=(ssize_t) gradient->number_stops-1L;\n }\n CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,\n &gradient->stops[j].color,alpha,&composite);\n }\n break;\n }\n }\n CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,\n &pixel);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w P a t t e r n P a t h %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPatternPath() draws a pattern.\n%\n% The format of the DrawPatternPath method is:\n%\n% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,\n% const char *name,Image **pattern,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o name: the pattern name.\n%\n% o image: the image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nMagickExport MagickBooleanType DrawPatternPath(Image *image,\n const DrawInfo *draw_info,const char *name,Image **pattern,\n ExceptionInfo *exception)\n{\n char\n property[MagickPathExtent];", " const char\n *geometry,\n *path,\n *type;", " DrawInfo\n *clone_info;", " ImageInfo\n *image_info;", " MagickBooleanType\n status;", " assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (const DrawInfo *) NULL);\n assert(name != (const char *) NULL);\n (void) FormatLocaleString(property,MagickPathExtent,\"%s\",name);\n path=GetImageArtifact(image,property);\n if (path == (const char *) NULL)\n return(MagickFalse);\n (void) FormatLocaleString(property,MagickPathExtent,\"%s-geometry\",name);\n geometry=GetImageArtifact(image,property);\n if (geometry == (const char *) NULL)\n return(MagickFalse);\n if ((*pattern) != (Image *) NULL)\n *pattern=DestroyImage(*pattern);\n image_info=AcquireImageInfo();\n image_info->size=AcquireString(geometry);\n *pattern=AcquireImage(image_info,exception);\n image_info=DestroyImageInfo(image_info);\n (void) QueryColorCompliance(\"#000000ff\",AllCompliance,\n &(*pattern)->background_color,exception);\n (void) SetImageBackgroundColor(*pattern,exception);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"begin pattern-path %s %s\",name,geometry);\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->fill_pattern=NewImageList();\n clone_info->stroke_pattern=NewImageList();\n (void) FormatLocaleString(property,MagickPathExtent,\"%s-type\",name);\n type=GetImageArtifact(image,property);\n if (type != (const char *) NULL)\n clone_info->gradient.type=(GradientType) ParseCommandOption(\n MagickGradientOptions,MagickFalse,type);\n (void) CloneString(&clone_info->primitive,path);\n status=DrawImage(*pattern,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\"end pattern-path\");\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w P o l y g o n P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPolygonPrimitive() draws a polygon on the image.\n%\n% The format of the DrawPolygonPrimitive method is:\n%\n% MagickBooleanType DrawPolygonPrimitive(Image *image,\n% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)\n{\n register ssize_t\n i;", " assert(polygon_info != (PolygonInfo **) NULL);\n for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)\n if (polygon_info[i] != (PolygonInfo *) NULL)\n polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);\n polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);\n return(polygon_info);\n}", "static PolygonInfo **AcquirePolygonThreadSet(\n const PrimitiveInfo *primitive_info)\n{\n PathInfo\n *magick_restrict path_info;", " PolygonInfo\n **polygon_info;", " register ssize_t\n i;", " size_t\n number_threads;", " number_threads=(size_t) GetMagickResourceLimit(ThreadResource);\n polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,\n sizeof(*polygon_info));\n if (polygon_info == (PolygonInfo **) NULL)\n return((PolygonInfo **) NULL);\n (void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));\n path_info=ConvertPrimitiveToPath(primitive_info);\n if (path_info == (PathInfo *) NULL)\n return(DestroyPolygonThreadSet(polygon_info));\n for (i=0; i < (ssize_t) number_threads; i++)\n {\n polygon_info[i]=ConvertPathToPolygon(path_info);\n if (polygon_info[i] == (PolygonInfo *) NULL)\n return(DestroyPolygonThreadSet(polygon_info));\n }\n path_info=(PathInfo *) RelinquishMagickMemory(path_info);\n return(polygon_info);\n}", "static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,\n const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,\n const ssize_t y,double *stroke_alpha)\n{\n double\n alpha,\n beta,\n distance,\n subpath_alpha;", " PointInfo\n delta;", " register const PointInfo\n *q;", " register EdgeInfo\n *p;", " register ssize_t\n i;", " ssize_t\n j,\n winding_number;", " /*\n Compute fill & stroke opacity for this (x,y) point.\n */\n *stroke_alpha=0.0;\n subpath_alpha=0.0;\n p=polygon_info->edges;\n for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)\n {\n if ((double) y <= (p->bounds.y1-mid-0.5))\n break;\n if ((double) y > (p->bounds.y2+mid+0.5))\n {\n (void) DestroyEdge(polygon_info,(size_t) j);\n continue;\n }\n if (((double) x <= (p->bounds.x1-mid-0.5)) ||\n ((double) x > (p->bounds.x2+mid+0.5)))\n continue;\n i=(ssize_t) MagickMax((double) p->highwater,1.0);\n for ( ; i < (ssize_t) p->number_points; i++)\n {\n if ((double) y <= (p->points[i-1].y-mid-0.5))\n break;\n if ((double) y > (p->points[i].y+mid+0.5))\n continue;\n if (p->scanline != (double) y)\n {\n p->scanline=(double) y;\n p->highwater=(size_t) i;\n }\n /*\n Compute distance between a point and an edge.\n */\n q=p->points+i-1;\n delta.x=(q+1)->x-q->x;\n delta.y=(q+1)->y-q->y;\n beta=delta.x*(x-q->x)+delta.y*(y-q->y);\n if (beta < 0.0)\n {\n delta.x=(double) x-q->x;\n delta.y=(double) y-q->y;\n distance=delta.x*delta.x+delta.y*delta.y;\n }\n else\n {\n alpha=delta.x*delta.x+delta.y*delta.y;\n if (beta > alpha)\n {\n delta.x=(double) x-(q+1)->x;\n delta.y=(double) y-(q+1)->y;\n distance=delta.x*delta.x+delta.y*delta.y;\n }\n else\n {\n alpha=1.0/alpha;\n beta=delta.x*(y-q->y)-delta.y*(x-q->x);\n distance=alpha*beta*beta;\n }\n }\n /*\n Compute stroke & subpath opacity.\n */\n beta=0.0;\n if (p->ghostline == MagickFalse)\n {\n alpha=mid+0.5;\n if ((*stroke_alpha < 1.0) &&\n (distance <= ((alpha+0.25)*(alpha+0.25))))\n {\n alpha=mid-0.5;\n if (distance <= ((alpha+0.25)*(alpha+0.25)))\n *stroke_alpha=1.0;\n else\n {\n beta=1.0;\n if (distance != 1.0)\n beta=sqrt((double) distance);\n alpha=beta-mid-0.5;\n if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))\n *stroke_alpha=(alpha-0.25)*(alpha-0.25);\n }\n }\n }\n if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))\n continue;\n if (distance <= 0.0)\n {\n subpath_alpha=1.0;\n continue;\n }\n if (distance > 1.0)\n continue;\n if (beta == 0.0)\n {\n beta=1.0;\n if (distance != 1.0)\n beta=sqrt(distance);\n }\n alpha=beta-1.0;\n if (subpath_alpha < (alpha*alpha))\n subpath_alpha=alpha*alpha;\n }\n }\n /*\n Compute fill opacity.\n */\n if (fill == MagickFalse)\n return(0.0);\n if (subpath_alpha >= 1.0)\n return(1.0);\n /*\n Determine winding number.\n */\n winding_number=0;\n p=polygon_info->edges;\n for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)\n {\n if ((double) y <= p->bounds.y1)\n break;\n if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))\n continue;\n if ((double) x > p->bounds.x2)\n {\n winding_number+=p->direction ? 1 : -1;\n continue;\n }\n i=(ssize_t) MagickMax((double) p->highwater,1.0);\n for ( ; i < (ssize_t) p->number_points; i++)\n if ((double) y <= p->points[i].y)\n break;\n q=p->points+i-1;\n if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))\n winding_number+=p->direction ? 1 : -1;\n }\n if (fill_rule != NonZeroRule)\n {\n if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)\n return(1.0);\n }\n else\n if (MagickAbsoluteValue(winding_number) != 0)\n return(1.0);\n return(subpath_alpha);\n}", "static MagickBooleanType DrawPolygonPrimitive(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " MagickBooleanType\n fill,\n status;", " double\n mid;", " PolygonInfo\n **magick_restrict polygon_info;", " register EdgeInfo\n *p;", " register ssize_t\n i;", " SegmentInfo\n bounds;", " ssize_t\n start_y,\n stop_y,\n y;", " /*\n Compute bounding box.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(draw_info != (DrawInfo *) NULL);\n assert(draw_info->signature == MagickCoreSignature);\n assert(primitive_info != (PrimitiveInfo *) NULL);\n if (primitive_info->coordinates == 0)\n return(MagickTrue);\n polygon_info=AcquirePolygonThreadSet(primitive_info);\n if (polygon_info == (PolygonInfo **) NULL)\n return(MagickFalse);\nDisableMSCWarning(4127)\n if (0)\n DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);\nRestoreMSCWarning\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" begin draw-polygon\");\n fill=(primitive_info->method == FillToBorderMethod) ||\n (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n bounds=polygon_info[0]->edges[0].bounds;\n for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)\n {\n p=polygon_info[0]->edges+i;\n if (p->bounds.x1 < bounds.x1)\n bounds.x1=p->bounds.x1;\n if (p->bounds.y1 < bounds.y1)\n bounds.y1=p->bounds.y1;\n if (p->bounds.x2 > bounds.x2)\n bounds.x2=p->bounds.x2;\n if (p->bounds.y2 > bounds.y2)\n bounds.y2=p->bounds.y2;\n }\n bounds.x1-=(mid+1.0);\n bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=\n image->columns ? (double) image->columns-1 : bounds.x1;\n bounds.y1-=(mid+1.0);\n bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=\n image->rows ? (double) image->rows-1 : bounds.y1;\n bounds.x2+=(mid+1.0);\n bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=\n image->columns ? (double) image->columns-1 : bounds.x2;\n bounds.y2+=(mid+1.0);\n bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=\n image->rows ? (double) image->rows-1 : bounds.y2;\n status=MagickTrue;\n image_view=AcquireAuthenticCacheView(image,exception);\n if ((primitive_info->coordinates == 1) ||\n (polygon_info[0]->number_edges == 0))\n {\n /*\n Draw point.\n */\n start_y=(ssize_t) ceil(bounds.y1-0.5);\n stop_y=(ssize_t) floor(bounds.y2+0.5);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=start_y; y <= stop_y; y++)\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " register ssize_t\n x;", " register Quantum\n *magick_restrict q;", " ssize_t\n start_x,\n stop_x;", " if (status == MagickFalse)\n continue;\n start_x=(ssize_t) ceil(bounds.x1-0.5);\n stop_x=(ssize_t) floor(bounds.x2+0.5);\n x=start_x;\n q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n GetPixelInfo(image,&pixel);\n for ( ; x <= stop_x; x++)\n {\n if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&\n (y == (ssize_t) ceil(primitive_info->point.y-0.5)))\n {\n GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n }\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n polygon_info=DestroyPolygonThreadSet(polygon_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" end draw-polygon\");\n return(status);\n }\n /*\n Draw polygon or line.\n */\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n start_y=(ssize_t) ceil(bounds.y1-0.5);\n stop_y=(ssize_t) floor(bounds.y2+0.5);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,1,1)\n#endif\n for (y=start_y; y <= stop_y; y++)\n {\n const int\n id = GetOpenMPThreadId();", " double\n fill_alpha,\n stroke_alpha;", " PixelInfo\n fill_color,\n stroke_color;", " register Quantum\n *magick_restrict q;", " register ssize_t\n x;", " ssize_t\n start_x,\n stop_x;", " if (status == MagickFalse)\n continue;\n start_x=(ssize_t) ceil(bounds.x1-0.5);\n stop_x=(ssize_t) floor(bounds.x2+0.5);\n q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+1),1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=start_x; x <= stop_x; x++)\n {\n /*\n Fill and/or stroke.\n */\n fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,\n x,y,&stroke_alpha);\n if (draw_info->stroke_antialias == MagickFalse)\n {\n fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;\n stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;\n }\n GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);\n fill_alpha=fill_alpha*fill_color.alpha;\n CompositePixelOver(image,&fill_color,fill_alpha,q,(double)\n GetPixelAlpha(image,q),q);\n GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);\n stroke_alpha=stroke_alpha*stroke_color.alpha;\n CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n }\n image_view=DestroyCacheView(image_view);\n polygon_info=DestroyPolygonThreadSet(polygon_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-polygon\");\n return(status);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% D r a w P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.\n%\n% The format of the DrawPrimitive method is:\n%\n% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,\n% PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)\n{\n const char\n *methods[] =\n {\n \"point\",\n \"replace\",\n \"floodfill\",\n \"filltoborder\",\n \"reset\",\n \"?\"\n };", " PointInfo\n p,\n q,\n point;", " register ssize_t\n i,\n x;", " ssize_t\n coordinates,\n y;", " x=(ssize_t) ceil(primitive_info->point.x-0.5);\n y=(ssize_t) ceil(primitive_info->point.y-0.5);\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"AlphaPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case ColorPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"ColorPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case ImagePrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"ImagePrimitive %.20g,%.20g\",(double) x,(double) y);\n return;\n }\n case PointPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"PointPrimitive %.20g,%.20g %s\",(double) x,(double) y,\n methods[primitive_info->method]);\n return;\n }\n case TextPrimitive:\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \"TextPrimitive %.20g,%.20g\",(double) x,(double) y);\n return;\n }\n default:\n break;\n }\n coordinates=0;\n p=primitive_info[0].point;\n q.x=(-1.0);\n q.y=(-1.0);\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)\n {\n point=primitive_info[i].point;\n if (coordinates <= 0)\n {\n coordinates=(ssize_t) primitive_info[i].coordinates;\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin open (%.20g)\",(double) coordinates);\n p=point;\n }\n point=primitive_info[i].point;\n if ((fabs(q.x-point.x) >= MagickEpsilon) ||\n (fabs(q.y-point.y) >= MagickEpsilon))\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %.20g: %.18g,%.18g\",(double) coordinates,point.x,point.y);\n else\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" %.20g: %g %g (duplicate)\",(double) coordinates,point.x,point.y);\n q=point;\n coordinates--;\n if (coordinates > 0)\n continue;\n if ((fabs(p.x-point.x) >= MagickEpsilon) ||\n (fabs(p.y-point.y) >= MagickEpsilon))\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end last (%.20g)\",\n (double) coordinates);\n else\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end open (%.20g)\",\n (double) coordinates);\n }\n}", "MagickExport MagickBooleanType DrawPrimitive(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n CacheView\n *image_view;", " MagickStatusType\n status;", " register ssize_t\n i,\n x;", " ssize_t\n y;", " if (image->debug != MagickFalse)\n {\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin draw-primitive\");\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" affine: %g %g %g %g %g %g\",draw_info->affine.sx,\n draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,\n draw_info->affine.tx,draw_info->affine.ty);\n }\n if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&\n ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||\n (IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))\n (void) SetImageColorspace(image,sRGBColorspace,exception);\n status=MagickTrue;\n x=(ssize_t) ceil(primitive_info->point.x-0.5);\n y=(ssize_t) ceil(primitive_info->point.y-0.5);\n image_view=AcquireAuthenticCacheView(image,exception);\n switch (primitive_info->primitive)\n {\n case AlphaPrimitive:\n {\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;", " register Quantum\n *q;", " q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel,\n target;", " (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n ChannelType\n channel_mask;", " PixelInfo\n target;", " (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n channel_mask=SetImageChannelMask(image,AlphaChannel);\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n (void) SetImageChannelMask(image,channel_mask);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ColorPrimitive:\n {\n switch (primitive_info->method)\n {\n case PointMethod:\n default:\n {\n PixelInfo\n pixel;", " register Quantum\n *q;", " q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetPixelInfo(image,&pixel);\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case ReplaceMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel,\n target;", " (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,\n exception);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,q,&pixel);\n if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n case FloodfillMethod:\n case FillToBorderMethod:\n {\n PixelInfo\n target;", " (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,\n &target,exception);\n if (primitive_info->method == FillToBorderMethod)\n {\n target.red=(double) draw_info->border_color.red;\n target.green=(double) draw_info->border_color.green;\n target.blue=(double) draw_info->border_color.blue;\n }\n status&=FloodfillPaintImage(image,draw_info,&target,x,y,\n primitive_info->method == FloodfillMethod ? MagickFalse :\n MagickTrue,exception);\n break;\n }\n case ResetMethod:\n {\n MagickBooleanType\n sync;", " PixelInfo\n pixel;", " GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;", " q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetFillColor(draw_info,x,y,&pixel,exception);\n SetPixelViaPixelInfo(image,&pixel,q);\n q+=GetPixelChannels(image);\n }\n sync=SyncCacheViewAuthenticPixels(image_view,exception);\n if (sync == MagickFalse)\n break;\n }\n break;\n }\n }\n break;\n }\n case ImagePrimitive:\n {\n AffineMatrix\n affine;", " char\n composite_geometry[MagickPathExtent];", " Image\n *composite_image;", " ImageInfo\n *clone_info;", " RectangleInfo\n geometry;", " ssize_t\n x1,\n y1;", " if (primitive_info->text == (char *) NULL)\n break;\n clone_info=AcquireImageInfo();\n if (LocaleNCompare(primitive_info->text,\"data:\",5) == 0)\n composite_image=ReadInlineImage(clone_info,primitive_info->text,\n exception);\n else\n {\n (void) CopyMagickString(clone_info->filename,primitive_info->text,\n MagickPathExtent);\n composite_image=ReadImage(clone_info,exception);\n }\n clone_info=DestroyImageInfo(clone_info);\n if (composite_image == (Image *) NULL)\n break;\n (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)\n NULL,(void *) NULL);\n x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);\n y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);\n if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||\n ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))\n {\n /*\n Resize image.\n */\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%gx%g!\",primitive_info[1].point.x,primitive_info[1].point.y);\n composite_image->filter=image->filter;\n (void) TransformImage(&composite_image,(char *) NULL,\n composite_geometry,exception);\n }\n if (composite_image->alpha_trait == UndefinedPixelTrait)\n (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,\n exception);\n if (draw_info->alpha != OpaqueAlpha)\n (void) SetImageAlpha(composite_image,draw_info->alpha,exception);\n SetGeometry(image,&geometry);\n image->gravity=draw_info->gravity;\n geometry.x=x;\n geometry.y=y;\n (void) FormatLocaleString(composite_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) composite_image->columns,(double)\n composite_image->rows,(double) geometry.x,(double) geometry.y);\n (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);\n affine=draw_info->affine;\n affine.tx=(double) geometry.x;\n affine.ty=(double) geometry.y;\n composite_image->interpolate=image->interpolate;\n if (draw_info->compose == OverCompositeOp)\n (void) DrawAffineImage(image,composite_image,&affine,exception);\n else\n (void) CompositeImage(image,composite_image,draw_info->compose,\n MagickTrue,geometry.x,geometry.y,exception);\n composite_image=DestroyImage(composite_image);\n break;\n }\n case PointPrimitive:\n {\n PixelInfo\n fill_color;", " register Quantum\n *q;", " if ((y < 0) || (y >= (ssize_t) image->rows))\n break;\n if ((x < 0) || (x >= (ssize_t) image->columns))\n break;\n q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);\n if (q == (Quantum *) NULL)\n break;\n GetFillColor(draw_info,x,y,&fill_color,exception);\n CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,\n (double) GetPixelAlpha(image,q),q);\n (void) SyncCacheViewAuthenticPixels(image_view,exception);\n break;\n }\n case TextPrimitive:\n {\n char\n geometry[MagickPathExtent];", " DrawInfo\n *clone_info;", " if (primitive_info->text == (char *) NULL)\n break;\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n (void) CloneString(&clone_info->text,primitive_info->text);\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%+f%+f\",\n primitive_info->point.x,primitive_info->point.y);\n (void) CloneString(&clone_info->geometry,geometry);\n status&=AnnotateImage(image,clone_info,exception);\n clone_info=DestroyDrawInfo(clone_info);\n break;\n }\n default:\n {\n double\n mid,\n scale;", " DrawInfo\n *clone_info;", " if (IsEventLogging() != MagickFalse)\n LogPrimitiveInfo(primitive_info);\n scale=ExpandAffine(&draw_info->affine);\n if ((draw_info->dash_pattern != (double *) NULL) &&\n (draw_info->dash_pattern[0] != 0.0) &&\n ((scale*draw_info->stroke_width) >= MagickEpsilon) &&\n (draw_info->stroke.alpha != (Quantum) TransparentAlpha))\n {\n /*\n Draw dash polygon.\n */\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;", " clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;", " status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n (void) DrawDashPolygon(draw_info,primitive_info,image,exception);\n break;\n }\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n if ((mid > 1.0) &&\n ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||\n (draw_info->stroke_pattern != (Image *) NULL)))\n {\n MagickBooleanType\n closed_path;", " /*\n Draw strokes while respecting line cap/join attributes.\n */\n for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;\n closed_path=\n (primitive_info[i-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[i-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n i=(ssize_t) primitive_info[0].coordinates;\n if ((((draw_info->linecap == RoundCap) ||\n (closed_path != MagickFalse)) &&\n (draw_info->linejoin == RoundJoin)) ||\n (primitive_info[i].primitive != UndefinedPrimitive))\n {\n (void) DrawPolygonPrimitive(image,draw_info,primitive_info,\n exception);\n break;\n }\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->stroke_width=0.0;", " clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;", " status&=DrawPolygonPrimitive(image,clone_info,primitive_info,\n exception);\n clone_info=DestroyDrawInfo(clone_info);\n status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);\n break;\n }\n status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);\n break;\n }\n }\n image_view=DestroyCacheView(image_view);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\" end draw-primitive\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ D r a w S t r o k e P o l y g o n %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on\n% the image while respecting the line cap and join attributes.\n%\n% The format of the DrawStrokePolygon method is:\n%\n% MagickBooleanType DrawStrokePolygon(Image *image,\n% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)\n%\n% A description of each parameter follows:\n%\n% o image: the image.\n%\n% o draw_info: the draw info.\n%\n% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.\n%\n%\n*/", "static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n{\n PrimitiveInfo\n linecap[5];", " register ssize_t\n i;", " for (i=0; i < 4; i++)\n linecap[i]=(*primitive_info);\n linecap[0].coordinates=4;\n linecap[1].point.x+=(double) (10.0*MagickEpsilon);\n linecap[2].point.x+=(double) (10.0*MagickEpsilon);\n linecap[2].point.y+=(double) (10.0*MagickEpsilon);\n linecap[3].point.y+=(double) (10.0*MagickEpsilon);\n linecap[4].primitive=UndefinedPrimitive;\n (void) DrawPolygonPrimitive(image,draw_info,linecap,exception);\n}", "static MagickBooleanType DrawStrokePolygon(Image *image,\n const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,\n ExceptionInfo *exception)\n{\n DrawInfo\n *clone_info;", " MagickBooleanType\n closed_path;", " MagickStatusType\n status;", " PrimitiveInfo\n *stroke_polygon;", " register const PrimitiveInfo\n *p,\n *q;", " /*\n Draw stroked polygon.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" begin draw-stroke-polygon\");\n clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);\n clone_info->fill=draw_info->stroke;\n if (clone_info->fill_pattern != (Image *) NULL)\n clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);\n if (clone_info->stroke_pattern != (Image *) NULL)\n clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,\n MagickTrue,exception);", " clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;", " clone_info->stroke_width=0.0;\n clone_info->fill_rule=NonZeroRule;\n status=MagickTrue;\n for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)\n {\n stroke_polygon=TraceStrokePolygon(draw_info,p);\n status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);\n if (status == 0)\n break;\n stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);\n q=p+p->coordinates-1;\n closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?\n MagickTrue : MagickFalse;\n if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))\n {\n DrawRoundLinecap(image,draw_info,p,exception);\n DrawRoundLinecap(image,draw_info,q,exception);\n }\n }\n clone_info=DestroyDrawInfo(clone_info);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(DrawEvent,GetMagickModule(),\n \" end draw-stroke-polygon\");\n return(status != 0 ? MagickTrue : MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% G e t A f f i n e M a t r i x %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GetAffineMatrix() returns an AffineMatrix initialized to the identity\n% matrix.\n%\n% The format of the GetAffineMatrix method is:\n%\n% void GetAffineMatrix(AffineMatrix *affine_matrix)\n%\n% A description of each parameter follows:\n%\n% o affine_matrix: the affine matrix.\n%\n*/\nMagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)\n{\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(affine_matrix != (AffineMatrix *) NULL);\n (void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));\n affine_matrix->sx=1.0;\n affine_matrix->sy=1.0;\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ G e t D r a w I n f o %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GetDrawInfo() initializes draw_info to default values from image_info.\n%\n% The format of the GetDrawInfo method is:\n%\n% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info..\n%\n% o draw_info: the draw info.\n%\n*/\nMagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)\n{\n const char\n *option;", " ExceptionInfo\n *exception;", " ImageInfo\n *clone_info;", " /*\n Initialize draw attributes.\n */\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(draw_info != (DrawInfo *) NULL);\n (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));\n clone_info=CloneImageInfo(image_info);\n GetAffineMatrix(&draw_info->affine);\n exception=AcquireExceptionInfo();\n (void) QueryColorCompliance(\"#000F\",AllCompliance,&draw_info->fill,\n exception);\n (void) QueryColorCompliance(\"#0000\",AllCompliance,&draw_info->stroke,\n exception);\n draw_info->stroke_width=1.0;\n draw_info->alpha=OpaqueAlpha;\n draw_info->fill_rule=EvenOddRule;\n draw_info->linecap=ButtCap;\n draw_info->linejoin=MiterJoin;\n draw_info->miterlimit=10;\n draw_info->decorate=NoDecoration;\n draw_info->pointsize=12.0;", " draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha;", " draw_info->compose=OverCompositeOp;\n draw_info->render=MagickTrue;\n draw_info->debug=IsEventLogging();\n draw_info->stroke_antialias=clone_info->antialias;\n if (clone_info->font != (char *) NULL)\n draw_info->font=AcquireString(clone_info->font);\n if (clone_info->density != (char *) NULL)\n draw_info->density=AcquireString(clone_info->density);\n draw_info->text_antialias=clone_info->antialias;\n if (clone_info->pointsize != 0.0)\n draw_info->pointsize=clone_info->pointsize;\n draw_info->border_color=clone_info->border_color;\n if (clone_info->server_name != (char *) NULL)\n draw_info->server_name=AcquireString(clone_info->server_name);\n option=GetImageOption(clone_info,\"direction\");\n if (option != (const char *) NULL)\n draw_info->direction=(DirectionType) ParseCommandOption(\n MagickDirectionOptions,MagickFalse,option);\n else\n draw_info->direction=UndefinedDirection;\n option=GetImageOption(clone_info,\"encoding\");\n if (option != (const char *) NULL)\n (void) CloneString(&draw_info->encoding,option);\n option=GetImageOption(clone_info,\"family\");\n if (option != (const char *) NULL)\n (void) CloneString(&draw_info->family,option);\n option=GetImageOption(clone_info,\"fill\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,\n exception);\n option=GetImageOption(clone_info,\"gravity\");\n if (option != (const char *) NULL)\n draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,\n MagickFalse,option);\n option=GetImageOption(clone_info,\"interline-spacing\");\n if (option != (const char *) NULL)\n draw_info->interline_spacing=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"interword-spacing\");\n if (option != (const char *) NULL)\n draw_info->interword_spacing=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"kerning\");\n if (option != (const char *) NULL)\n draw_info->kerning=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"stroke\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,\n exception);\n option=GetImageOption(clone_info,\"strokewidth\");\n if (option != (const char *) NULL)\n draw_info->stroke_width=StringToDouble(option,(char **) NULL);\n option=GetImageOption(clone_info,\"style\");\n if (option != (const char *) NULL)\n draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,\n MagickFalse,option);\n option=GetImageOption(clone_info,\"undercolor\");\n if (option != (const char *) NULL)\n (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,\n exception);\n option=GetImageOption(clone_info,\"weight\");\n if (option != (const char *) NULL)\n {\n ssize_t\n weight;", " weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);\n if (weight == -1)", " weight=(ssize_t) StringToUnsignedLong(option);", " draw_info->weight=(size_t) weight;\n }\n exception=DestroyExceptionInfo(exception);\n draw_info->signature=MagickCoreSignature;\n clone_info=DestroyImageInfo(clone_info);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ P e r m u t a t e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Permutate() returns the permuation of the (n,k).\n%\n% The format of the Permutate method is:\n%\n% void Permutate(ssize_t n,ssize_t k)\n%\n% A description of each parameter follows:\n%\n% o n:\n%\n% o k:\n%\n%\n*/\nstatic inline double Permutate(const ssize_t n,const ssize_t k)\n{\n double\n r;", " register ssize_t\n i;", " r=1.0;\n for (i=k+1; i <= n; i++)\n r*=i;\n for (i=1; i <= (n-k); i++)\n r/=i;\n return(r);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n+ T r a c e P r i m i t i v e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% TracePrimitive is a collection of methods for generating graphic\n% primitives such as arcs, ellipses, paths, etc.\n%\n*/", "static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end,const PointInfo degrees)\n{\n PointInfo\n center,\n radii;", " center.x=0.5*(end.x+start.x);\n center.y=0.5*(end.y+start.y);\n radii.x=fabs(center.x-start.x);\n radii.y=fabs(center.y-start.y);\n TraceEllipse(primitive_info,center,radii,degrees);\n}", "static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end,const PointInfo arc,const double angle,\n const MagickBooleanType large_arc,const MagickBooleanType sweep)\n{\n double\n alpha,\n beta,\n delta,\n factor,\n gamma,\n theta;", " PointInfo\n center,\n points[3],\n radii;", " register double\n cosine,\n sine;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " size_t\n arc_segments;", " if ((start.x == end.x) && (start.y == end.y))\n {\n TracePoint(primitive_info,end);\n return;\n }\n radii.x=fabs(arc.x);\n radii.y=fabs(arc.y);\n if ((radii.x == 0.0) || (radii.y == 0.0))\n {\n TraceLine(primitive_info,start,end);\n return;\n }\n cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));\n sine=sin(DegreesToRadians(fmod((double) angle,360.0)));\n center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);\n center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);\n delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/\n (radii.y*radii.y);\n if (delta < MagickEpsilon)\n {\n TraceLine(primitive_info,start,end);\n return;\n }\n if (delta > 1.0)\n {\n radii.x*=sqrt((double) delta);\n radii.y*=sqrt((double) delta);\n }\n points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);\n points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);\n points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);\n points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);\n alpha=points[1].x-points[0].x;\n beta=points[1].y-points[0].y;\n factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;\n if (factor <= 0.0)\n factor=0.0;\n else\n {\n factor=sqrt((double) factor);\n if (sweep == large_arc)\n factor=(-factor);\n }\n center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);\n center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);\n alpha=atan2(points[0].y-center.y,points[0].x-center.x);\n theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;\n if ((theta < 0.0) && (sweep != MagickFalse))\n theta+=(double) (2.0*MagickPI);\n else\n if ((theta > 0.0) && (sweep == MagickFalse))\n theta-=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+\n MagickEpsilon))));\n p=primitive_info;\n for (i=0; i < (ssize_t) arc_segments; i++)\n {\n beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));\n gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*\n sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/\n sin(fmod((double) beta,DegreesToRadians(360.0)));\n points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/\n arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+\n (double) i*theta/arc_segments),DegreesToRadians(360.0))));\n points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/\n arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+\n (double) i*theta/arc_segments),DegreesToRadians(360.0))));\n points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*\n theta/arc_segments),DegreesToRadians(360.0))));\n points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*\n theta/arc_segments),DegreesToRadians(360.0))));\n points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)\n (i+1)*theta/arc_segments),DegreesToRadians(360.0))));\n points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)\n (i+1)*theta/arc_segments),DegreesToRadians(360.0))));\n p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;\n p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;\n (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*\n points[0].y);\n (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*\n points[0].y);\n (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*\n points[1].y);\n (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*\n points[1].y);\n (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*\n points[2].y);\n (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*\n points[2].y);\n if (i == (ssize_t) (arc_segments-1))\n (p+3)->point=end;\n TraceBezier(p,4);\n p+=p->coordinates;\n }\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceBezier(PrimitiveInfo *primitive_info,\n const size_t number_coordinates)\n{\n double\n alpha,\n *coefficients,\n weight;", " PointInfo\n end,\n point,\n *points;", " register PrimitiveInfo\n *p;", " register ssize_t\n i,\n j;", " size_t\n control_points,\n quantum;", " /*\n Allocate coeficients.\n */\n quantum=number_coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n for (j=i+1; j < (ssize_t) number_coordinates; j++)\n {\n alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n }\n }\n quantum=(size_t) MagickMin((double) quantum/number_coordinates,\n (double) BezierQuantum);\n control_points=quantum*number_coordinates;\n coefficients=(double *) AcquireQuantumMemory((size_t)\n number_coordinates,sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,\n sizeof(*points));\n if ((coefficients == (double *) NULL) ||\n (points == (PointInfo *) NULL))\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n /*\n Compute bezier points.\n */\n end=primitive_info[number_coordinates-1].point;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);\n weight=0.0;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n p=primitive_info;\n point.x=0.0;\n point.y=0.0;\n alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);\n for (j=0; j < (ssize_t) number_coordinates; j++)\n {\n point.x+=alpha*coefficients[j]*p->point.x;\n point.y+=alpha*coefficients[j]*p->point.y;\n alpha*=weight/(1.0-weight);\n p++;\n }\n points[i]=point;\n weight+=1.0/control_points;\n }\n /*\n Bezier curves are just short segmented polys.\n */\n p=primitive_info;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n TracePoint(p,points[i]);\n p+=p->coordinates;\n }\n TracePoint(p,end);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n}", "static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n double\n alpha,\n beta,\n radius;", " PointInfo\n offset,\n degrees;", " alpha=end.x-start.x;\n beta=end.y-start.y;\n radius=hypot((double) alpha,(double) beta);\n offset.x=(double) radius;\n offset.y=(double) radius;\n degrees.x=0.0;\n degrees.y=360.0;\n TraceEllipse(primitive_info,start,offset,degrees);\n}", "static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo stop,const PointInfo degrees)\n{\n double\n delta,\n step,\n y;", " PointInfo\n angle,\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " /*\n Ellipses are just short segmented polys.\n */\n if ((stop.x == 0.0) && (stop.y == 0.0))\n {\n TracePoint(primitive_info,start);\n return;\n }\n delta=2.0/MagickMax(stop.x,stop.y);\n step=(double) (MagickPI/8.0);\n if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0)))\n step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5)));\n angle.x=DegreesToRadians(degrees.x);\n y=degrees.y;\n while (y < degrees.x)\n y+=360.0;\n angle.y=(double) DegreesToRadians(y);\n for (p=primitive_info; angle.x < angle.y; angle.x+=step)\n {\n point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;\n point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n }\n point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;\n point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n TracePoint(primitive_info,start);\n if ((fabs(start.x-end.x) < MagickEpsilon) &&\n (fabs(start.y-end.y) < MagickEpsilon))\n {\n primitive_info->primitive=PointPrimitive;\n primitive_info->coordinates=1;\n return;\n }\n TracePoint(primitive_info+1,end);\n (primitive_info+1)->primitive=primitive_info->primitive;\n primitive_info->coordinates=2;\n}", "static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)\n{\n char\n token[MagickPathExtent];", " const char\n *p;", " int\n attribute,\n last_attribute;", " double\n x,\n y;", " PointInfo\n end = {0.0, 0.0},\n points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },\n point = {0.0, 0.0},\n start = {0.0, 0.0};", " PrimitiveType\n primitive_type;", " register PrimitiveInfo\n *q;", " register ssize_t\n i;", " size_t\n number_coordinates,\n z_count;", " attribute=0;\n number_coordinates=0;\n z_count=0;\n primitive_type=primitive_info->primitive;\n q=primitive_info;\n for (p=path; *p != '\\0'; )\n {\n while (isspace((int) ((unsigned char) *p)) != 0)\n p++;\n if (*p == '\\0')\n break;\n last_attribute=attribute;\n attribute=(int) (*p++);\n switch (attribute)\n {\n case 'a':\n case 'A':\n {\n MagickBooleanType\n large_arc,\n sweep;", " double\n angle;", " PointInfo\n arc;", " /*\n Compute arc points.\n */\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n arc.x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n arc.y=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n angle=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'A' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'A' ? y : point.y+y);\n TraceArcPath(q,point,end,arc,angle,large_arc,sweep);\n q+=q->coordinates;\n point=end;\n while (isspace((int) ((unsigned char) *p)) != 0)\n p++;\n if (*p == ',')\n p++;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'c':\n case 'C':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=point;\n for (i=1; i < 4; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'C' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'C' ? y : point.y+y);\n points[i]=end;\n }\n for (i=0; i < 4; i++)\n (q+i)->point=points[i];\n TraceBezier(q,4);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'H':\n case 'h':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'H' ? x: point.x+x);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'l':\n case 'L':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'L' ? x : point.x+x);\n point.y=(double) (attribute == (int) 'L' ? y : point.y+y);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'M':\n case 'm':\n {\n if (q != primitive_info)\n {\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n primitive_info=q;\n }\n i=0;\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.x=(double) (attribute == (int) 'M' ? x : point.x+x);\n point.y=(double) (attribute == (int) 'M' ? y : point.y+y);\n if (i == 0)\n start=point;\n i++;\n TracePoint(q,point);\n q+=q->coordinates;\n if ((i != 0) && (attribute == (int) 'M'))\n {\n TracePoint(q,point);\n q+=q->coordinates;\n }\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'q':\n case 'Q':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=point;\n for (i=1; i < 3; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n if (*p == ',')\n p++;\n end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);\n points[i]=end;\n }\n for (i=0; i < 3; i++)\n (q+i)->point=points[i];\n TraceBezier(q,3);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 's':\n case 'S':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=points[3];\n points[1].x=2.0*points[3].x-points[2].x;\n points[1].y=2.0*points[3].y-points[2].y;\n for (i=2; i < 4; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n if (*p == ',')\n p++;\n end.x=(double) (attribute == (int) 'S' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'S' ? y : point.y+y);\n points[i]=end;\n }\n if (strchr(\"CcSs\",last_attribute) == (char *) NULL)\n {\n points[0]=point;\n points[1]=point;\n }\n for (i=0; i < 4; i++)\n (q+i)->point=points[i];\n TraceBezier(q,4);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 't':\n case 'T':\n {\n /*\n Compute bezier points.\n */\n do\n {\n points[0]=points[2];\n points[1].x=2.0*points[2].x-points[1].x;\n points[1].y=2.0*points[2].y-points[1].y;\n for (i=2; i < 3; i++)\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n x=StringToDouble(token,(char **) NULL);\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n end.x=(double) (attribute == (int) 'T' ? x : point.x+x);\n end.y=(double) (attribute == (int) 'T' ? y : point.y+y);\n points[i]=end;\n }\n if (strchr(\"QqTt\",last_attribute) == (char *) NULL)\n {\n points[0]=point;\n points[1]=point;\n }\n for (i=0; i < 3; i++)\n (q+i)->point=points[i];\n TraceBezier(q,3);\n q+=q->coordinates;\n point=end;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'v':\n case 'V':\n {\n do\n {\n GetNextToken(p,&p,MagickPathExtent,token);\n if (*token == ',')\n GetNextToken(p,&p,MagickPathExtent,token);\n y=StringToDouble(token,(char **) NULL);\n point.y=(double) (attribute == (int) 'V' ? y : point.y+y);\n TracePoint(q,point);\n q+=q->coordinates;\n } while (IsPoint(p) != MagickFalse);\n break;\n }\n case 'z':\n case 'Z':\n {\n point=start;\n TracePoint(q,point);\n q+=q->coordinates;\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n primitive_info=q;\n z_count++;\n break;\n }\n default:\n {\n if (isalpha((int) ((unsigned char) attribute)) != 0)\n (void) FormatLocaleFile(stderr,\"attribute not recognized: %c\\n\",\n attribute);\n break;\n }\n }\n }\n primitive_info->coordinates=(size_t) (q-primitive_info);\n number_coordinates+=primitive_info->coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n q--;\n q->primitive=primitive_type;\n if (z_count > 1)\n q->method=FillToBorderMethod;\n }\n q=primitive_info;\n return(number_coordinates);\n}", "static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,\n const PointInfo end)\n{\n PointInfo\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " p=primitive_info;\n TracePoint(p,start);\n p+=p->coordinates;\n point.x=start.x;\n point.y=end.y;\n TracePoint(p,point);\n p+=p->coordinates;\n TracePoint(p,end);\n p+=p->coordinates;\n point.x=end.x;\n point.y=start.y;\n TracePoint(p,point);\n p+=p->coordinates;\n TracePoint(p,start);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceRoundRectangle(PrimitiveInfo *primitive_info,\n const PointInfo start,const PointInfo end,PointInfo arc)\n{\n PointInfo\n degrees,\n offset,\n point;", " register PrimitiveInfo\n *p;", " register ssize_t\n i;", " p=primitive_info;\n offset.x=fabs(end.x-start.x);\n offset.y=fabs(end.y-start.y);\n if (arc.x > (0.5*offset.x))\n arc.x=0.5*offset.x;\n if (arc.y > (0.5*offset.y))\n arc.y=0.5*offset.y;\n point.x=start.x+offset.x-arc.x;\n point.y=start.y+arc.y;\n degrees.x=270.0;\n degrees.y=360.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+offset.x-arc.x;\n point.y=start.y+offset.y-arc.y;\n degrees.x=0.0;\n degrees.y=90.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+arc.x;\n point.y=start.y+offset.y-arc.y;\n degrees.x=90.0;\n degrees.y=180.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n point.x=start.x+arc.x;\n point.y=start.y+arc.y;\n degrees.x=180.0;\n degrees.y=270.0;\n TraceEllipse(p,point,arc,degrees);\n p+=p->coordinates;\n TracePoint(p,primitive_info->point);\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n}", "static void TraceSquareLinecap(PrimitiveInfo *primitive_info,\n const size_t number_vertices,const double offset)\n{\n double\n distance;", " register double\n dx,\n dy;", " register ssize_t\n i;", " ssize_t\n j;", " dx=0.0;\n dy=0.0;\n for (i=1; i < (ssize_t) number_vertices; i++)\n {\n dx=primitive_info[0].point.x-primitive_info[i].point.x;\n dy=primitive_info[0].point.y-primitive_info[i].point.y;\n if ((fabs((double) dx) >= MagickEpsilon) ||\n (fabs((double) dy) >= MagickEpsilon))\n break;\n }\n if (i == (ssize_t) number_vertices)\n i=(ssize_t) number_vertices-1L;\n distance=hypot((double) dx,(double) dy);\n primitive_info[0].point.x=(double) (primitive_info[i].point.x+\n dx*(distance+offset)/distance);\n primitive_info[0].point.y=(double) (primitive_info[i].point.y+\n dy*(distance+offset)/distance);\n for (j=(ssize_t) number_vertices-2; j >= 0; j--)\n {\n dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;\n dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;\n if ((fabs((double) dx) >= MagickEpsilon) ||\n (fabs((double) dy) >= MagickEpsilon))\n break;\n }\n distance=hypot((double) dx,(double) dy);\n primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+\n dx*(distance+offset)/distance);\n primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+\n dy*(distance+offset)/distance);\n}", "static inline double DrawEpsilonReciprocal(const double x)\n{\n#define DrawEpsilon (1.0e-6)", " double sign = x < 0.0 ? -1.0 : 1.0;\n return((sign*x) >= DrawEpsilon ? 1.0/x : sign*(1.0/DrawEpsilon));\n}", "static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info)\n{\n typedef struct _LineSegment\n {\n double\n p,\n q;\n } LineSegment;", " LineSegment\n dx,\n dy,\n inverse_slope,\n slope,\n theta;", " MagickBooleanType\n closed_path;", " double\n delta_theta,\n dot_product,\n mid,\n miterlimit;", " PointInfo\n box_p[5],\n box_q[5],\n center,\n offset,\n *path_p,\n *path_q;", " PrimitiveInfo\n *polygon_primitive,\n *stroke_polygon;", " register ssize_t\n i;", " size_t\n arc_segments,\n max_strokes,\n number_vertices;", " ssize_t\n j,\n n,\n p,\n q;", " /*\n Allocate paths.\n */\n number_vertices=primitive_info->coordinates;\n max_strokes=2*number_vertices+6*BezierQuantum+360;\n path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,\n sizeof(*path_q));\n polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n number_vertices+2UL,sizeof(*polygon_primitive));\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||\n (polygon_primitive == (PrimitiveInfo *) NULL))\n return((PrimitiveInfo *) NULL);\n (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)\n number_vertices*sizeof(*polygon_primitive));\n closed_path=\n (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&\n (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?\n MagickTrue : MagickFalse;\n if ((draw_info->linejoin == RoundJoin) ||\n ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))\n {\n polygon_primitive[number_vertices]=primitive_info[1];\n number_vertices++;\n }\n polygon_primitive[number_vertices].primitive=UndefinedPrimitive;\n /*\n Compute the slope for the first line segment, p.\n */\n dx.p=0.0;\n dy.p=0.0;\n for (n=1; n < (ssize_t) number_vertices; n++)\n {\n dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;\n dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;\n if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))\n break;\n }\n if (n == (ssize_t) number_vertices)\n n=(ssize_t) number_vertices-1L;\n slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;\n inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*\n mid*mid);\n if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))\n TraceSquareLinecap(polygon_primitive,number_vertices,mid);\n offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));\n offset.y=(double) (offset.x*inverse_slope.p);\n if ((dy.p*offset.x-dx.p*offset.y) > 0.0)\n {\n box_p[0].x=polygon_primitive[0].point.x-offset.x;\n box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;\n box_p[1].x=polygon_primitive[n].point.x-offset.x;\n box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;\n box_q[0].x=polygon_primitive[0].point.x+offset.x;\n box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;\n box_q[1].x=polygon_primitive[n].point.x+offset.x;\n box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;\n }\n else\n {\n box_p[0].x=polygon_primitive[0].point.x+offset.x;\n box_p[0].y=polygon_primitive[0].point.y+offset.y;\n box_p[1].x=polygon_primitive[n].point.x+offset.x;\n box_p[1].y=polygon_primitive[n].point.y+offset.y;\n box_q[0].x=polygon_primitive[0].point.x-offset.x;\n box_q[0].y=polygon_primitive[0].point.y-offset.y;\n box_q[1].x=polygon_primitive[n].point.x-offset.x;\n box_q[1].y=polygon_primitive[n].point.y-offset.y;\n }\n /*\n Create strokes for the line join attribute: bevel, miter, round.\n */\n p=0;\n q=0;\n path_q[p++]=box_q[0];\n path_p[q++]=box_p[0];\n for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)\n {\n /*\n Compute the slope for this line segment, q.\n */\n dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;\n dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;\n dot_product=dx.q*dx.q+dy.q*dy.q;\n if (dot_product < 0.25)\n continue;\n slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;\n inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));\n offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));\n offset.y=(double) (offset.x*inverse_slope.q);\n dot_product=dy.q*offset.x-dx.q*offset.y;\n if (dot_product > 0.0)\n {\n box_p[2].x=polygon_primitive[n].point.x-offset.x;\n box_p[2].y=polygon_primitive[n].point.y-offset.y;\n box_p[3].x=polygon_primitive[i].point.x-offset.x;\n box_p[3].y=polygon_primitive[i].point.y-offset.y;\n box_q[2].x=polygon_primitive[n].point.x+offset.x;\n box_q[2].y=polygon_primitive[n].point.y+offset.y;\n box_q[3].x=polygon_primitive[i].point.x+offset.x;\n box_q[3].y=polygon_primitive[i].point.y+offset.y;\n }\n else\n {\n box_p[2].x=polygon_primitive[n].point.x+offset.x;\n box_p[2].y=polygon_primitive[n].point.y+offset.y;\n box_p[3].x=polygon_primitive[i].point.x+offset.x;\n box_p[3].y=polygon_primitive[i].point.y+offset.y;\n box_q[2].x=polygon_primitive[n].point.x-offset.x;\n box_q[2].y=polygon_primitive[n].point.y-offset.y;\n box_q[3].x=polygon_primitive[i].point.x-offset.x;\n box_q[3].y=polygon_primitive[i].point.y-offset.y;\n }\n if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)\n {\n box_p[4]=box_p[1];\n box_q[4]=box_q[1];\n }\n else\n {\n box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+\n box_p[3].y)/(slope.p-slope.q));\n box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);\n box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+\n box_q[3].y)/(slope.p-slope.q));\n box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);\n }\n if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))\n {", " if (~max_strokes < (6*BezierQuantum+360))\n {\n path_p=(PointInfo *) RelinquishMagickMemory(path_p);\n path_q=(PointInfo *) RelinquishMagickMemory(path_q);\n }\n else\n {\n max_strokes+=6*BezierQuantum+360;\n path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes,\n sizeof(*path_p));\n path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes,\n sizeof(*path_q));\n }\n if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))\n {\n if (path_p != (PointInfo *) NULL)\n path_p=(PointInfo *) RelinquishMagickMemory(path_p);\n if (path_q != (PointInfo *) NULL)\n path_q=(PointInfo *) RelinquishMagickMemory(path_q);\n polygon_primitive=(PrimitiveInfo *)\n RelinquishMagickMemory(polygon_primitive);\n return((PrimitiveInfo *) NULL);\n }", " }\n dot_product=dx.q*dy.p-dx.p*dy.q;\n if (dot_product <= 0.0)\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_p[p++]=box_p[4];\n else\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);\n theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);\n if (theta.q < theta.p)\n theta.q+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_q[q].x=box_q[1].x;\n path_q[q].y=box_q[1].y;\n q++;\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_q[q].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_q[q].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n q++;\n }\n path_q[q++]=box_q[2];\n break;\n }\n default:\n break;\n }\n else\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n path_q[q++]=box_q[4];\n path_p[p++]=box_p[4];\n }\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n path_p[p++]=box_p[1];\n path_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n path_q[q++]=box_q[4];\n else\n {\n path_q[q++]=box_q[1];\n path_q[q++]=box_q[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);\n theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);\n if (theta.p < theta.q)\n theta.p+=(double) (2.0*MagickPI);\n arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/\n (2.0*sqrt((double) (1.0/mid)))));\n path_p[p++]=box_p[1];\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n path_p[p].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n path_p[p].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n p++;\n }\n path_p[p++]=box_p[2];\n break;\n }\n default:\n break;\n }\n slope.p=slope.q;\n inverse_slope.p=inverse_slope.q;\n box_p[0]=box_p[2];\n box_p[1]=box_p[3];\n box_q[0]=box_q[2];\n box_q[1]=box_q[3];\n dx.p=dx.q;\n dy.p=dy.q;\n n=i;\n }\n path_p[p++]=box_p[1];\n path_q[q++]=box_q[1];\n /*\n Trace stroked polygon.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));\n if (stroke_polygon != (PrimitiveInfo *) NULL)\n {\n for (i=0; i < (ssize_t) p; i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_p[i];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n }\n for ( ; i < (ssize_t) (p+q+closed_path); i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[p+closed_path].point;\n i++;\n }\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n stroke_polygon[i].primitive=UndefinedPrimitive;\n stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);\n }\n path_p=(PointInfo *) RelinquishMagickMemory(path_p);\n path_q=(PointInfo *) RelinquishMagickMemory(path_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);\n return(stroke_polygon);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [0, 6060], "buggy_code_start_loc": [0, 1434], "filenames": ["ChangeLog", "MagickCore/draw.c"], "fixing_code_end_loc": [4, 6073], "fixing_code_start_loc": [1, 1434], "message": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "FEF4935E-1F84-4394-A897-30F56CDC0B1A", "versionEndExcluding": null, "versionEndIncluding": "6.9.3-0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.0-0:*:*:*:*:*:*:*", "matchCriteriaId": "3B7CCC6B-C66E-48E2-BA1E-CBF6421B4FEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-0:*:*:*:*:*:*:*", "matchCriteriaId": "693C9F8F-A8C1-4D06-8F31-E085E16E701C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.1-1:*:*:*:*:*:*:*", "matchCriteriaId": "6D3D3DFC-8459-41BA-BF3E-AE84E48FCEE7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The DrawDashPolygon function in MagickCore/draw.c in ImageMagick before 6.9.4-0 and 7.x before 7.0.1-2 mishandles calculations of certain vertices integer data, which allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted file."}, {"lang": "es", "value": "La funci\u00f3n DrawDashPolygon en MagickCore/draw.c en ImageMagick en versiones anteriores a 6.9.4-0 y 7.x en versiones anteriores a 7.0.1-2 no maneja correctamente los c\u00e1lculos de ciertos v\u00e9rtices de datos integrados, lo que permite a atacantes remotos provocar una denegaci\u00f3n de servicio (desbordamiento de buffer y ca\u00edda de aplicaci\u00f3n) o posiblemente tener otro impacto no especificado a trav\u00e9s de un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2016-4562", "lastModified": "2016-09-23T02:00:17.293", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2016-06-04T16:59:00.140", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.imagemagick.org/script/changelog.php"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.oracle.com/technetwork/topics/security/bulletinjul2016-3090568.html"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/726812fa2fa7ce16bcf58f6e115f65427a1c0950"}, "type": "CWE-119"}
122
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n# MantisBT - A PHP based bugtracking system", "# MantisBT is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#\n# MantisBT 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with MantisBT. If not, see <http://www.gnu.org/licenses/>.", "/**\n * CALLERS\n *\tThis page is called from:\n *\t- print_menu()\n *\t- print_account_menu()\n *\n * EXPECTED BEHAVIOUR\n *\t- Display the user's current sponsorships\n *\t- Allow the user to edit the payment flag\n *\n * CALLS\n *\tThis page calls the following pages:\n *\t- account_sponsor_update.php (to save changes)\n *\n * RESTRICTIONS & PERMISSIONS\n *\t- User must be authenticated, and not anonymous\n * - sponsorship must be enabled\n *\n * @package MantisBT\n * @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org\n * @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net\n * @link http://www.mantisbt.org\n *\n * @uses core.php\n * @uses access_api.php\n * @uses authentication_api.php\n * @uses bug_api.php\n * @uses config_api.php\n * @uses constant_inc.php\n * @uses current_user_api.php\n * @uses database_api.php\n * @uses form_api.php\n * @uses gpc_api.php\n * @uses helper_api.php\n * @uses html_api.php\n * @uses lang_api.php\n * @uses print_api.php\n * @uses project_api.php\n * @uses sponsorship_api.php\n * @uses string_api.php\n * @uses version_api.php\n */", "require_once( 'core.php' );\nrequire_api( 'access_api.php' );\nrequire_api( 'authentication_api.php' );\nrequire_api( 'bug_api.php' );\nrequire_api( 'config_api.php' );\nrequire_api( 'constant_inc.php' );\nrequire_api( 'current_user_api.php' );\nrequire_api( 'database_api.php' );\nrequire_api( 'form_api.php' );\nrequire_api( 'gpc_api.php' );\nrequire_api( 'helper_api.php' );\nrequire_api( 'html_api.php' );\nrequire_api( 'lang_api.php' );\nrequire_api( 'print_api.php' );\nrequire_api( 'project_api.php' );\nrequire_api( 'sponsorship_api.php' );\nrequire_api( 'string_api.php' );\nrequire_api( 'version_api.php' );", "require_css( 'status_config.php' );", "if ( !config_get( 'enable_sponsorship' ) ) {\n\ttrigger_error( ERROR_SPONSORSHIP_NOT_ENABLED, ERROR );\n}", "# anonymous users are not allowed to sponsor issues\nif ( current_user_is_anonymous() ) {\n\taccess_denied();\n}", "$t_show_all = gpc_get_bool( 'show_all', false );", "# start the page\nhtml_page_top( lang_get( 'my_sponsorship' ) );", "$t_project = helper_get_current_project();\n?>\n<br />\n<table class=\"width100\" cellspacing=\"1\">\n<tr>\n\t<td class=\"form-title\">\n\t\t<?php echo lang_get( 'my_sponsorship' ) ?>\n\t</td>\n\t<td class=\"right\">\n\t\t<?php print_account_menu( 'account_sponsor_page.php' ) ?>\n\t</td>\n</tr>\n</table>\n<?php\n# get issues user has sponsored\n$t_user = auth_get_current_user_id();\n$t_resolved = config_get( 'bug_resolved_status_threshold' );\n$t_bug_table = db_get_table( 'bug' );\n$t_sponsor_table = db_get_table( 'sponsorship' );\n$t_payment = config_get( 'payment_enable', 0 );", "$t_project_clause = helper_project_specific_where( $t_project );", "$t_query = \"SELECT b.id as bug, s.id as sponsor, s.paid, b.project_id, b.fixed_in_version, b.status\n\tFROM $t_bug_table b, $t_sponsor_table s\n\tWHERE s.user_id=\" . db_param() . \" AND s.bug_id = b.id \" .\n\t( $t_show_all ? '' : 'AND ( b.status < ' . db_param() . ' OR s.paid < ' . SPONSORSHIP_PAID . ')' ) . \"\n\tAND $t_project_clause\n\tORDER BY s.paid ASC, b.project_id ASC, b.fixed_in_version ASC, b.status ASC, b.id DESC\";", "$t_result = db_query_bound( $t_query, $t_show_all ? array( $t_user ) : array( $t_user , $t_resolved ) );", "$t_sponsors = array();\nwhile ( $t_row = db_fetch_array( $t_result ) ) {\n\t$t_sponsors[] = $t_row;\n}", "$t_sponsor_count = count( $t_sponsors );\nif ( $t_sponsor_count === 0 ) {\n\techo '<p>' . lang_get( 'no_own_sponsored' ) . '</p>';\n} else {\n?>", "<!-- # Edit own sponsorship Form BEGIN -->\n<br />\n<div>\n<table class=\"width100\" cellspacing=\"1\">", "\t<!-- Headings -->\n\t<tr>\n\t\t<td class=\"form-title\" colspan=\"9\">\n\t\t\t<?php echo lang_get( 'own_sponsored' ) ?>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_bug' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'email_project' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'fixed_in_version' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_handler' ) ?></td>\n\t\t<td class=\"form-title\" width=\"30%\"><?php echo lang_get( 'email_summary' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'amount' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\">&#160;</td>\n\t</tr>\n<?php\n\t$t_total_owing = 0;\n\t$t_total_paid = 0;\n\tfor ( $i = 0; $i < $t_sponsor_count; ++$i ) {\n\t\t$t_sponsor_row = $t_sponsors[$i];\n\t\t$t_bug = bug_get( $t_sponsor_row['bug'] );\n\t\t$t_sponsor = sponsorship_get( $t_sponsor_row['sponsor'] );", "\t\t# describe bug\n\t\t$t_status = string_attribute( get_enum_element( 'status', $t_bug->status, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_resolution = string_attribute( get_enum_element( 'resolution', $t_bug->resolution, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_version_id = version_get_id( $t_bug->fixed_in_version, $t_project );\n\t\tif ( ( false !== $t_version_id ) && ( VERSION_RELEASED == version_get_field( $t_version_id, 'released' ) ) ) {\n\t\t\t$t_released_label = '<a title=\"' . lang_get( 'released' ) . '\">' . $t_bug->fixed_in_version . '</a>';\n\t\t} else {\n\t\t\t$t_released_label = $t_bug->fixed_in_version;\n\t\t}", "\t\t# choose color based on status\n\t\t$status_label = html_get_status_css_class( $t_bug->status, auth_get_current_user_id(), $t_bug->project_id );", "\t\techo '<tr class=\"' . $status_label . '\">';\n\t\techo '<td><a href=\"' . string_get_bug_view_url( $row['bug'] ) . '\">' . bug_format_id( $row['bug'] ) . '</a></td>';", "\t\techo '<td>' . project_get_field( $t_bug->project_id, 'name' ) . '&#160;</td>';", "\t\techo '<td class=\"right\">' . $t_released_label . '&#160;</td>';\n\t\techo '<td><span class=\"issue-status\" title=\"' . $t_resolution . '\">' . $t_status . '</span></td>';\n\t\techo '<td>';\n\t\tprint_user( $t_bug->handler_id );\n\t\techo '</td>';", "\t\t# summary\n\t\techo '<td>' . string_display_line( $t_bug->summary );\n\t\tif ( VS_PRIVATE == $t_bug->view_state ) {\n\t\t\tprintf( ' <img src=\"%s\" alt=\"(%s)\" title=\"%s\" />', $t_icon_path . 'protected.gif', lang_get( 'private' ), lang_get( 'private' ) );\n\t\t}\n\t\techo '</td>';", "\t\t# describe sponsorship amount\n\t\techo '<td class=\"right\">' . sponsorship_format_amount( $t_sponsor->amount ) . '</td>';\n\t\techo '<td>' . get_enum_element( 'sponsorship', $t_sponsor->paid ) . '</td>';", "\t\tif ( SPONSORSHIP_PAID == $t_sponsor->paid ) {\n\t\t\t$t_total_paid += $t_sponsor->amount;\n\t\t} else {\n\t\t\t$t_total_owing += $t_sponsor->amount;\n\t\t}", "\t\techo '<td>';\n\t\tif ( $t_payment ) {\n\t\t\techo '(paypal button)';\n\t\t} else {\n\t\t\techo '&#160;';\n\t\t}\n\t\techo '</td>';\n\t\techo '</tr>';\n\t}\n?>\n<!-- Totals -->\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_owing' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_owing ) ?></td>\n\t<td colspan=\"2\"></td>\n</tr>\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_paid' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_paid ) ?></td>\n\t<td colspan=\"2\"></td>\n</tr>\n</table>\n</div>\n<?php } # end sponsored issues", "$t_query = \"SELECT b.id as bug, s.id as sponsor, s.paid, b.project_id, b.fixed_in_version, b.status\n\tFROM $t_bug_table b, $t_sponsor_table s\n\tWHERE b.handler_id=\" . db_param() . \" AND s.bug_id = b.id \" .\n\t( $t_show_all ? '' : 'AND ( b.status < ' . db_param() . ' OR s.paid < ' . SPONSORSHIP_PAID . ')' ) . \"\n\tAND $t_project_clause\n\tORDER BY s.paid ASC, b.project_id ASC, b.fixed_in_version ASC, b.status ASC, b.id DESC\";", "$t_result = db_query_bound( $t_query, $t_show_all ? array( $t_user ) : array( $t_user , $t_resolved ) );", "$t_sponsors = array();\nwhile ( $t_row = db_fetch_array( $t_result ) ) {\n\t$t_sponsors[] = $t_row;\n}", "$t_sponsor_count = count( $t_sponsors );\nif ( $t_sponsor_count === 0 ) {\n\techo '<p>' . lang_get( 'no_sponsored' ) . '</p>';\n} else {\n?>", "<!-- # Edit sponsorship Form BEGIN -->\n<br />\n<div>\n<form method=\"post\" action=\"account_sponsor_update.php\">\n<?php echo form_security_field( 'account_sponsor_update' ) ?>\n<table class=\"width100\" cellspacing=\"1\">", "\t<!-- Headings -->\n\t<tr>\n\t\t<td class=\"form-title\" colspan=\"8\">\n\t\t\t<?php echo lang_get( 'issues_handled' ) ?>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_bug' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'email_project' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'fixed_in_version' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"35%\"><?php echo lang_get( 'email_summary' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'sponsor' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'amount' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'status' ) ?></td>\n\t</tr>\n<?php\n\t$t_bug_list = array();\n\t$t_total_owing = 0;\n\t$t_total_paid = 0;\n\tfor ( $i = 0; $i < $t_sponsor_count; ++$i ) {\n\t\t$t_sponsor_row = $t_sponsors[$i];\n\t\t$t_bug = bug_get( $t_sponsor_row['bug'] );\n\t\t$t_sponsor = sponsorship_get( $t_sponsor_row['sponsor'] );\n\t\t$t_buglist[] = $t_sponsor_row['bug'] . ':' . $t_sponsor_row['sponsor'];", "\t\t# describe bug\n\t\t$t_status = string_attribute( get_enum_element( 'status', $t_bug->status, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_resolution = string_attribute( get_enum_element( 'resolution', $t_bug->resolution, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_version_id = version_get_id( $t_bug->fixed_in_version, $t_project );\n\t\tif ( ( false !== $t_version_id ) && ( VERSION_RELEASED == version_get_field( $t_version_id, 'released' ) ) ) {\n\t\t\t$t_released_label = '<a title=\"' . lang_get( 'released' ) . '\">' . $t_bug->fixed_in_version . '</a>';\n\t\t} else {\n\t\t\t$t_released_label = $t_bug->fixed_in_version;\n\t\t}", "\t\t# choose color based on status\n\t\t$status_label = html_get_status_css_class( $t_bug->status, auth_get_current_user_id(), $t_bug->project_id );", "\t\techo '<tr class=\"' . $status_label . '\">';\n\t\techo '<td><a href=\"' . string_get_bug_view_url( $row['bug'] ) . '\">' . bug_format_id( $row['bug'] ) . '</a></td>';", "\t\techo '<td>' . project_get_field( $t_bug->project_id, 'name' ) . '&#160;</td>';", "\t\techo '<td class=\"right\">' . $t_released_label . '&#160;</td>';\n\t\techo '<td><a title=\"' . $t_resolution . '\"><span class=\"underline\">' . $t_status . '</span>&#160;</a></td>';", "\t\t# summary\n\t\techo '<td>' . string_display_line( $t_bug->summary );\n\t\tif ( VS_PRIVATE == $t_bug->view_state ) {\n\t\t\tprintf( ' <img src=\"%s\" alt=\"(%s)\" title=\"%s\" />', $t_icon_path . 'protected.gif', lang_get( 'private' ), lang_get( 'private' ) );\n\t\t}\n\t\techo '</td>';", "\t\t# describe sponsorship amount\n\t\techo '<td>';\n\t\tprint_user( $t_sponsor->user_id );\n\t\techo '</td>';\n\t\techo '<td class=\"right\">' . sponsorship_format_amount( $t_sponsor->amount ) . '</td>';\n\t\techo '<td><select name=\"sponsor_' . $row['bug'] . '_' . $t_sponsor->id . '\">';\n\t\tprint_enum_string_option_list( 'sponsorship', $t_sponsor->paid );\n\t\techo '</select></td>';", "\t\techo '</tr>';\n\t\tif ( SPONSORSHIP_PAID == $t_sponsor->paid ) {\n\t\t\t$t_total_paid += $t_sponsor->amount;\n\t\t} else {\n\t\t\t$t_total_owing += $t_sponsor->amount;\n\t\t}", "\t}\n\t$t_hidden_bug_list = implode( ',', $t_buglist );\n?>\n<!-- Totals -->\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_owing' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_owing ) ?></td>\n\t<td></td>\n</tr>\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_paid' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_paid ) ?></td>\n\t<td></td>\n</tr>\n\t<input type=\"hidden\" name=\"buglist\" value=\"<?php echo $t_hidden_bug_list ?>\" />\n\t<!-- BUTTONS -->\n\t<tr>\n\t\t<td colspan=\"5\">&#160;</td>\n\t\t<!-- Update Button -->\n\t\t<td colspan=\"2\">\n\t\t\t<input type=\"submit\" class=\"button\" value=\"<?php echo lang_get( 'update_sponsorship_button' ) ?>\" />\n\t\t</td>\n\t</tr>\n</table>\n</form>\n</div>\n<?php } # end sponsored issues ?>", "<br />\n<div>\n<?php\nhtml_button ( 'account_sponsor_page.php',\n\tlang_get( ( $t_show_all ? 'sponsor_hide' : 'sponsor_show' ) ),\n\tarray( 'show_all' => ( $t_show_all ? 0 : 1 ) ) );\n?>\n</div>", "<?php\nhtml_page_bottom();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [303], "buggy_code_start_loc": [183], "filenames": ["account_sponsor_page.php"], "fixing_code_end_loc": [303], "fixing_code_start_loc": [183], "message": "Cross-site scripting (XSS) vulnerability in account_sponsor_page.php in MantisBT 1.0.0 through 1.2.15 allows remote authenticated users to inject arbitrary web script or HTML via a project name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6B2602F7-2D93-4E1E-9425-4EDD23752029", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a1:*:*:*:*:*:*", "matchCriteriaId": "482256A6-B213-4226-AF03-9F93164AA337", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a2:*:*:*:*:*:*", "matchCriteriaId": "1F005474-CEBD-48FC-9C7F-861AFF771081", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a3:*:*:*:*:*:*", "matchCriteriaId": "BEF461E5-24D2-4540-A2FC-E0D4C3488B8F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "62F6B391-DDE3-4E8E-8582-85EA7287E591", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "80DBD667-1FB9-4354-9150-A190D4D817A2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "F27E40C0-263F-452B-8C91-E621A02EFC28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB888B14-EA67-4EDB-A3AF-ACD3F0A6227E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "1DB45A02-2522-4E10-BC81-48750ACB42DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "86DE3BE3-D6C9-4905-9E61-B70776460604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "F128A2E2-D509-4B50-95C2-1A31C5B3B31F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "140D5F68-1CAB-458C-BC8B-4F726D657FE8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "0D25F4F5-7678-41C1-93CB-305883A08527", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "D1A1316D-314B-4740-A836-D5E6319F4B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "DBD27CCE-28C4-43CC-8CBD-D7FFB46171AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "97298C43-B881-4C11-ADB6-17A8E43EB84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "7257ADD7-C9B7-4F85-AA13-615DD033FD5C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "DE6A94C0-48A1-4D42-AC43-7B4E959C4E21", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "02FE950B-5E29-4FAA-9BE5-79F38B4C38F7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a1:*:*:*:*:*:*", "matchCriteriaId": "45FF2B45-AA64-4428-8F6E-65C5171990CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a2:*:*:*:*:*:*", "matchCriteriaId": "CC868663-1E48-4F9A-B687-5B48D016611B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a3:*:*:*:*:*:*", "matchCriteriaId": "4F04ED02-4D99-45CF-9BEC-AC0F648748EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a4:*:*:*:*:*:*", "matchCriteriaId": "0AC08731-C4BB-4D84-ADBE-80054149BF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "35AAF0B4-31B5-4849-813F-63D9546C2E16", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "FB98EF06-7D6E-4D5F-819D-21B437E91B58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "66AB409E-5A5B-4455-8B68-22C32152681B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D6F2BA78-D054-4E49-ABCA-637922898BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4595B1E3-25AB-489E-A847-FDBF2554DD6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "E6A13A38-E149-42A7-9309-BC991521320B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "C11A8F17-5253-475B-89FF-A26EA7531E13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "4A88B09D-CDCF-45FD-B004-13B597DA4F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "49583BE8-B832-4E9F-B154-47A26C72489D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "E2501F40-3630-4528-BE0A-61D4BB6EC7FE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "9223DAF7-D03E-4A4E-8AB5-5CEB87DFF2C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "078C0943-C27C-44A9-B00D-5A261C58D6CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "CFF77ABF-0A03-437A-B241-1EF2BBB83D24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "9DA2615A-CD65-4765-AB0A-D72C2BEB00F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "7D09CC46-DFA2-408D-8720-05C23E73C859", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "3461212B-A96B-4D38-A722-84E7418C2A7A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "7B6DEE14-744B-4DE4-BDCF-E4E4D37F70A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "D4462BEE-39B6-47BD-B08F-5BE1FD918221", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5F096CD6-534E-4ABF-B2DF-D4B55B8C5F6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A66AB537-6FBA-4A51-B10C-BF61F54BC01B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "A50835BF-D28B-47FF-81F0-C34D95D6F2E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BA0EB9A6-1DFD-4C17-A002-0899DA252A56", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "BBA33285-3EE7-43FD-8347-E7D9A18DC134", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "8827C2B4-EBEC-4D64-9AC8-07A048467F40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "1F32DFF4-6448-46FD-9358-4FB1C310EC2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "20328CE4-0488-43B8-AA64-A6CB2230C74C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "0BDEB950-D3F4-4B96-B456-B8441DC403D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "FE69E6A6-8CD2-4C8A-A30A-CB0A04AC539F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "D464F7CF-A156-4EE5-BB59-6C759448EB23", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "5F1BFB72-CDD6-466E-ACAD-EA442D11C22F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "DD11DD1B-EC1C-48F4-B4C6-1CF6A0F80970", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "5899A557-AC72-4CB0-984F-F274AE5932BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in account_sponsor_page.php in MantisBT 1.0.0 through 1.2.15 allows remote authenticated users to inject arbitrary web script or HTML via a project name."}, {"lang": "es", "value": "Vulnerabilidad cross-site scripting (XSS) en account_sponsor_page.php de MantisBT 1.0.0 hasta 1.2.15 permite a usuarios remotos autenticados inyectar script web o HTML de forma arbitraria a trav\u00e9s de un nombre de proyecto."}], "evaluatorComment": null, "id": "CVE-2013-4460", "lastModified": "2021-01-12T18:05:59.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-01-10T15:55:03.773", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://seclists.org/oss-sec/2013/q4/168"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.mantisbt.org/bugs/view.php?id=16513"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/mantisbt/mantisbt/commit/0002d106a6cd35cb0a6fe03246531a4e3f32c9d0#diff-4122320b011a3291cd45da074a867076"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mantisbt/mantisbt/commit/0002d106a6cd35cb0a6fe03246531a4e3f32c9d0#diff-4122320b011a3291cd45da074a867076"}, "type": "CWE-79"}
123
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n# MantisBT - A PHP based bugtracking system", "# MantisBT is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#\n# MantisBT 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with MantisBT. If not, see <http://www.gnu.org/licenses/>.", "/**\n * CALLERS\n *\tThis page is called from:\n *\t- print_menu()\n *\t- print_account_menu()\n *\n * EXPECTED BEHAVIOUR\n *\t- Display the user's current sponsorships\n *\t- Allow the user to edit the payment flag\n *\n * CALLS\n *\tThis page calls the following pages:\n *\t- account_sponsor_update.php (to save changes)\n *\n * RESTRICTIONS & PERMISSIONS\n *\t- User must be authenticated, and not anonymous\n * - sponsorship must be enabled\n *\n * @package MantisBT\n * @copyright Copyright 2000 - 2002 Kenzaburo Ito - kenito@300baud.org\n * @copyright Copyright 2002 MantisBT Team - mantisbt-dev@lists.sourceforge.net\n * @link http://www.mantisbt.org\n *\n * @uses core.php\n * @uses access_api.php\n * @uses authentication_api.php\n * @uses bug_api.php\n * @uses config_api.php\n * @uses constant_inc.php\n * @uses current_user_api.php\n * @uses database_api.php\n * @uses form_api.php\n * @uses gpc_api.php\n * @uses helper_api.php\n * @uses html_api.php\n * @uses lang_api.php\n * @uses print_api.php\n * @uses project_api.php\n * @uses sponsorship_api.php\n * @uses string_api.php\n * @uses version_api.php\n */", "require_once( 'core.php' );\nrequire_api( 'access_api.php' );\nrequire_api( 'authentication_api.php' );\nrequire_api( 'bug_api.php' );\nrequire_api( 'config_api.php' );\nrequire_api( 'constant_inc.php' );\nrequire_api( 'current_user_api.php' );\nrequire_api( 'database_api.php' );\nrequire_api( 'form_api.php' );\nrequire_api( 'gpc_api.php' );\nrequire_api( 'helper_api.php' );\nrequire_api( 'html_api.php' );\nrequire_api( 'lang_api.php' );\nrequire_api( 'print_api.php' );\nrequire_api( 'project_api.php' );\nrequire_api( 'sponsorship_api.php' );\nrequire_api( 'string_api.php' );\nrequire_api( 'version_api.php' );", "require_css( 'status_config.php' );", "if ( !config_get( 'enable_sponsorship' ) ) {\n\ttrigger_error( ERROR_SPONSORSHIP_NOT_ENABLED, ERROR );\n}", "# anonymous users are not allowed to sponsor issues\nif ( current_user_is_anonymous() ) {\n\taccess_denied();\n}", "$t_show_all = gpc_get_bool( 'show_all', false );", "# start the page\nhtml_page_top( lang_get( 'my_sponsorship' ) );", "$t_project = helper_get_current_project();\n?>\n<br />\n<table class=\"width100\" cellspacing=\"1\">\n<tr>\n\t<td class=\"form-title\">\n\t\t<?php echo lang_get( 'my_sponsorship' ) ?>\n\t</td>\n\t<td class=\"right\">\n\t\t<?php print_account_menu( 'account_sponsor_page.php' ) ?>\n\t</td>\n</tr>\n</table>\n<?php\n# get issues user has sponsored\n$t_user = auth_get_current_user_id();\n$t_resolved = config_get( 'bug_resolved_status_threshold' );\n$t_bug_table = db_get_table( 'bug' );\n$t_sponsor_table = db_get_table( 'sponsorship' );\n$t_payment = config_get( 'payment_enable', 0 );", "$t_project_clause = helper_project_specific_where( $t_project );", "$t_query = \"SELECT b.id as bug, s.id as sponsor, s.paid, b.project_id, b.fixed_in_version, b.status\n\tFROM $t_bug_table b, $t_sponsor_table s\n\tWHERE s.user_id=\" . db_param() . \" AND s.bug_id = b.id \" .\n\t( $t_show_all ? '' : 'AND ( b.status < ' . db_param() . ' OR s.paid < ' . SPONSORSHIP_PAID . ')' ) . \"\n\tAND $t_project_clause\n\tORDER BY s.paid ASC, b.project_id ASC, b.fixed_in_version ASC, b.status ASC, b.id DESC\";", "$t_result = db_query_bound( $t_query, $t_show_all ? array( $t_user ) : array( $t_user , $t_resolved ) );", "$t_sponsors = array();\nwhile ( $t_row = db_fetch_array( $t_result ) ) {\n\t$t_sponsors[] = $t_row;\n}", "$t_sponsor_count = count( $t_sponsors );\nif ( $t_sponsor_count === 0 ) {\n\techo '<p>' . lang_get( 'no_own_sponsored' ) . '</p>';\n} else {\n?>", "<!-- # Edit own sponsorship Form BEGIN -->\n<br />\n<div>\n<table class=\"width100\" cellspacing=\"1\">", "\t<!-- Headings -->\n\t<tr>\n\t\t<td class=\"form-title\" colspan=\"9\">\n\t\t\t<?php echo lang_get( 'own_sponsored' ) ?>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_bug' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'email_project' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'fixed_in_version' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_handler' ) ?></td>\n\t\t<td class=\"form-title\" width=\"30%\"><?php echo lang_get( 'email_summary' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'amount' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\">&#160;</td>\n\t</tr>\n<?php\n\t$t_total_owing = 0;\n\t$t_total_paid = 0;\n\tfor ( $i = 0; $i < $t_sponsor_count; ++$i ) {\n\t\t$t_sponsor_row = $t_sponsors[$i];\n\t\t$t_bug = bug_get( $t_sponsor_row['bug'] );\n\t\t$t_sponsor = sponsorship_get( $t_sponsor_row['sponsor'] );", "\t\t# describe bug\n\t\t$t_status = string_attribute( get_enum_element( 'status', $t_bug->status, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_resolution = string_attribute( get_enum_element( 'resolution', $t_bug->resolution, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_version_id = version_get_id( $t_bug->fixed_in_version, $t_project );\n\t\tif ( ( false !== $t_version_id ) && ( VERSION_RELEASED == version_get_field( $t_version_id, 'released' ) ) ) {\n\t\t\t$t_released_label = '<a title=\"' . lang_get( 'released' ) . '\">' . $t_bug->fixed_in_version . '</a>';\n\t\t} else {\n\t\t\t$t_released_label = $t_bug->fixed_in_version;\n\t\t}", "\t\t# choose color based on status\n\t\t$status_label = html_get_status_css_class( $t_bug->status, auth_get_current_user_id(), $t_bug->project_id );", "\t\techo '<tr class=\"' . $status_label . '\">';\n\t\techo '<td><a href=\"' . string_get_bug_view_url( $row['bug'] ) . '\">' . bug_format_id( $row['bug'] ) . '</a></td>';", "\t\techo '<td>' . string_display_line( project_get_field( $t_bug->project_id, 'name' ) ) . '&#160;</td>';", "\t\techo '<td class=\"right\">' . $t_released_label . '&#160;</td>';\n\t\techo '<td><span class=\"issue-status\" title=\"' . $t_resolution . '\">' . $t_status . '</span></td>';\n\t\techo '<td>';\n\t\tprint_user( $t_bug->handler_id );\n\t\techo '</td>';", "\t\t# summary\n\t\techo '<td>' . string_display_line( $t_bug->summary );\n\t\tif ( VS_PRIVATE == $t_bug->view_state ) {\n\t\t\tprintf( ' <img src=\"%s\" alt=\"(%s)\" title=\"%s\" />', $t_icon_path . 'protected.gif', lang_get( 'private' ), lang_get( 'private' ) );\n\t\t}\n\t\techo '</td>';", "\t\t# describe sponsorship amount\n\t\techo '<td class=\"right\">' . sponsorship_format_amount( $t_sponsor->amount ) . '</td>';\n\t\techo '<td>' . get_enum_element( 'sponsorship', $t_sponsor->paid ) . '</td>';", "\t\tif ( SPONSORSHIP_PAID == $t_sponsor->paid ) {\n\t\t\t$t_total_paid += $t_sponsor->amount;\n\t\t} else {\n\t\t\t$t_total_owing += $t_sponsor->amount;\n\t\t}", "\t\techo '<td>';\n\t\tif ( $t_payment ) {\n\t\t\techo '(paypal button)';\n\t\t} else {\n\t\t\techo '&#160;';\n\t\t}\n\t\techo '</td>';\n\t\techo '</tr>';\n\t}\n?>\n<!-- Totals -->\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_owing' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_owing ) ?></td>\n\t<td colspan=\"2\"></td>\n</tr>\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_paid' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_paid ) ?></td>\n\t<td colspan=\"2\"></td>\n</tr>\n</table>\n</div>\n<?php } # end sponsored issues", "$t_query = \"SELECT b.id as bug, s.id as sponsor, s.paid, b.project_id, b.fixed_in_version, b.status\n\tFROM $t_bug_table b, $t_sponsor_table s\n\tWHERE b.handler_id=\" . db_param() . \" AND s.bug_id = b.id \" .\n\t( $t_show_all ? '' : 'AND ( b.status < ' . db_param() . ' OR s.paid < ' . SPONSORSHIP_PAID . ')' ) . \"\n\tAND $t_project_clause\n\tORDER BY s.paid ASC, b.project_id ASC, b.fixed_in_version ASC, b.status ASC, b.id DESC\";", "$t_result = db_query_bound( $t_query, $t_show_all ? array( $t_user ) : array( $t_user , $t_resolved ) );", "$t_sponsors = array();\nwhile ( $t_row = db_fetch_array( $t_result ) ) {\n\t$t_sponsors[] = $t_row;\n}", "$t_sponsor_count = count( $t_sponsors );\nif ( $t_sponsor_count === 0 ) {\n\techo '<p>' . lang_get( 'no_sponsored' ) . '</p>';\n} else {\n?>", "<!-- # Edit sponsorship Form BEGIN -->\n<br />\n<div>\n<form method=\"post\" action=\"account_sponsor_update.php\">\n<?php echo form_security_field( 'account_sponsor_update' ) ?>\n<table class=\"width100\" cellspacing=\"1\">", "\t<!-- Headings -->\n\t<tr>\n\t\t<td class=\"form-title\" colspan=\"8\">\n\t\t\t<?php echo lang_get( 'issues_handled' ) ?>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_bug' ) ?></td>\n\t\t<td class=\"form-title\" width=\"8%\"><?php echo lang_get( 'email_project' ) ?></td>\n\t\t<td class=\"form-title\" width=\"7%\"><?php echo lang_get( 'fixed_in_version' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'email_status' ) ?></td>\n\t\t<td class=\"form-title\" width=\"35%\"><?php echo lang_get( 'email_summary' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'sponsor' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'amount' ) ?></td>\n\t\t<td class=\"form-title\" width=\"10%\"><?php echo lang_get( 'status' ) ?></td>\n\t</tr>\n<?php\n\t$t_bug_list = array();\n\t$t_total_owing = 0;\n\t$t_total_paid = 0;\n\tfor ( $i = 0; $i < $t_sponsor_count; ++$i ) {\n\t\t$t_sponsor_row = $t_sponsors[$i];\n\t\t$t_bug = bug_get( $t_sponsor_row['bug'] );\n\t\t$t_sponsor = sponsorship_get( $t_sponsor_row['sponsor'] );\n\t\t$t_buglist[] = $t_sponsor_row['bug'] . ':' . $t_sponsor_row['sponsor'];", "\t\t# describe bug\n\t\t$t_status = string_attribute( get_enum_element( 'status', $t_bug->status, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_resolution = string_attribute( get_enum_element( 'resolution', $t_bug->resolution, auth_get_current_user_id(), $t_bug->project_id ) );\n\t\t$t_version_id = version_get_id( $t_bug->fixed_in_version, $t_project );\n\t\tif ( ( false !== $t_version_id ) && ( VERSION_RELEASED == version_get_field( $t_version_id, 'released' ) ) ) {\n\t\t\t$t_released_label = '<a title=\"' . lang_get( 'released' ) . '\">' . $t_bug->fixed_in_version . '</a>';\n\t\t} else {\n\t\t\t$t_released_label = $t_bug->fixed_in_version;\n\t\t}", "\t\t# choose color based on status\n\t\t$status_label = html_get_status_css_class( $t_bug->status, auth_get_current_user_id(), $t_bug->project_id );", "\t\techo '<tr class=\"' . $status_label . '\">';\n\t\techo '<td><a href=\"' . string_get_bug_view_url( $row['bug'] ) . '\">' . bug_format_id( $row['bug'] ) . '</a></td>';", "\t\techo '<td>' . string_display_line( project_get_field( $t_bug->project_id, 'name' ) ) . '&#160;</td>';", "\t\techo '<td class=\"right\">' . $t_released_label . '&#160;</td>';\n\t\techo '<td><a title=\"' . $t_resolution . '\"><span class=\"underline\">' . $t_status . '</span>&#160;</a></td>';", "\t\t# summary\n\t\techo '<td>' . string_display_line( $t_bug->summary );\n\t\tif ( VS_PRIVATE == $t_bug->view_state ) {\n\t\t\tprintf( ' <img src=\"%s\" alt=\"(%s)\" title=\"%s\" />', $t_icon_path . 'protected.gif', lang_get( 'private' ), lang_get( 'private' ) );\n\t\t}\n\t\techo '</td>';", "\t\t# describe sponsorship amount\n\t\techo '<td>';\n\t\tprint_user( $t_sponsor->user_id );\n\t\techo '</td>';\n\t\techo '<td class=\"right\">' . sponsorship_format_amount( $t_sponsor->amount ) . '</td>';\n\t\techo '<td><select name=\"sponsor_' . $row['bug'] . '_' . $t_sponsor->id . '\">';\n\t\tprint_enum_string_option_list( 'sponsorship', $t_sponsor->paid );\n\t\techo '</select></td>';", "\t\techo '</tr>';\n\t\tif ( SPONSORSHIP_PAID == $t_sponsor->paid ) {\n\t\t\t$t_total_paid += $t_sponsor->amount;\n\t\t} else {\n\t\t\t$t_total_owing += $t_sponsor->amount;\n\t\t}", "\t}\n\t$t_hidden_bug_list = implode( ',', $t_buglist );\n?>\n<!-- Totals -->\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_owing' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_owing ) ?></td>\n\t<td></td>\n</tr>\n<tr>\n\t<td colspan=\"5\"></td>\n\t<td><?php echo lang_get( 'total_paid' ) ?></td>\n\t<td class=\"right\"><?php echo sponsorship_format_amount( $t_total_paid ) ?></td>\n\t<td></td>\n</tr>\n\t<input type=\"hidden\" name=\"buglist\" value=\"<?php echo $t_hidden_bug_list ?>\" />\n\t<!-- BUTTONS -->\n\t<tr>\n\t\t<td colspan=\"5\">&#160;</td>\n\t\t<!-- Update Button -->\n\t\t<td colspan=\"2\">\n\t\t\t<input type=\"submit\" class=\"button\" value=\"<?php echo lang_get( 'update_sponsorship_button' ) ?>\" />\n\t\t</td>\n\t</tr>\n</table>\n</form>\n</div>\n<?php } # end sponsored issues ?>", "<br />\n<div>\n<?php\nhtml_button ( 'account_sponsor_page.php',\n\tlang_get( ( $t_show_all ? 'sponsor_hide' : 'sponsor_show' ) ),\n\tarray( 'show_all' => ( $t_show_all ? 0 : 1 ) ) );\n?>\n</div>", "<?php\nhtml_page_bottom();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [303], "buggy_code_start_loc": [183], "filenames": ["account_sponsor_page.php"], "fixing_code_end_loc": [303], "fixing_code_start_loc": [183], "message": "Cross-site scripting (XSS) vulnerability in account_sponsor_page.php in MantisBT 1.0.0 through 1.2.15 allows remote authenticated users to inject arbitrary web script or HTML via a project name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6B2602F7-2D93-4E1E-9425-4EDD23752029", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a1:*:*:*:*:*:*", "matchCriteriaId": "482256A6-B213-4226-AF03-9F93164AA337", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a2:*:*:*:*:*:*", "matchCriteriaId": "1F005474-CEBD-48FC-9C7F-861AFF771081", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:a3:*:*:*:*:*:*", "matchCriteriaId": "BEF461E5-24D2-4540-A2FC-E0D4C3488B8F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "62F6B391-DDE3-4E8E-8582-85EA7287E591", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "80DBD667-1FB9-4354-9150-A190D4D817A2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "F27E40C0-263F-452B-8C91-E621A02EFC28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB888B14-EA67-4EDB-A3AF-ACD3F0A6227E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "1DB45A02-2522-4E10-BC81-48750ACB42DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "86DE3BE3-D6C9-4905-9E61-B70776460604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "F128A2E2-D509-4B50-95C2-1A31C5B3B31F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "140D5F68-1CAB-458C-BC8B-4F726D657FE8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "0D25F4F5-7678-41C1-93CB-305883A08527", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "D1A1316D-314B-4740-A836-D5E6319F4B28", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "DBD27CCE-28C4-43CC-8CBD-D7FFB46171AC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "97298C43-B881-4C11-ADB6-17A8E43EB84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "7257ADD7-C9B7-4F85-AA13-615DD033FD5C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "DE6A94C0-48A1-4D42-AC43-7B4E959C4E21", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "02FE950B-5E29-4FAA-9BE5-79F38B4C38F7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a1:*:*:*:*:*:*", "matchCriteriaId": "45FF2B45-AA64-4428-8F6E-65C5171990CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a2:*:*:*:*:*:*", "matchCriteriaId": "CC868663-1E48-4F9A-B687-5B48D016611B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a3:*:*:*:*:*:*", "matchCriteriaId": "4F04ED02-4D99-45CF-9BEC-AC0F648748EA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:a4:*:*:*:*:*:*", "matchCriteriaId": "0AC08731-C4BB-4D84-ADBE-80054149BF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "35AAF0B4-31B5-4849-813F-63D9546C2E16", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "FB98EF06-7D6E-4D5F-819D-21B437E91B58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "66AB409E-5A5B-4455-8B68-22C32152681B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D6F2BA78-D054-4E49-ABCA-637922898BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4595B1E3-25AB-489E-A847-FDBF2554DD6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "E6A13A38-E149-42A7-9309-BC991521320B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "C11A8F17-5253-475B-89FF-A26EA7531E13", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "4A88B09D-CDCF-45FD-B004-13B597DA4F48", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "49583BE8-B832-4E9F-B154-47A26C72489D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "E2501F40-3630-4528-BE0A-61D4BB6EC7FE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "9223DAF7-D03E-4A4E-8AB5-5CEB87DFF2C3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "078C0943-C27C-44A9-B00D-5A261C58D6CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "CFF77ABF-0A03-437A-B241-1EF2BBB83D24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "9DA2615A-CD65-4765-AB0A-D72C2BEB00F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "7D09CC46-DFA2-408D-8720-05C23E73C859", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "3461212B-A96B-4D38-A722-84E7418C2A7A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "7B6DEE14-744B-4DE4-BDCF-E4E4D37F70A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "D4462BEE-39B6-47BD-B08F-5BE1FD918221", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5F096CD6-534E-4ABF-B2DF-D4B55B8C5F6A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "A66AB537-6FBA-4A51-B10C-BF61F54BC01B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "A50835BF-D28B-47FF-81F0-C34D95D6F2E9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BA0EB9A6-1DFD-4C17-A002-0899DA252A56", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "BBA33285-3EE7-43FD-8347-E7D9A18DC134", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "8827C2B4-EBEC-4D64-9AC8-07A048467F40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "1F32DFF4-6448-46FD-9358-4FB1C310EC2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "20328CE4-0488-43B8-AA64-A6CB2230C74C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "0BDEB950-D3F4-4B96-B456-B8441DC403D9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "FE69E6A6-8CD2-4C8A-A30A-CB0A04AC539F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "D464F7CF-A156-4EE5-BB59-6C759448EB23", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "5F1BFB72-CDD6-466E-ACAD-EA442D11C22F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "DD11DD1B-EC1C-48F4-B4C6-1CF6A0F80970", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mantisbt:mantisbt:1.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "5899A557-AC72-4CB0-984F-F274AE5932BB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in account_sponsor_page.php in MantisBT 1.0.0 through 1.2.15 allows remote authenticated users to inject arbitrary web script or HTML via a project name."}, {"lang": "es", "value": "Vulnerabilidad cross-site scripting (XSS) en account_sponsor_page.php de MantisBT 1.0.0 hasta 1.2.15 permite a usuarios remotos autenticados inyectar script web o HTML de forma arbitraria a trav\u00e9s de un nombre de proyecto."}], "evaluatorComment": null, "id": "CVE-2013-4460", "lastModified": "2021-01-12T18:05:59.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-01-10T15:55:03.773", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://seclists.org/oss-sec/2013/q4/168"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.mantisbt.org/bugs/view.php?id=16513"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Patch"], "url": "https://github.com/mantisbt/mantisbt/commit/0002d106a6cd35cb0a6fe03246531a4e3f32c9d0#diff-4122320b011a3291cd45da074a867076"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mantisbt/mantisbt/commit/0002d106a6cd35cb0a6fe03246531a4e3f32c9d0#diff-4122320b011a3291cd45da074a867076"}, "type": "CWE-79"}
123
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.apiv1.servermaintenancemode.representers", "import com.thoughtworks.go.helper.JobInstanceMother\nimport com.thoughtworks.go.helper.MaterialsMother\nimport com.thoughtworks.go.server.domain.ServerMaintenanceMode\nimport com.thoughtworks.go.server.service.MaintenanceModeService\nimport com.thoughtworks.go.util.SystemEnvironment\nimport com.thoughtworks.go.util.TimeProvider\nimport org.junit.jupiter.api.BeforeEach\nimport org.junit.jupiter.api.Test\nimport org.mockito.Mock", "import java.sql.Timestamp", "import static com.thoughtworks.go.CurrentGoCDVersion.apiDocsUrl\nimport static com.thoughtworks.go.api.base.JsonOutputWriter.jsonDate\nimport static com.thoughtworks.go.api.base.JsonUtils.toObjectString\nimport static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson\nimport static org.mockito.Mockito.when\nimport static org.mockito.MockitoAnnotations.initMocks", "class MaintenanceModeInfoRepresenterTest {\n @BeforeEach\n void setUp() {\n initMocks(this)\n }", " @Mock\n TimeProvider timeProvider", " @Mock\n SystemEnvironment systemEnvironment", " @Test\n void \"should represent maintenance mode info\"() {\n def maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment)", " def gitMaterial = MaterialsMother.gitMaterial(\"foo/bar\")\n def hgMaterial = MaterialsMother.hgMaterial()\n def svnMaterial = MaterialsMother.svnMaterial()", " def gitMaterialMDUStartTime = 10000000l\n def hgMaterialMDUStartTime = 20000000l\n def svnMaterialMDUStartTime = 30000000l", " when(timeProvider.currentTimeMillis())\n .thenReturn(gitMaterialMDUStartTime)\n .thenReturn(hgMaterialMDUStartTime)\n .thenReturn(svnMaterialMDUStartTime)", " maintenanceModeService.update(new ServerMaintenanceMode(true, \"admin\", new Date()))", " maintenanceModeService.mduStartedForMaterial(gitMaterial)\n maintenanceModeService.mduStartedForMaterial(hgMaterial)\n maintenanceModeService.mduStartedForMaterial(svnMaterial)", " def runningMDUs = maintenanceModeService.getRunningMDUs()\n def scheduled = JobInstanceMother.scheduled(\"up42_job_1\")\n def building = JobInstanceMother.building(\"up42_job_2\")", " def buildingJobs = Arrays.asList(building)\n def scheduledJobs = Arrays.asList(scheduled)", " def actualJson = toObjectString({\n MaintenanceModeInfoRepresenter.toJSON(it, maintenanceModeService.get(), true, runningMDUs, buildingJobs, scheduledJobs)\n })", " def expectedJson = [\n _links : [\n self: [href: 'http://test.host/go/api/admin/maintenance_mode/info'],\n doc : [href: apiDocsUrl('#maintenance-mode-info')]\n ],\n \"is_maintenance_mode\": true,\n \"metadata\" : [\n \"updated_by\": maintenanceModeService.get().updatedBy(),\n \"updated_on\": jsonDate(maintenanceModeService.get().updatedOn())\n ],\n \"attributes\" : [\n \"has_running_systems\": false,\n \"running_systems\" : [\n \"material_update_in_progress\": [\n [\n \"type\" : \"git\",\n \"attributes\" : [\n \"url\" : \"foo/bar\",\n \"destination\" : null,\n \"filter\" : null,\n \"invert_filter\" : false,\n \"name\" : null,\n \"auto_update\" : true,\n \"branch\" : \"master\",\n \"submodule_folder\": null,\n \"shallow_clone\" : false\n ],\n \"mdu_start_time\": \"1970-01-01T02:46:40Z\"\n ],\n [\n \"type\" : \"hg\",\n \"attributes\" : [\n \"url\" : \"hg-url\",\n \"destination\" : null,\n \"filter\" : null,\n \"invert_filter\": false,\n \"name\" : null,\n \"auto_update\" : true\n ],\n \"mdu_start_time\": \"1970-01-01T05:33:20Z\"\n ],\n [\n \"type\" : \"svn\",\n \"attributes\" : [\n \"url\" : \"url\",\n \"destination\" : \"svnDir\",\n \"filter\" : [\n \"ignore\": [\"*.doc\"]\n ],\n \"invert_filter\" : false,\n \"name\" : null,\n \"auto_update\" : true,\n \"check_externals\" : true,\n \"username\" : \"user\",", " \"encrypted_password\": svnMaterial.encryptedPassword", " ],\n \"mdu_start_time\": \"1970-01-01T08:20:00Z\"\n ]\n ],\n building_jobs : [\n [\n pipeline_name : building.pipelineName,\n pipeline_counter: building.pipelineCounter,\n stage_name : building.stageName,\n stage_counter : building.stageCounter,\n name : building.name,\n state : building.state,\n scheduled_date : jsonDate(new Timestamp(building.getScheduledDate().getTime())),\n agent_uuid : building.getAgentUuid()\n ]\n ],\n scheduled_jobs : [\n [\n pipeline_name : scheduled.pipelineName,\n pipeline_counter: scheduled.pipelineCounter,\n stage_name : scheduled.stageName,\n stage_counter : scheduled.stageCounter,\n name : scheduled.name,\n state : scheduled.state,\n scheduled_date : jsonDate(new Timestamp(scheduled.getScheduledDate().getTime())),\n agent_uuid : scheduled.getAgentUuid()\n ]\n ]\n ]\n ]\n ]", " assertThatJson(actualJson).isEqualTo(expectedJson)\n }", " @Test\n void 'should not add attributes if server is not in maintenance mode'() {\n def maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment)", " def actualJson = toObjectString({\n MaintenanceModeInfoRepresenter.toJSON(it, maintenanceModeService.get(), false, null, null, null)\n })", " def expectedJson = [\n _links : [\n self: [href: 'http://test.host/go/api/admin/maintenance_mode/info'],\n doc : [href: apiDocsUrl('#maintenance-mode-info')]\n ],\n \"is_maintenance_mode\": false,\n \"metadata\" : [\n \"updated_by\": maintenanceModeService.get().updatedBy(),\n \"updated_on\": jsonDate(maintenanceModeService.get().updatedOn())\n ]\n ]", " assertThatJson(actualJson).isEqualTo(expectedJson)\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.apiv1.servermaintenancemode.representers", "import com.thoughtworks.go.helper.JobInstanceMother\nimport com.thoughtworks.go.helper.MaterialsMother\nimport com.thoughtworks.go.server.domain.ServerMaintenanceMode\nimport com.thoughtworks.go.server.service.MaintenanceModeService\nimport com.thoughtworks.go.util.SystemEnvironment\nimport com.thoughtworks.go.util.TimeProvider\nimport org.junit.jupiter.api.BeforeEach\nimport org.junit.jupiter.api.Test\nimport org.mockito.Mock", "import java.sql.Timestamp", "import static com.thoughtworks.go.CurrentGoCDVersion.apiDocsUrl\nimport static com.thoughtworks.go.api.base.JsonOutputWriter.jsonDate\nimport static com.thoughtworks.go.api.base.JsonUtils.toObjectString\nimport static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson\nimport static org.mockito.Mockito.when\nimport static org.mockito.MockitoAnnotations.initMocks", "class MaintenanceModeInfoRepresenterTest {\n @BeforeEach\n void setUp() {\n initMocks(this)\n }", " @Mock\n TimeProvider timeProvider", " @Mock\n SystemEnvironment systemEnvironment", " @Test\n void \"should represent maintenance mode info\"() {\n def maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment)", " def gitMaterial = MaterialsMother.gitMaterial(\"foo/bar\")\n def hgMaterial = MaterialsMother.hgMaterial()\n def svnMaterial = MaterialsMother.svnMaterial()", " def gitMaterialMDUStartTime = 10000000l\n def hgMaterialMDUStartTime = 20000000l\n def svnMaterialMDUStartTime = 30000000l", " when(timeProvider.currentTimeMillis())\n .thenReturn(gitMaterialMDUStartTime)\n .thenReturn(hgMaterialMDUStartTime)\n .thenReturn(svnMaterialMDUStartTime)", " maintenanceModeService.update(new ServerMaintenanceMode(true, \"admin\", new Date()))", " maintenanceModeService.mduStartedForMaterial(gitMaterial)\n maintenanceModeService.mduStartedForMaterial(hgMaterial)\n maintenanceModeService.mduStartedForMaterial(svnMaterial)", " def runningMDUs = maintenanceModeService.getRunningMDUs()\n def scheduled = JobInstanceMother.scheduled(\"up42_job_1\")\n def building = JobInstanceMother.building(\"up42_job_2\")", " def buildingJobs = Arrays.asList(building)\n def scheduledJobs = Arrays.asList(scheduled)", " def actualJson = toObjectString({\n MaintenanceModeInfoRepresenter.toJSON(it, maintenanceModeService.get(), true, runningMDUs, buildingJobs, scheduledJobs)\n })", " def expectedJson = [\n _links : [\n self: [href: 'http://test.host/go/api/admin/maintenance_mode/info'],\n doc : [href: apiDocsUrl('#maintenance-mode-info')]\n ],\n \"is_maintenance_mode\": true,\n \"metadata\" : [\n \"updated_by\": maintenanceModeService.get().updatedBy(),\n \"updated_on\": jsonDate(maintenanceModeService.get().updatedOn())\n ],\n \"attributes\" : [\n \"has_running_systems\": false,\n \"running_systems\" : [\n \"material_update_in_progress\": [\n [\n \"type\" : \"git\",\n \"attributes\" : [\n \"url\" : \"foo/bar\",\n \"destination\" : null,\n \"filter\" : null,\n \"invert_filter\" : false,\n \"name\" : null,\n \"auto_update\" : true,\n \"branch\" : \"master\",\n \"submodule_folder\": null,\n \"shallow_clone\" : false\n ],\n \"mdu_start_time\": \"1970-01-01T02:46:40Z\"\n ],\n [\n \"type\" : \"hg\",\n \"attributes\" : [\n \"url\" : \"hg-url\",\n \"destination\" : null,\n \"filter\" : null,\n \"invert_filter\": false,\n \"name\" : null,\n \"auto_update\" : true\n ],\n \"mdu_start_time\": \"1970-01-01T05:33:20Z\"\n ],\n [\n \"type\" : \"svn\",\n \"attributes\" : [\n \"url\" : \"url\",\n \"destination\" : \"svnDir\",\n \"filter\" : [\n \"ignore\": [\"*.doc\"]\n ],\n \"invert_filter\" : false,\n \"name\" : null,\n \"auto_update\" : true,\n \"check_externals\" : true,\n \"username\" : \"user\",", " \"encrypted_password\": svnMaterial.config().getEncryptedPassword()", " ],\n \"mdu_start_time\": \"1970-01-01T08:20:00Z\"\n ]\n ],\n building_jobs : [\n [\n pipeline_name : building.pipelineName,\n pipeline_counter: building.pipelineCounter,\n stage_name : building.stageName,\n stage_counter : building.stageCounter,\n name : building.name,\n state : building.state,\n scheduled_date : jsonDate(new Timestamp(building.getScheduledDate().getTime())),\n agent_uuid : building.getAgentUuid()\n ]\n ],\n scheduled_jobs : [\n [\n pipeline_name : scheduled.pipelineName,\n pipeline_counter: scheduled.pipelineCounter,\n stage_name : scheduled.stageName,\n stage_counter : scheduled.stageCounter,\n name : scheduled.name,\n state : scheduled.state,\n scheduled_date : jsonDate(new Timestamp(scheduled.getScheduledDate().getTime())),\n agent_uuid : scheduled.getAgentUuid()\n ]\n ]\n ]\n ]\n ]", " assertThatJson(actualJson).isEqualTo(expectedJson)\n }", " @Test\n void 'should not add attributes if server is not in maintenance mode'() {\n def maintenanceModeService = new MaintenanceModeService(timeProvider, systemEnvironment)", " def actualJson = toObjectString({\n MaintenanceModeInfoRepresenter.toJSON(it, maintenanceModeService.get(), false, null, null, null)\n })", " def expectedJson = [\n _links : [\n self: [href: 'http://test.host/go/api/admin/maintenance_mode/info'],\n doc : [href: apiDocsUrl('#maintenance-mode-info')]\n ],\n \"is_maintenance_mode\": false,\n \"metadata\" : [\n \"updated_by\": maintenanceModeService.get().updatedBy(),\n \"updated_on\": jsonDate(maintenanceModeService.get().updatedOn())\n ]\n ]", " assertThatJson(actualJson).isEqualTo(expectedJson)\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.perforce;", "import com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.Modification;\nimport com.thoughtworks.go.domain.materials.perforce.P4Client;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.helper.P4TestRepo;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map;", "import static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.assertThatCode;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;", "public class P4MaterialTest extends P4MaterialTestBase {", " @Override\n protected P4TestRepo createTestRepo() throws Exception {\n P4TestRepo repo = P4TestRepo.createP4TestRepo(temporaryFolder, clientFolder);\n repo.onSetup();\n return repo;\n }", " @Test\n void shouldAddServerSideEnvironmentVariablesClientNameEnvironmentVariable() throws IOException {\n File p4_working_dir = temporaryFolder.newFolder();", " P4Material p4 = new P4Material(\"host:10\", \"beautiful\", \"user\");\n p4.setPassword(\"loser\");\n EnvironmentVariableContext envVarCtx;", " envVarCtx = new EnvironmentVariableContext();\n p4.populateEnvironmentContext(envVarCtx, new MaterialRevision(p4, new Modification(\"loser\", \"loserish commit\", \"loser@boozer.com\", new Date(), \"123\")), p4_working_dir);\n assertThat(envVarCtx.getProperty(\"GO_REVISION\")).isEqualTo(\"123\");\n assertThat(envVarCtx.getProperty(\"GO_TO_REVISION\")).isEqualTo(\"123\");\n assertThat(envVarCtx.getProperty(\"GO_FROM_REVISION\")).isEqualTo(\"123\");\n }", " @Test\n void shouldAddClientNameEnvironmentVariable() throws IOException {\n File p4_working_dir = temporaryFolder.newFolder();", " P4Material p4 = new P4Material(\"host:10\", \"beautiful\", \"user\");\n p4.setPassword(\"loser\");\n EnvironmentVariableContext envVarCtx;", " envVarCtx = new EnvironmentVariableContext();\n p4.populateAgentSideEnvironmentContext(envVarCtx, p4_working_dir);\n assertThat(envVarCtx.getProperty(\"GO_P4_CLIENT\")).isEqualTo(p4.clientName(p4_working_dir));\n }", " @Test\n void shouldGenerateTheSameP4ClientValueForCommandAndEnvironment() throws Exception {", " P4Material p4Material = new P4Material(\"server:10\", \"out-of-the-window\");\n ReflectionUtil.setField(p4Material, \"folder\", \"crapy_dir\");", " P4Client p4Client = p4Material._p4(tempDir, new InMemoryStreamConsumer(), false);", " assertThat(p4Client).isNotNull();\n String client = (String) ReflectionUtil.getField(p4Client, \"p4ClientName\");\n assertThat(client).isEqualTo(p4Material.clientName(tempDir));\n }", " @Test\n void shouldNotDisplayPasswordInStringRepresentation() {\n P4Material p4 = new P4Material(\"host:10\", \"beautiful\");\n p4.setUsername(\"user\");\n p4.setPassword(\"loser\");\n assertThat(p4.toString()).doesNotContain(\"loser\");\n }", " @Test", " void shouldEncryptP4Password() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");", " P4Material p4Material = new P4Material(\"example.com:1818\", \"view\", mockGoCipher);\n p4Material.setPassword(\"password\");\n p4Material.ensureEncrypted();", " assertThat(p4Material.getEncryptedPassword()).isEqualTo(\"encrypted\");\n assertThat(p4Material.getPassword()).isNull();\n }", " @Test\n void shouldDecryptP4Password() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");", " P4Material p4Material = new P4Material(\"example.com:1818\", \"view\", mockGoCipher);\n ReflectionUtil.setField(p4Material, \"encryptedPassword\", \"encrypted\");\n p4Material.getPassword();", " assertThat(p4Material.getPassword()).isEqualTo(\"password\");\n }", " @Test", " void shouldReturnEqualsEvenIfPasswordsAreDifferent() throws Exception {\n P4Material material = MaterialsMother.p4Material();\n material.setPassword(\"password\");", " P4Material other = MaterialsMother.p4Material();\n other.setPassword(\"password1\");\n assertThat(material).isEqualTo(other);\n }", " @Test\n void shouldNotConsiderPasswordForEqualityCheck() {\n P4Material one = new P4Material(\"host:123\", \"through_window\");\n one.setPassword(\"password\");\n P4Material two = new P4Material(\"host:123\", \"through_window\");\n two.setPassword(\"wordpass\");", " assertThat(one).isEqualTo(two);\n assertThat(one.hashCode()).isEqualTo(two.hashCode());\n }", " @Test\n void shouldGetLongDescriptionForMaterial() {\n P4Material material = new P4Material(\"host:123\", \"through_window\", \"user\", \"folder\");\n assertThat(material.getLongDescription()).isEqualTo(\"URL: host:123, View: through_window, Username: user\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() throws Exception {\n P4Material material = new P4Material(\"blah.com\", \"view\");\n material.setPassword(\"password\");", " P4MaterialConfig config = (P4MaterialConfig) material.config();", " assertThat(config.getPassword()).isEqualTo(\"password\");\n assertThat(config.getEncryptedPassword()).isNotNull();\n }", " @Test\n void shouldGetAttributesWithSecureFields() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\");\n material.setPassword(\"password\");\n material.setUseTickets(true);\n Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"perforce\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"perforce-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"host:1234\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"view\")).isEqualTo(\"view\");\n assertThat(configuration.get(\"use-tickets\")).isEqualTo(true);\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\");\n material.setPassword(\"password\");\n material.setUseTickets(true);\n Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"perforce\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"perforce-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"host:1234\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"view\")).isEqualTo(\"view\");\n assertThat(configuration.get(\"use-tickets\")).isEqualTo(true);\n }", " @Test\n void shouldSetGO_P4_CLIENT_toTheClientName() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\", \"destination\");\n EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext();\n File agentWorkingDirectory = new File(\"pipelines/pipeline-name\");\n material.populateAgentSideEnvironmentContext(environmentVariableContext, agentWorkingDirectory);\n assertThat(environmentVariableContext.getProperty(\"GO_P4_CLIENT_DESTINATION\")).isEqualTo(material.clientName(material.workingdir(agentWorkingDirectory)));\n }", " @Nested\n class hasSecretParams {\n @Test\n void shouldBeTrueIfMaterialUrlHasSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_password]}}\");", " assertThat(p4Material.hasSecretParams()).isTrue();\n }", " @Test\n void shouldBeFalseInMaterialUrlDoesNotHaveSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"foo\");", " assertThat(p4Material.hasSecretParams()).isFalse();\n }\n }", " @Nested\n class getSecretParams {\n @Test\n void shouldReturnAListOfSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_password]}}\");", " assertThat(p4Material.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_password\"));\n }", " @Test\n void shouldBeAnEmptyListInAbsenceOfSecretParamsinMaterialUrl() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"pass\");", " assertThat(p4Material.getSecretParams())\n .hasSize(0);\n }\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"badger\");", " assertThat(p4Material.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " p4Material.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(p4Material.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " assertThatCode(p4Material::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " assertThat(p4Material.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.perforce;", "import com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.Modification;\nimport com.thoughtworks.go.domain.materials.perforce.P4Client;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.helper.P4TestRepo;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map;", "import static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.assertThatCode;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;", "public class P4MaterialTest extends P4MaterialTestBase {", " @Override\n protected P4TestRepo createTestRepo() throws Exception {\n P4TestRepo repo = P4TestRepo.createP4TestRepo(temporaryFolder, clientFolder);\n repo.onSetup();\n return repo;\n }", " @Test\n void shouldAddServerSideEnvironmentVariablesClientNameEnvironmentVariable() throws IOException {\n File p4_working_dir = temporaryFolder.newFolder();", " P4Material p4 = new P4Material(\"host:10\", \"beautiful\", \"user\");\n p4.setPassword(\"loser\");\n EnvironmentVariableContext envVarCtx;", " envVarCtx = new EnvironmentVariableContext();\n p4.populateEnvironmentContext(envVarCtx, new MaterialRevision(p4, new Modification(\"loser\", \"loserish commit\", \"loser@boozer.com\", new Date(), \"123\")), p4_working_dir);\n assertThat(envVarCtx.getProperty(\"GO_REVISION\")).isEqualTo(\"123\");\n assertThat(envVarCtx.getProperty(\"GO_TO_REVISION\")).isEqualTo(\"123\");\n assertThat(envVarCtx.getProperty(\"GO_FROM_REVISION\")).isEqualTo(\"123\");\n }", " @Test\n void shouldAddClientNameEnvironmentVariable() throws IOException {\n File p4_working_dir = temporaryFolder.newFolder();", " P4Material p4 = new P4Material(\"host:10\", \"beautiful\", \"user\");\n p4.setPassword(\"loser\");\n EnvironmentVariableContext envVarCtx;", " envVarCtx = new EnvironmentVariableContext();\n p4.populateAgentSideEnvironmentContext(envVarCtx, p4_working_dir);\n assertThat(envVarCtx.getProperty(\"GO_P4_CLIENT\")).isEqualTo(p4.clientName(p4_working_dir));\n }", " @Test\n void shouldGenerateTheSameP4ClientValueForCommandAndEnvironment() throws Exception {", " P4Material p4Material = new P4Material(\"server:10\", \"out-of-the-window\");\n ReflectionUtil.setField(p4Material, \"folder\", \"crapy_dir\");", " P4Client p4Client = p4Material._p4(tempDir, new InMemoryStreamConsumer(), false);", " assertThat(p4Client).isNotNull();\n String client = (String) ReflectionUtil.getField(p4Client, \"p4ClientName\");\n assertThat(client).isEqualTo(p4Material.clientName(tempDir));\n }", " @Test\n void shouldNotDisplayPasswordInStringRepresentation() {\n P4Material p4 = new P4Material(\"host:10\", \"beautiful\");\n p4.setUsername(\"user\");\n p4.setPassword(\"loser\");\n assertThat(p4.toString()).doesNotContain(\"loser\");\n }", " @Test", "", " void shouldReturnEqualsEvenIfPasswordsAreDifferent() throws Exception {\n P4Material material = MaterialsMother.p4Material();\n material.setPassword(\"password\");", " P4Material other = MaterialsMother.p4Material();\n other.setPassword(\"password1\");\n assertThat(material).isEqualTo(other);\n }", " @Test\n void shouldNotConsiderPasswordForEqualityCheck() {\n P4Material one = new P4Material(\"host:123\", \"through_window\");\n one.setPassword(\"password\");\n P4Material two = new P4Material(\"host:123\", \"through_window\");\n two.setPassword(\"wordpass\");", " assertThat(one).isEqualTo(two);\n assertThat(one.hashCode()).isEqualTo(two.hashCode());\n }", " @Test\n void shouldGetLongDescriptionForMaterial() {\n P4Material material = new P4Material(\"host:123\", \"through_window\", \"user\", \"folder\");\n assertThat(material.getLongDescription()).isEqualTo(\"URL: host:123, View: through_window, Username: user\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() throws Exception {\n P4Material material = new P4Material(\"blah.com\", \"view\");\n material.setPassword(\"password\");", " P4MaterialConfig config = (P4MaterialConfig) material.config();", " assertThat(config.getPassword()).isEqualTo(\"password\");\n assertThat(config.getEncryptedPassword()).isNotNull();\n }", " @Test\n void shouldGetAttributesWithSecureFields() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\");\n material.setPassword(\"password\");\n material.setUseTickets(true);\n Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"perforce\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"perforce-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"host:1234\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"view\")).isEqualTo(\"view\");\n assertThat(configuration.get(\"use-tickets\")).isEqualTo(true);\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\");\n material.setPassword(\"password\");\n material.setUseTickets(true);\n Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"perforce\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"perforce-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"host:1234\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"view\")).isEqualTo(\"view\");\n assertThat(configuration.get(\"use-tickets\")).isEqualTo(true);\n }", " @Test\n void shouldSetGO_P4_CLIENT_toTheClientName() {\n P4Material material = new P4Material(\"host:1234\", \"view\", \"username\", \"destination\");\n EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext();\n File agentWorkingDirectory = new File(\"pipelines/pipeline-name\");\n material.populateAgentSideEnvironmentContext(environmentVariableContext, agentWorkingDirectory);\n assertThat(environmentVariableContext.getProperty(\"GO_P4_CLIENT_DESTINATION\")).isEqualTo(material.clientName(material.workingdir(agentWorkingDirectory)));\n }", " @Nested\n class hasSecretParams {\n @Test\n void shouldBeTrueIfMaterialUrlHasSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_password]}}\");", " assertThat(p4Material.hasSecretParams()).isTrue();\n }", " @Test\n void shouldBeFalseInMaterialUrlDoesNotHaveSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"foo\");", " assertThat(p4Material.hasSecretParams()).isFalse();\n }\n }", " @Nested\n class getSecretParams {\n @Test\n void shouldReturnAListOfSecretParams() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_password]}}\");", " assertThat(p4Material.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_password\"));\n }", " @Test\n void shouldBeAnEmptyListInAbsenceOfSecretParamsinMaterialUrl() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"pass\");", " assertThat(p4Material.getSecretParams())\n .hasSize(0);\n }\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"badger\");", " assertThat(p4Material.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " p4Material.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(p4Material.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " assertThatCode(p4Material::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {\n P4Material p4Material = new P4Material(\"host:10\", \"beautiful\");\n p4Material.setPassword(\"{{SECRET:[secret_config_id][lookup_pass]}}\");", " assertThat(p4Material.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.tfs;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.config.materials.AbstractMaterial;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.Modification;\nimport com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;\nimport com.thoughtworks.go.domain.materials.mercurial.StringRevision;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommand;\nimport com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.Rule;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;\nimport org.junit.rules.TemporaryFolder;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "import static com.thoughtworks.go.config.materials.AbstractMaterial.SQL_CRITERIA_TYPE;\nimport static com.thoughtworks.go.domain.materials.ValidationBean.valid;\nimport static com.thoughtworks.go.util.DataStructureUtils.m;\nimport static org.assertj.core.api.Assertions.*;\nimport static org.mockito.Mockito.*;", "@EnableRuleMigrationSupport\npublic class TfsMaterialTest {\n @Rule\n public final TemporaryFolder temporaryFolder = new TemporaryFolder();", " private TfsMaterial tfsMaterialFirstCollectionFirstProject;\n private TfsMaterial tfsMaterialFirstCollectionSecondProject;\n private final String DOMAIN = \"domain\";\n private final String USERNAME = \"username\";\n private final String PASSWORD = \"password\";\n private final String TFS_FIRST_COLLECTION_URL = \"http://some.tfs.repo.local\";\n private final String TFS_FIRST_PROJECT = \"$/first_project\";\n private final String TFS_SECOND_PROJECT = \"$/second_project\";", " @BeforeEach\n void setUp() {\n GoCipher goCipher = mock(GoCipher.class);", " tfsMaterialFirstCollectionFirstProject = new TfsMaterial(goCipher, new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, DOMAIN, PASSWORD, TFS_FIRST_PROJECT);\n tfsMaterialFirstCollectionSecondProject = new TfsMaterial(goCipher, new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, DOMAIN, PASSWORD, TFS_SECOND_PROJECT);", " }", " @Test\n void shouldShowLatestModification() throws IOException {\n File dir = temporaryFolder.newFolder(\"tfs-dir\");\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionSecondProject);\n TfsCommand tfsCommand = mock(TfsCommand.class);\n when(tfsCommand.latestModification(dir)).thenReturn(new ArrayList<>());\n doReturn(tfsCommand).when(spy).tfs(execCtx);", " List<Modification> actual = spy.latestModification(dir, execCtx);", " assertThat(actual).isEqualTo(new ArrayList<Modification>());\n verify(tfsCommand).latestModification(dir);\n }", " @Test\n void shouldLoadAllModificationsSinceAGivenRevision() throws IOException {\n File dir = temporaryFolder.newFolder(\"tfs-dir\");\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionFirstProject);\n TfsCommand tfsCommand = mock(TfsCommand.class);\n when(tfsCommand.modificationsSince(dir, new StringRevision(\"5\"))).thenReturn(new ArrayList<>());\n doReturn(tfsCommand).when(spy).tfs(execCtx);", " List<Modification> actual = spy.modificationsSince(dir, new StringRevision(\"5\"), execCtx);", " assertThat(actual).isEqualTo(new ArrayList<Modification>());\n verify(tfsCommand).modificationsSince(dir, new StringRevision(\"5\"));\n }", " @Test\n void shouldInjectAllRelevantAttributesInSqlCriteriaMap() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"my-url\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getSqlCriteria()).isEqualTo(m(\n SQL_CRITERIA_TYPE, (Object) \"TfsMaterial\",\n \"url\", \"my-url\",\n \"username\", \"loser\",\n \"projectPath\", \"/dev/null\", \"domain\", DOMAIN));\n }", " @Test\n void shouldInjectAllRelevantAttributesInAttributeMap() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"my-url\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getAttributesForXml()).isEqualTo(m(\n AbstractMaterial.SQL_CRITERIA_TYPE, (Object) \"TfsMaterial\",\n \"url\", \"my-url\",\n \"username\", \"loser\",\n \"projectPath\", \"/dev/null\", \"domain\", DOMAIN));\n }", " @Test\n void shouldReturnUrlForCommandLine_asUrl_IfSet() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://foo:bar@my-url.com\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\"", " );\n assertThat(tfsMaterial.getUrl()).isEqualTo(\"http://foo:bar@my-url.com\");\n", " tfsMaterial = new TfsMaterial(new GoCipher(), null, \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getUrl()).isNull();\n }", " @Test\n void shouldReturnUrlForCommandLine_asLocation_IfSet() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://foo:bar@my-url.com\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\"", " );\n assertThat(tfsMaterial.getLocation()).isEqualTo(\"http://foo:******@my-url.com\");\n", " tfsMaterial = new TfsMaterial(new GoCipher(), null, \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getLocation()).isNull();", " }", " @Test\n void shouldEncryptTfsPasswordAndMarkPasswordAsNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");", " TfsMaterial tfsMaterial = new TfsMaterial(mockGoCipher, new UrlArgument(\"/foo\"), \"username\", DOMAIN, \"password\", \"\");\n tfsMaterial.ensureEncrypted();", " assertThat(tfsMaterial.getPassword()).isNull();\n assertThat(tfsMaterial.getEncryptedPassword()).isEqualTo(\"encrypted\");\n }", " @Test\n void shouldDecryptTfsPassword() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");", " TfsMaterial tfsMaterial = new TfsMaterial(mockGoCipher, new UrlArgument(\"/foo\"), \"username\", DOMAIN, null, \"\");", " ReflectionUtil.setField(tfsMaterial, \"encryptedPassword\", \"encrypted\");", " tfsMaterial.ensureEncrypted();\n assertThat(tfsMaterial.getPassword()).isEqualTo(\"password\");", " }", " @Test\n void shouldNotDecryptPasswordIfPasswordIsNotNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");\n", " TfsMaterial material = new TfsMaterial(mockGoCipher, new UrlArgument(\"/foo\"), \"username\", DOMAIN, \"password\", \"\");", " material.ensureEncrypted();\n when(mockGoCipher.encrypt(\"new_password\")).thenReturn(\"new_encrypted\");\n material.setPassword(\"new_password\");\n when(mockGoCipher.decrypt(\"new_encrypted\")).thenReturn(\"new_password\");", " assertThat(material.getPassword()).isEqualTo(\"new_password\");", " }", " @Test\n void shouldErrorOutIfDecryptionFails() throws CryptoException {\n GoCipher mockGoCipher = mock(GoCipher.class);\n String fakeCipherText = \"fake cipher text\";\n when(mockGoCipher.decrypt(fakeCipherText)).thenThrow(new CryptoException(\"exception\"));\n TfsMaterial material = new TfsMaterial(mockGoCipher, new UrlArgument(\"/foo\"), \"username\", DOMAIN, \"password\", \"\");\n ReflectionUtil.setField(material, \"encryptedPassword\", fakeCipherText);\n try {\n material.getPassword();\n fail(\"Should have thrown up\");\n } catch (Exception e) {\n assertThat(e.getMessage()).isEqualTo(\"Could not decrypt the password to get the real password\");\n }\n }", " @Test\n void shouldErrorOutIfEncryptionFails() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenThrow(new CryptoException(\"exception\"));\n try {\n new TfsMaterial(mockGoCipher, new UrlArgument(\"/foo\"), \"username\", DOMAIN, \"password\", \"\");\n fail(\"Should have thrown up\");\n } catch (Exception e) {\n assertThat(e.getMessage()).isEqualTo(\"Password encryption failed. Please verify your cipher key.\");\n }", " }", " @Test\n void shouldBePasswordAware() {\n assertThat(PasswordAwareMaterial.class.isAssignableFrom(TfsMaterial.class)).isTrue();\n }", " @Test\n void shouldBePasswordEncrypter() {\n assertThat(PasswordEncrypter.class.isAssignableFrom(TfsMaterial.class)).isTrue();\n }", " @Test\n void shouldKnowItsType() {\n assertThat(tfsMaterialFirstCollectionFirstProject.getTypeForDisplay()).isEqualTo(\"Tfs\");\n }", " @Test\n void shouldCheckConnection() {\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsCommand tfsCommand = mock(TfsCommand.class);\n doNothing().when(tfsCommand).checkConnection();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionFirstProject);\n doReturn(tfsCommand).when(spy).tfs(execCtx);\n assertThat(spy.checkConnection(execCtx)).isEqualTo(valid());\n verify(tfsCommand, times(1)).checkConnection();\n }", " @Test\n void shouldGetLongDescriptionForMaterial() {", " TfsMaterial material = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://url/\"), \"user\", \"domain\", \"password\", \"$project/path/\");", " assertThat(material.getLongDescription()).isEqualTo(\"URL: http://url/, Username: user, Domain: domain, ProjectPath: $project/path/\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() throws Exception {", " TfsMaterial material = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://url/\"), \"user\", \"domain\", \"password\", \"$project/path/\");", "\n TfsMaterialConfig config = (TfsMaterialConfig) material.config();", " assertThat(config.getPassword()).isEqualTo(\"password\");\n assertThat(config.getEncryptedPassword()).isNotNull();\n }", " @Test\n void shouldGetAttributesWithSecureFields() {", " TfsMaterial material = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://username:password@tfsrepo.com\"), \"username\", \"domain\", \"password\", \"$project/path/\");", " Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"tfs\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"tfs-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:password@tfsrepo.com\");\n assertThat(configuration.get(\"domain\")).isEqualTo(\"domain\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"project-path\")).isEqualTo(\"$project/path/\");\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {", " TfsMaterial material = new TfsMaterial(new GoCipher(), new UrlArgument(\"http://username:password@tfsrepo.com\"), \"username\", \"domain\", \"password\", \"$project/path/\");", " Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"tfs\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"tfs-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:******@tfsrepo.com\");\n assertThat(configuration.get(\"domain\")).isEqualTo(\"domain\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"project-path\")).isEqualTo(\"$project/path/\");\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"some-url\"), null, null, \"badger\", null);", "\n assertThat(tfsMaterial.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n tfsMaterial.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(tfsMaterial.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n assertThatCode(tfsMaterial::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n assertThat(tfsMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }", " @Test\n void populateEnvContextShouldSetMaterialEnvVars() {\n EnvironmentVariableContext ctx = new EnvironmentVariableContext();\n final ArrayList<Modification> modifications = new ArrayList<>();", " modifications.add(new Modification(\"user2\", \"comment2\", \"email2\", new Date(), \"24\"));\n modifications.add(new Modification(\"user1\", \"comment1\", \"email1\", new Date(), \"23\"));", " MaterialRevision materialRevision = new MaterialRevision(tfsMaterialFirstCollectionFirstProject, modifications);\n assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL)).isNull();\n assertThat(ctx.getProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isNull();", " tfsMaterialFirstCollectionFirstProject.populateEnvironmentContext(ctx, materialRevision, new File(\".\"));", " assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL)).isEqualTo(TFS_FIRST_COLLECTION_URL);\n assertThat(ctx.getProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isEqualTo(DOMAIN);\n }", " @Test\n void shouldOnlyPopulateDomainEnvVarIfPresent() {", " TfsMaterial material = new TfsMaterial(mock(GoCipher.class), new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, \"\", PASSWORD, TFS_FIRST_PROJECT);", " EnvironmentVariableContext ctx = new EnvironmentVariableContext();\n final ArrayList<Modification> modifications = new ArrayList<>();", " modifications.add(new Modification(\"user2\", \"comment2\", \"email2\", new Date(), \"24\"));\n modifications.add(new Modification(\"user1\", \"comment1\", \"email1\", new Date(), \"23\"));", " MaterialRevision materialRevision = new MaterialRevision(material, modifications);\n material.populateEnvironmentContext(ctx, materialRevision, new File(\".\"));", " assertThat(ctx.hasProperty(ScmMaterial.GO_MATERIAL_URL)).isTrue();\n assertThat(ctx.hasProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isFalse();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.tfs;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.config.materials.AbstractMaterial;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.Modification;\nimport com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;\nimport com.thoughtworks.go.domain.materials.mercurial.StringRevision;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommand;\nimport com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.Rule;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;\nimport org.junit.rules.TemporaryFolder;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "import static com.thoughtworks.go.config.materials.AbstractMaterial.SQL_CRITERIA_TYPE;\nimport static com.thoughtworks.go.domain.materials.ValidationBean.valid;\nimport static com.thoughtworks.go.util.DataStructureUtils.m;\nimport static org.assertj.core.api.Assertions.*;\nimport static org.mockito.Mockito.*;", "@EnableRuleMigrationSupport\npublic class TfsMaterialTest {\n @Rule\n public final TemporaryFolder temporaryFolder = new TemporaryFolder();", " private TfsMaterial tfsMaterialFirstCollectionFirstProject;\n private TfsMaterial tfsMaterialFirstCollectionSecondProject;\n private final String DOMAIN = \"domain\";\n private final String USERNAME = \"username\";\n private final String PASSWORD = \"password\";\n private final String TFS_FIRST_COLLECTION_URL = \"http://some.tfs.repo.local\";\n private final String TFS_FIRST_PROJECT = \"$/first_project\";\n private final String TFS_SECOND_PROJECT = \"$/second_project\";", " @BeforeEach\n void setUp() {\n GoCipher goCipher = mock(GoCipher.class);", " tfsMaterialFirstCollectionFirstProject = new TfsMaterial(new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, DOMAIN, PASSWORD, TFS_FIRST_PROJECT);\n tfsMaterialFirstCollectionSecondProject = new TfsMaterial(new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, DOMAIN, PASSWORD, TFS_SECOND_PROJECT);", " }", " @Test\n void shouldShowLatestModification() throws IOException {\n File dir = temporaryFolder.newFolder(\"tfs-dir\");\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionSecondProject);\n TfsCommand tfsCommand = mock(TfsCommand.class);\n when(tfsCommand.latestModification(dir)).thenReturn(new ArrayList<>());\n doReturn(tfsCommand).when(spy).tfs(execCtx);", " List<Modification> actual = spy.latestModification(dir, execCtx);", " assertThat(actual).isEqualTo(new ArrayList<Modification>());\n verify(tfsCommand).latestModification(dir);\n }", " @Test\n void shouldLoadAllModificationsSinceAGivenRevision() throws IOException {\n File dir = temporaryFolder.newFolder(\"tfs-dir\");\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionFirstProject);\n TfsCommand tfsCommand = mock(TfsCommand.class);\n when(tfsCommand.modificationsSince(dir, new StringRevision(\"5\"))).thenReturn(new ArrayList<>());\n doReturn(tfsCommand).when(spy).tfs(execCtx);", " List<Modification> actual = spy.modificationsSince(dir, new StringRevision(\"5\"), execCtx);", " assertThat(actual).isEqualTo(new ArrayList<Modification>());\n verify(tfsCommand).modificationsSince(dir, new StringRevision(\"5\"));\n }", " @Test\n void shouldInjectAllRelevantAttributesInSqlCriteriaMap() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"my-url\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getSqlCriteria()).isEqualTo(m(\n SQL_CRITERIA_TYPE, (Object) \"TfsMaterial\",\n \"url\", \"my-url\",\n \"username\", \"loser\",\n \"projectPath\", \"/dev/null\", \"domain\", DOMAIN));\n }", " @Test\n void shouldInjectAllRelevantAttributesInAttributeMap() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"my-url\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getAttributesForXml()).isEqualTo(m(\n AbstractMaterial.SQL_CRITERIA_TYPE, (Object) \"TfsMaterial\",\n \"url\", \"my-url\",\n \"username\", \"loser\",\n \"projectPath\", \"/dev/null\", \"domain\", DOMAIN));\n }", " @Test\n void shouldReturnUrlForCommandLine_asUrl_IfSet() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"http://foo:bar@my-url.com\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\"", " );\n assertThat(tfsMaterial.getUrl()).isEqualTo(\"http://foo:bar@my-url.com\");\n", " tfsMaterial = new TfsMaterial(null, \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getUrl()).isNull();\n }", " @Test\n void shouldReturnUrlForCommandLine_asLocation_IfSet() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"http://foo:bar@my-url.com\"), \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\"", " );\n assertThat(tfsMaterial.getLocation()).isEqualTo(\"http://foo:******@my-url.com\");\n", " tfsMaterial = new TfsMaterial(null, \"loser\", DOMAIN, \"foo_bar_baz\", \"/dev/null\");", " assertThat(tfsMaterial.getLocation()).isNull();", "", " }", " @Test\n void shouldNotDecryptPasswordIfPasswordIsNotNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");\n", " TfsMaterial material = new TfsMaterial(new UrlArgument(\"/foo\"), \"username\", DOMAIN, \"password\", \"\");", " material.ensureEncrypted();\n when(mockGoCipher.encrypt(\"new_password\")).thenReturn(\"new_encrypted\");\n material.setPassword(\"new_password\");\n when(mockGoCipher.decrypt(\"new_encrypted\")).thenReturn(\"new_password\");", " assertThat(material.getPassword()).isEqualTo(\"new_password\");", "", " }", " @Test\n void shouldBePasswordAware() {\n assertThat(PasswordAwareMaterial.class.isAssignableFrom(TfsMaterial.class)).isTrue();\n }", " @Test\n void shouldBePasswordEncrypter() {\n assertThat(PasswordEncrypter.class.isAssignableFrom(TfsMaterial.class)).isTrue();\n }", " @Test\n void shouldKnowItsType() {\n assertThat(tfsMaterialFirstCollectionFirstProject.getTypeForDisplay()).isEqualTo(\"Tfs\");\n }", " @Test\n void shouldCheckConnection() {\n TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();\n TfsCommand tfsCommand = mock(TfsCommand.class);\n doNothing().when(tfsCommand).checkConnection();\n TfsMaterial spy = spy(tfsMaterialFirstCollectionFirstProject);\n doReturn(tfsCommand).when(spy).tfs(execCtx);\n assertThat(spy.checkConnection(execCtx)).isEqualTo(valid());\n verify(tfsCommand, times(1)).checkConnection();\n }", " @Test\n void shouldGetLongDescriptionForMaterial() {", " TfsMaterial material = new TfsMaterial(new UrlArgument(\"http://url/\"), \"user\", \"domain\", \"password\", \"$project/path/\");", " assertThat(material.getLongDescription()).isEqualTo(\"URL: http://url/, Username: user, Domain: domain, ProjectPath: $project/path/\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() throws Exception {", " TfsMaterial material = new TfsMaterial(new UrlArgument(\"http://url/\"), \"user\", \"domain\", \"password\", \"$project/path/\");", "\n TfsMaterialConfig config = (TfsMaterialConfig) material.config();", " assertThat(config.getPassword()).isEqualTo(\"password\");\n assertThat(config.getEncryptedPassword()).isNotNull();\n }", " @Test\n void shouldGetAttributesWithSecureFields() {", " TfsMaterial material = new TfsMaterial(new UrlArgument(\"http://username:password@tfsrepo.com\"), \"username\", \"domain\", \"password\", \"$project/path/\");", " Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"tfs\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"tfs-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:password@tfsrepo.com\");\n assertThat(configuration.get(\"domain\")).isEqualTo(\"domain\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"project-path\")).isEqualTo(\"$project/path/\");\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {", " TfsMaterial material = new TfsMaterial(new UrlArgument(\"http://username:password@tfsrepo.com\"), \"username\", \"domain\", \"password\", \"$project/path/\");", " Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"tfs\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"tfs-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:******@tfsrepo.com\");\n assertThat(configuration.get(\"domain\")).isEqualTo(\"domain\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"username\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"project-path\")).isEqualTo(\"$project/path/\");\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"some-url\"), null, null, \"badger\", null);", "\n assertThat(tfsMaterial.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n tfsMaterial.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(tfsMaterial.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n assertThatCode(tfsMaterial::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(\"some-url\"), null, null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", null);", "\n assertThat(tfsMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }", " @Test\n void populateEnvContextShouldSetMaterialEnvVars() {\n EnvironmentVariableContext ctx = new EnvironmentVariableContext();\n final ArrayList<Modification> modifications = new ArrayList<>();", " modifications.add(new Modification(\"user2\", \"comment2\", \"email2\", new Date(), \"24\"));\n modifications.add(new Modification(\"user1\", \"comment1\", \"email1\", new Date(), \"23\"));", " MaterialRevision materialRevision = new MaterialRevision(tfsMaterialFirstCollectionFirstProject, modifications);\n assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL)).isNull();\n assertThat(ctx.getProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isNull();", " tfsMaterialFirstCollectionFirstProject.populateEnvironmentContext(ctx, materialRevision, new File(\".\"));", " assertThat(ctx.getProperty(ScmMaterial.GO_MATERIAL_URL)).isEqualTo(TFS_FIRST_COLLECTION_URL);\n assertThat(ctx.getProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isEqualTo(DOMAIN);\n }", " @Test\n void shouldOnlyPopulateDomainEnvVarIfPresent() {", " TfsMaterial material = new TfsMaterial(new UrlArgument(TFS_FIRST_COLLECTION_URL), USERNAME, \"\", PASSWORD, TFS_FIRST_PROJECT);", " EnvironmentVariableContext ctx = new EnvironmentVariableContext();\n final ArrayList<Modification> modifications = new ArrayList<>();", " modifications.add(new Modification(\"user2\", \"comment2\", \"email2\", new Date(), \"24\"));\n modifications.add(new Modification(\"user1\", \"comment1\", \"email1\", new Date(), \"23\"));", " MaterialRevision materialRevision = new MaterialRevision(material, modifications);\n material.populateEnvironmentContext(ctx, materialRevision, new File(\".\"));", " assertThat(ctx.hasProperty(ScmMaterial.GO_MATERIAL_URL)).isTrue();\n assertThat(ctx.hasProperty(TfsMaterial.GO_MATERIAL_DOMAIN)).isFalse();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials;", "import com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;", "import java.io.File;\nimport java.util.List;\nimport java.util.Map;", "/**\n * ChrisS and ChrisT :\n * Note iBatis requires a concrete class here for the XSD but it does not actually use it.\n * Dummy material is just used to help iBatis and should not be used in real code.\n */\npublic final class DummyMaterial extends ScmMaterial {\n private String url;", " public DummyMaterial() {", " super(\"DummyMaterial\", new GoCipher());", " }", " @Override\n public String getUrl() {\n return url;\n }", " @Override\n public String urlForCommandLine() {\n return url;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(url);\n }", " @Override\n public String getLongDescription() {\n return \"Dummy\";\n }", " public void setUrl(String url) {\n this.url = url;\n }", " @Override\n protected String getLocation() {\n return getUrl();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Dummy\";\n }", " @Override\n public Class getInstanceType() {\n throw new UnsupportedOperationException(\"dummy material doens't have a type\");\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n throw new UnsupportedOperationException();\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public void checkout(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public boolean isCheckExternals() {\n throw unsupported();\n }", " private UnsupportedOperationException unsupported() {\n return new UnsupportedOperationException(\"This class is only for iBatis and should not be used.\");\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n throw unsupported();\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n throw unsupported();\n }", "}" ]
[ 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials;", "import com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;", "", "import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;", "import java.io.File;\nimport java.util.List;\nimport java.util.Map;", "/**\n * ChrisS and ChrisT :\n * Note iBatis requires a concrete class here for the XSD but it does not actually use it.\n * Dummy material is just used to help iBatis and should not be used in real code.\n */\npublic final class DummyMaterial extends ScmMaterial {\n private String url;", " public DummyMaterial() {", " super(\"DummyMaterial\");", " }", " @Override\n public String getUrl() {\n return url;\n }", " @Override\n public String urlForCommandLine() {\n return url;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(url);\n }", " @Override\n public String getLongDescription() {\n return \"Dummy\";\n }", " public void setUrl(String url) {\n this.url = url;\n }", " @Override\n protected String getLocation() {\n return getUrl();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Dummy\";\n }", " @Override\n public Class getInstanceType() {\n throw new UnsupportedOperationException(\"dummy material doens't have a type\");\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n throw new UnsupportedOperationException();\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public void checkout(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n throw unsupported();\n }", " @Override\n public boolean isCheckExternals() {\n throw unsupported();\n }", " private UnsupportedOperationException unsupported() {\n return new UnsupportedOperationException(\"This class is only for iBatis and should not be used.\");\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n throw unsupported();\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n throw unsupported();\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.svn;", "import com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.materials.RevisionContext;\nimport com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;\nimport com.thoughtworks.go.helper.MaterialConfigsMother;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.JsonValue;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.codec.digest.DigestUtils;\nimport org.junit.Rule;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;\nimport org.junit.rules.TemporaryFolder;", "import java.io.*;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.Map;", "import static com.thoughtworks.go.util.JsonUtils.from;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static org.assertj.core.api.Assertions.*;\nimport static org.mockito.Mockito.*;", "@EnableRuleMigrationSupport\npublic class SvnMaterialTest {\n @Rule\n public final TemporaryFolder temporaryFolder = new TemporaryFolder();", " private Subversion subversion;", " private SvnMaterial svnMaterial;\n private static final String URL = \"svn://something\";\n private SubversionRevision revision = new SubversionRevision(\"1\");\n private InMemoryStreamConsumer outputStreamConsumer = inMemoryConsumer();", " @BeforeEach\n void setUp() throws IOException {\n temporaryFolder.create();\n subversion = mock(Subversion.class);", " when(subversion.getUrl()).thenReturn(new UrlArgument(URL));\n when(subversion.getPassword()).thenReturn(\"\");\n when(subversion.getUserName()).thenReturn(\"\");\n when(subversion.isCheckExternals()).thenReturn(false);", " svnMaterial = SvnMaterial.createSvnMaterialWithMock(subversion);\n svnMaterial.setUrl(URL);\n }", " @AfterEach\n void tearDown() {\n temporaryFolder.delete();\n }", " private File createSvnWorkingCopy(boolean withDotSvnFolder) throws IOException {\n File folder = temporaryFolder.newFolder(\"testSvnWorkingCopy\");\n if (withDotSvnFolder) {\n File dotSvnFolder = new File(folder, \".svn\");\n dotSvnFolder.mkdir();\n }\n return folder;\n }", " @Test\n void shouldNotDisplayPasswordInStringRepresentation() {\n SvnMaterial svn = new SvnMaterial(\"my-url\", \"user\", \"loser\", false);\n assertThat(svn.toString()).doesNotContain(\"loser\");", " svn = new SvnMaterial(\"https://user:loser@foo.bar/baz?quux=bang\", \"user\", \"loser\", false);\n assertThat(svn.toString()).doesNotContain(\"loser\");\n }", " @Test\n void shouldCheckoutWhenFolderDoesNotExist() {\n final File workingCopy = new File(\"xyz\");", " updateMaterial(svnMaterial, revision, workingCopy);", " verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldLogRepoInfoToConsoleOutWithOutFolder() throws Exception {\n final File workingCopy = new File(\"xyz\");", " updateMaterial(svnMaterial, revision, workingCopy);\n String stdout = outputStreamConsumer.getStdOut();\n assertThat(stdout).contains(String.format(\"Start updating %s at revision %s from %s\", \"files\", revision.getRevision(),\n svnMaterial.getUrl()));", " verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldCheckoutForInvalidSvnWorkingCopy() throws IOException {\n final File workingCopy = createSvnWorkingCopy(false);", " updateMaterial(svnMaterial, revision, workingCopy);", " assertThat(workingCopy.exists()).isFalse();\n verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " private void updateMaterial(SvnMaterial svnMaterial, SubversionRevision revision, File workingCopy) {\n svnMaterial.updateTo(outputStreamConsumer, workingCopy, new RevisionContext(revision), new TestSubprocessExecutionContext());\n }", " @Test\n void shouldCheckoutIfSvnRepositoryChanged() throws IOException {\n final File workingCopy = createSvnWorkingCopy(true);", " when(subversion.workingRepositoryUrl(workingCopy)).thenReturn(\"new url\");", " updateMaterial(svnMaterial, revision, workingCopy);\n assertThat(workingCopy.exists()).isFalse();\n verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldUpdateForValidSvnWorkingCopy() throws IOException {\n final File workingCopy = createSvnWorkingCopy(true);", " when(subversion.workingRepositoryUrl(workingCopy)).thenReturn(URL);", " updateMaterial(svnMaterial, revision, workingCopy);", " verify(subversion).cleanupAndRevert(outputStreamConsumer, workingCopy);\n verify(subversion).updateTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldBeEqualWhenUrlSameForSvnMaterial() {\n final Material material1 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n final Material material = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n assertComplementaryEquals(material1, material, true);", " }", " @Test\n void shouldNotBeEqualWhenUrlDifferent() {\n final Material material1 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n final Material material2 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url2\").get(0);\n assertComplementaryEquals(material1, material2, false);\n }", " @Test\n void shouldNotBeEqualWhenTypeDifferent() {\n final Material hgMaterial = MaterialsMother.hgMaterials(\"url1\", \"hgdir\").get(0);\n final Material nonHgMaterial = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n assertComplementaryEquals(hgMaterial, nonHgMaterial, false);\n }", " @Test\n void shouldNotBeEqualWhenAlternateFolderDifferent() {\n final SvnMaterial material1 = MaterialsMother.svnMaterial(\"url1\");\n final SvnMaterial material2 = MaterialsMother.svnMaterial(\"url1\");", " assertComplementaryEquals(material1, material2, true);", " material1.setFolder(\"foo\");\n material2.setFolder(null);\n assertComplementaryEquals(material1, material2, false);", " material1.setFolder(\"foo\");\n material2.setFolder(\"bar\");\n assertComplementaryEquals(material1, material2, false);\n }", " @Test\n void shouldSerializeAndDeserializeCorrectly() throws Exception {\n final SvnMaterial material1 = MaterialsMother.svnMaterial(\"url1\", \"foo\");\n ByteArrayOutputStream buf = new ByteArrayOutputStream();\n ObjectOutputStream serialized = new ObjectOutputStream(buf);\n serialized.writeObject(material1);\n ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));\n assertThat(in.readObject()).isEqualTo(material1);\n }", " @Test\n void shouldReturnNotEqualsWhenUrlIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"A\");", " SvnMaterial other = MaterialsMother.svnMaterial(\"B\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnNotEqualsWhenUserNameIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\", \"svnDir\", \"userName\", null, false, \"*.txt\");", " SvnMaterial other = MaterialsMother.svnMaterial(\"url\", \"svnDir\", \"userName1\", null, false, \"*.txt\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnEqualsEvenIfPasswordsAreDifferent() {\n SvnMaterial material = MaterialsMother.svnMaterial();\n material.setPassword(\"password\");", " SvnMaterial other = MaterialsMother.svnMaterial();\n other.setPassword(\"password1\");\n assertThat(material).isEqualTo(other);\n }", " @Test\n void shouldReturnNotEqualsWhenCheckExternalsIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\", \"svnDir\", null, null, true, \"*.txt\");\n SvnMaterial other = MaterialsMother.svnMaterial(\"url\", \"svnDir\", null, null, false, \"*.txt\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnEqualsWhenEverythingIsSame() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"URL\", \"dummy-folder\", \"userName\", \"password\", true, \"*.doc\");\n SvnMaterial other = MaterialsMother.svnMaterial(\"URL\", \"dummy-folder\", \"userName\", \"password\", true, \"*.doc\");", " assertThat(other).isEqualTo(material);\n }", " /* TODO: *SBD* Move this test into SvnMaterialConfig test after mothers are moved. */\n @Test\n void shouldReturnEqualsWhenEverythingIsSameForSvnMaterialConfigs() {\n SvnMaterialConfig svnMaterialConfig = MaterialConfigsMother.svnMaterialConfig();\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.CHECK_EXTERNALS, String.valueOf(true)));\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.USERNAME, \"userName\"));\n svnMaterialConfig.setPassword(\"password\");\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.URL, \"URL\"));", "\n SvnMaterialConfig other = MaterialConfigsMother.svnMaterialConfig();\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.CHECK_EXTERNALS, String.valueOf(true)));\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.USERNAME, \"userName\"));\n other.setPassword(\"password\");\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.URL, \"URL\"));", " assertThat(other).isEqualTo(svnMaterialConfig);\n }", " @Test\n void shouldBeAbleToConvertToJson() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\");\n Map<String, Object> json = new LinkedHashMap<>();\n material.toJson(json, revision);", " JsonValue jsonValue = from(json);\n assertThat(jsonValue.getString(\"scmType\")).isEqualTo(\"Subversion\");\n assertThat(new File(jsonValue.getString(\"location\"))).isEqualTo(new File(material.getUrl()));\n assertThat(jsonValue.getString(\"action\")).isEqualTo(\"Modified\");\n }", " @Test\n void shouldAddTheForwardSlashAndApplyThePattern() {\n SvnMaterial material = MaterialsMother.svnMaterial();", " assertThat(material.matches(\"/a.doc\", \"a.doc\")).isTrue();\n assertThat(material.matches(\"a.doc\", \"a.doc\")).isFalse();\n }", " @Test\n void shouldApplyThePatternDirectly() {\n SvnMaterial material = MaterialsMother.svnMaterial();", " assertThat(material.matches(\"/a.doc\", \"/a.doc\")).isTrue();\n }", " @Test\n void shouldGenerateSqlCriteriaMapInSpecificOrder() {\n SvnMaterial material = new SvnMaterial(\"url\", \"username\", \"password\", true);\n Map<String, Object> map = material.getSqlCriteria();\n assertThat(map.size()).isEqualTo(4);\n Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();\n assertThat(iter.next().getKey()).isEqualTo(\"type\");\n assertThat(iter.next().getKey()).isEqualTo(\"url\");\n assertThat(iter.next().getKey()).isEqualTo(\"username\");\n assertThat(iter.next().getKey()).isEqualTo(\"checkExternals\");\n }", " @Test\n void shouldGenerateFingerprintBasedOnSqlCriteria() {\n SvnMaterial one = new SvnMaterial(\"url\", \"username\", \"password\", true);\n SvnMaterial two = new SvnMaterial(\"url\", \"username\", \"password\", false);\n assertThat(one.getFingerprint()).isNotEqualTo(two.getFingerprint());\n assertThat(one.getFingerprint()).isEqualTo(DigestUtils.sha256Hex(\"type=SvnMaterial<|>url=url<|>username=username<|>checkExternals=true\"));\n }", " @Test\n void shouldGeneratePipelineUniqueFingerprintBasedOnFingerprintAndDest() {\n SvnMaterial one = new SvnMaterial(\"url\", \"username\", \"password\", true, \"folder1\");\n SvnMaterial two = new SvnMaterial(\"url\", \"username\", \"password\", true, \"folder2\");\n assertThat(one.getPipelineUniqueFingerprint()).isNotEqualTo(two.getFingerprint());\n assertThat(one.getPipelineUniqueFingerprint()).isEqualTo(DigestUtils.sha256Hex(\"type=SvnMaterial<|>url=url<|>username=username<|>checkExternals=true<|>dest=folder1\"));\n }", " @Test\n void shouldNotUsePasswordForEquality() {\n SvnMaterial svnBoozer = new SvnMaterial(\"foo.com\", \"loser\", \"boozer\", true);\n SvnMaterial svnZooser = new SvnMaterial(\"foo.com\", \"loser\", \"zooser\", true);\n assertThat(svnBoozer.hashCode()).isEqualTo(svnZooser.hashCode());\n assertThat(svnBoozer).isEqualTo(svnZooser);\n }", " @Test", " void shouldEncryptSvnPasswordAndMarkPasswordAsNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");", " SvnMaterial material = new SvnMaterial(\"/foo\", \"username\", \"password\", false, mockGoCipher);\n material.ensureEncrypted();", " assertThat(material.getPassword()).isNull();\n assertThat(material.getEncryptedPassword()).isEqualTo(\"encrypted\");\n }", " @Test\n void shouldDecryptSvnPassword() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");", " SvnMaterial material = new SvnMaterial(\"/foo\", \"username\", null, false, mockGoCipher);\n ReflectionUtil.setField(material, \"encryptedPassword\", \"encrypted\");", " material.ensureEncrypted();\n assertThat(material.getPassword()).isEqualTo(\"password\");\n }", " @Test", " void shouldNotDecryptSvnPasswordIfPasswordIsNotNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");", " SvnMaterial material = new SvnMaterial(\"/foo\", \"username\", \"password\", false, mockGoCipher);\n material.ensureEncrypted();\n when(mockGoCipher.encrypt(\"new_password\")).thenReturn(\"new_encrypted\");\n material.setPassword(\"new_password\");\n when(mockGoCipher.decrypt(\"new_encrypted\")).thenReturn(\"new_password\");", " assertThat(material.getPassword()).isEqualTo(\"new_password\");", " }", " @Test\n void shouldErrorOutIfDecryptionFails() throws CryptoException {\n GoCipher mockGoCipher = mock(GoCipher.class);\n String fakeCipherText = \"fake cipher text\";\n when(mockGoCipher.decrypt(fakeCipherText)).thenThrow(new CryptoException(\"exception\"));\n SvnMaterial material = new SvnMaterial(\"/foo\", \"username\", null, false, mockGoCipher);\n ReflectionUtil.setField(material, \"encryptedPassword\", fakeCipherText);\n try {\n material.getPassword();\n fail(\"Should have thrown up\");\n } catch (Exception e) {\n assertThat(e.getMessage()).isEqualTo(\"Could not decrypt the password to get the real password\");\n }\n }", " @Test\n void shouldErrorOutIfEncryptionFails() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenThrow(new CryptoException(\"exception\"));\n try {\n new SvnMaterial(\"/foo\", \"username\", \"password\", false, mockGoCipher);\n fail(\"Should have thrown up\");\n } catch (Exception e) {\n assertThat(e.getMessage()).isEqualTo(\"Password encryption failed. Please verify your cipher key.\");\n }", " }", " @Test\n void shouldGetLongDescriptionForMaterial() {\n SvnMaterial material = new SvnMaterial(\"http://url/\", \"user\", \"password\", true, \"folder\");\n assertThat(material.getLongDescription()).isEqualTo(\"URL: http://url/, Username: user, CheckExternals: true\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() {\n SvnMaterial material = new SvnMaterial(\"abc\", \"def\", \"ghi\", false);\n SvnMaterialConfig config = (SvnMaterialConfig) material.config();", " assertThat(config.getEncryptedPassword()).isNotNull();\n assertThat(config.getPassword()).isEqualTo(\"ghi\");\n }", " private void assertComplementaryEquals(Object o1, Object o2, boolean value) {\n assertThat(o1.equals(o2)).isEqualTo(value);\n assertThat(o2.equals(o1)).isEqualTo(value);\n }", " @Test\n void shouldGetAttributesWithSecureFields() {\n SvnMaterial material = new SvnMaterial(\"http://username:password@svnrepo.com\", \"user\", \"password\", true);\n Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"svn\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"svn-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:password@svnrepo.com\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"user\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"check-externals\")).isEqualTo(true);\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {\n SvnMaterial material = new SvnMaterial(\"http://username:password@svnrepo.com\", \"user\", \"password\", true);\n Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"svn\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"svn-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:******@svnrepo.com\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"user\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"check-externals\")).isEqualTo(true);\n }", " @Nested\n class hasSecretParams {\n @Test\n void shouldBeTrueIfPasswordHasSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"{{SECRET:[secret_config_id][lookup_password]}}\", false);", " assertThat(svnMaterial.hasSecretParams()).isTrue();\n }", " @Test\n void shouldBeFalseIfPasswordDoesNotHaveSecretParams() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"password\", false);", " assertThat(svnMaterial.hasSecretParams()).isFalse();\n }\n }", " @Nested\n class getSecretParams {\n @Test\n void shouldReturnAListOfSecretParams() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\",\n \"username\", \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }", " @Test\n void shouldBeAnEmptyListInAbsenceOfSecretParamsInMaterialUrlOrPassword() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"pass\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(0);\n }\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"badger\", false);", " assertThat(svnMaterial.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " svnMaterial.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(svnMaterial.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThatCode(svnMaterial::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.svn;", "import com.thoughtworks.go.config.SecretParam;\nimport com.thoughtworks.go.config.exceptions.UnresolvedSecretParamException;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.materials.RevisionContext;\nimport com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;\nimport com.thoughtworks.go.helper.MaterialConfigsMother;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.JsonValue;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.codec.digest.DigestUtils;\nimport org.junit.Rule;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Nested;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;\nimport org.junit.rules.TemporaryFolder;", "import java.io.*;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.Map;", "import static com.thoughtworks.go.util.JsonUtils.from;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static org.assertj.core.api.Assertions.*;\nimport static org.mockito.Mockito.*;", "@EnableRuleMigrationSupport\npublic class SvnMaterialTest {\n @Rule\n public final TemporaryFolder temporaryFolder = new TemporaryFolder();", " private Subversion subversion;", " private SvnMaterial svnMaterial;\n private static final String URL = \"svn://something\";\n private SubversionRevision revision = new SubversionRevision(\"1\");\n private InMemoryStreamConsumer outputStreamConsumer = inMemoryConsumer();", " @BeforeEach\n void setUp() throws IOException {\n temporaryFolder.create();\n subversion = mock(Subversion.class);", " when(subversion.getUrl()).thenReturn(new UrlArgument(URL));\n when(subversion.getPassword()).thenReturn(\"\");\n when(subversion.getUserName()).thenReturn(\"\");\n when(subversion.isCheckExternals()).thenReturn(false);", " svnMaterial = SvnMaterial.createSvnMaterialWithMock(subversion);\n svnMaterial.setUrl(URL);\n }", " @AfterEach\n void tearDown() {\n temporaryFolder.delete();\n }", " private File createSvnWorkingCopy(boolean withDotSvnFolder) throws IOException {\n File folder = temporaryFolder.newFolder(\"testSvnWorkingCopy\");\n if (withDotSvnFolder) {\n File dotSvnFolder = new File(folder, \".svn\");\n dotSvnFolder.mkdir();\n }\n return folder;\n }", " @Test\n void shouldNotDisplayPasswordInStringRepresentation() {\n SvnMaterial svn = new SvnMaterial(\"my-url\", \"user\", \"loser\", false);\n assertThat(svn.toString()).doesNotContain(\"loser\");", " svn = new SvnMaterial(\"https://user:loser@foo.bar/baz?quux=bang\", \"user\", \"loser\", false);\n assertThat(svn.toString()).doesNotContain(\"loser\");\n }", " @Test\n void shouldCheckoutWhenFolderDoesNotExist() {\n final File workingCopy = new File(\"xyz\");", " updateMaterial(svnMaterial, revision, workingCopy);", " verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldLogRepoInfoToConsoleOutWithOutFolder() throws Exception {\n final File workingCopy = new File(\"xyz\");", " updateMaterial(svnMaterial, revision, workingCopy);\n String stdout = outputStreamConsumer.getStdOut();\n assertThat(stdout).contains(String.format(\"Start updating %s at revision %s from %s\", \"files\", revision.getRevision(),\n svnMaterial.getUrl()));", " verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldCheckoutForInvalidSvnWorkingCopy() throws IOException {\n final File workingCopy = createSvnWorkingCopy(false);", " updateMaterial(svnMaterial, revision, workingCopy);", " assertThat(workingCopy.exists()).isFalse();\n verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " private void updateMaterial(SvnMaterial svnMaterial, SubversionRevision revision, File workingCopy) {\n svnMaterial.updateTo(outputStreamConsumer, workingCopy, new RevisionContext(revision), new TestSubprocessExecutionContext());\n }", " @Test\n void shouldCheckoutIfSvnRepositoryChanged() throws IOException {\n final File workingCopy = createSvnWorkingCopy(true);", " when(subversion.workingRepositoryUrl(workingCopy)).thenReturn(\"new url\");", " updateMaterial(svnMaterial, revision, workingCopy);\n assertThat(workingCopy.exists()).isFalse();\n verify(subversion).checkoutTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldUpdateForValidSvnWorkingCopy() throws IOException {\n final File workingCopy = createSvnWorkingCopy(true);", " when(subversion.workingRepositoryUrl(workingCopy)).thenReturn(URL);", " updateMaterial(svnMaterial, revision, workingCopy);", " verify(subversion).cleanupAndRevert(outputStreamConsumer, workingCopy);\n verify(subversion).updateTo(outputStreamConsumer, workingCopy, revision);\n }", " @Test\n void shouldBeEqualWhenUrlSameForSvnMaterial() {\n final Material material1 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n final Material material = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n assertComplementaryEquals(material1, material, true);", " }", " @Test\n void shouldNotBeEqualWhenUrlDifferent() {\n final Material material1 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n final Material material2 = MaterialsMother.defaultSvnMaterialsWithUrl(\"url2\").get(0);\n assertComplementaryEquals(material1, material2, false);\n }", " @Test\n void shouldNotBeEqualWhenTypeDifferent() {\n final Material hgMaterial = MaterialsMother.hgMaterials(\"url1\", \"hgdir\").get(0);\n final Material nonHgMaterial = MaterialsMother.defaultSvnMaterialsWithUrl(\"url1\").get(0);\n assertComplementaryEquals(hgMaterial, nonHgMaterial, false);\n }", " @Test\n void shouldNotBeEqualWhenAlternateFolderDifferent() {\n final SvnMaterial material1 = MaterialsMother.svnMaterial(\"url1\");\n final SvnMaterial material2 = MaterialsMother.svnMaterial(\"url1\");", " assertComplementaryEquals(material1, material2, true);", " material1.setFolder(\"foo\");\n material2.setFolder(null);\n assertComplementaryEquals(material1, material2, false);", " material1.setFolder(\"foo\");\n material2.setFolder(\"bar\");\n assertComplementaryEquals(material1, material2, false);\n }", " @Test\n void shouldSerializeAndDeserializeCorrectly() throws Exception {\n final SvnMaterial material1 = MaterialsMother.svnMaterial(\"url1\", \"foo\");\n ByteArrayOutputStream buf = new ByteArrayOutputStream();\n ObjectOutputStream serialized = new ObjectOutputStream(buf);\n serialized.writeObject(material1);\n ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));\n assertThat(in.readObject()).isEqualTo(material1);\n }", " @Test\n void shouldReturnNotEqualsWhenUrlIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"A\");", " SvnMaterial other = MaterialsMother.svnMaterial(\"B\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnNotEqualsWhenUserNameIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\", \"svnDir\", \"userName\", null, false, \"*.txt\");", " SvnMaterial other = MaterialsMother.svnMaterial(\"url\", \"svnDir\", \"userName1\", null, false, \"*.txt\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnEqualsEvenIfPasswordsAreDifferent() {\n SvnMaterial material = MaterialsMother.svnMaterial();\n material.setPassword(\"password\");", " SvnMaterial other = MaterialsMother.svnMaterial();\n other.setPassword(\"password1\");\n assertThat(material).isEqualTo(other);\n }", " @Test\n void shouldReturnNotEqualsWhenCheckExternalsIsChanged() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\", \"svnDir\", null, null, true, \"*.txt\");\n SvnMaterial other = MaterialsMother.svnMaterial(\"url\", \"svnDir\", null, null, false, \"*.txt\");\n assertThat(material).isNotEqualTo(other);\n }", " @Test\n void shouldReturnEqualsWhenEverythingIsSame() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"URL\", \"dummy-folder\", \"userName\", \"password\", true, \"*.doc\");\n SvnMaterial other = MaterialsMother.svnMaterial(\"URL\", \"dummy-folder\", \"userName\", \"password\", true, \"*.doc\");", " assertThat(other).isEqualTo(material);\n }", " /* TODO: *SBD* Move this test into SvnMaterialConfig test after mothers are moved. */\n @Test\n void shouldReturnEqualsWhenEverythingIsSameForSvnMaterialConfigs() {\n SvnMaterialConfig svnMaterialConfig = MaterialConfigsMother.svnMaterialConfig();\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.CHECK_EXTERNALS, String.valueOf(true)));\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.USERNAME, \"userName\"));\n svnMaterialConfig.setPassword(\"password\");\n svnMaterialConfig.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.URL, \"URL\"));", "\n SvnMaterialConfig other = MaterialConfigsMother.svnMaterialConfig();\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.CHECK_EXTERNALS, String.valueOf(true)));\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.USERNAME, \"userName\"));\n other.setPassword(\"password\");\n other.setConfigAttributes(Collections.singletonMap(SvnMaterialConfig.URL, \"URL\"));", " assertThat(other).isEqualTo(svnMaterialConfig);\n }", " @Test\n void shouldBeAbleToConvertToJson() {\n SvnMaterial material = MaterialsMother.svnMaterial(\"url\");\n Map<String, Object> json = new LinkedHashMap<>();\n material.toJson(json, revision);", " JsonValue jsonValue = from(json);\n assertThat(jsonValue.getString(\"scmType\")).isEqualTo(\"Subversion\");\n assertThat(new File(jsonValue.getString(\"location\"))).isEqualTo(new File(material.getUrl()));\n assertThat(jsonValue.getString(\"action\")).isEqualTo(\"Modified\");\n }", " @Test\n void shouldAddTheForwardSlashAndApplyThePattern() {\n SvnMaterial material = MaterialsMother.svnMaterial();", " assertThat(material.matches(\"/a.doc\", \"a.doc\")).isTrue();\n assertThat(material.matches(\"a.doc\", \"a.doc\")).isFalse();\n }", " @Test\n void shouldApplyThePatternDirectly() {\n SvnMaterial material = MaterialsMother.svnMaterial();", " assertThat(material.matches(\"/a.doc\", \"/a.doc\")).isTrue();\n }", " @Test\n void shouldGenerateSqlCriteriaMapInSpecificOrder() {\n SvnMaterial material = new SvnMaterial(\"url\", \"username\", \"password\", true);\n Map<String, Object> map = material.getSqlCriteria();\n assertThat(map.size()).isEqualTo(4);\n Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();\n assertThat(iter.next().getKey()).isEqualTo(\"type\");\n assertThat(iter.next().getKey()).isEqualTo(\"url\");\n assertThat(iter.next().getKey()).isEqualTo(\"username\");\n assertThat(iter.next().getKey()).isEqualTo(\"checkExternals\");\n }", " @Test\n void shouldGenerateFingerprintBasedOnSqlCriteria() {\n SvnMaterial one = new SvnMaterial(\"url\", \"username\", \"password\", true);\n SvnMaterial two = new SvnMaterial(\"url\", \"username\", \"password\", false);\n assertThat(one.getFingerprint()).isNotEqualTo(two.getFingerprint());\n assertThat(one.getFingerprint()).isEqualTo(DigestUtils.sha256Hex(\"type=SvnMaterial<|>url=url<|>username=username<|>checkExternals=true\"));\n }", " @Test\n void shouldGeneratePipelineUniqueFingerprintBasedOnFingerprintAndDest() {\n SvnMaterial one = new SvnMaterial(\"url\", \"username\", \"password\", true, \"folder1\");\n SvnMaterial two = new SvnMaterial(\"url\", \"username\", \"password\", true, \"folder2\");\n assertThat(one.getPipelineUniqueFingerprint()).isNotEqualTo(two.getFingerprint());\n assertThat(one.getPipelineUniqueFingerprint()).isEqualTo(DigestUtils.sha256Hex(\"type=SvnMaterial<|>url=url<|>username=username<|>checkExternals=true<|>dest=folder1\"));\n }", " @Test\n void shouldNotUsePasswordForEquality() {\n SvnMaterial svnBoozer = new SvnMaterial(\"foo.com\", \"loser\", \"boozer\", true);\n SvnMaterial svnZooser = new SvnMaterial(\"foo.com\", \"loser\", \"zooser\", true);\n assertThat(svnBoozer.hashCode()).isEqualTo(svnZooser.hashCode());\n assertThat(svnBoozer).isEqualTo(svnZooser);\n }", " @Test", "", " void shouldNotDecryptSvnPasswordIfPasswordIsNotNull() throws Exception {\n GoCipher mockGoCipher = mock(GoCipher.class);\n when(mockGoCipher.encrypt(\"password\")).thenReturn(\"encrypted\");\n when(mockGoCipher.decrypt(\"encrypted\")).thenReturn(\"password\");", " SvnMaterial material = new SvnMaterial(\"/foo\", \"username\", \"password\", false, mockGoCipher);\n material.ensureEncrypted();\n when(mockGoCipher.encrypt(\"new_password\")).thenReturn(\"new_encrypted\");\n material.setPassword(\"new_password\");\n when(mockGoCipher.decrypt(\"new_encrypted\")).thenReturn(\"new_password\");", " assertThat(material.getPassword()).isEqualTo(\"new_password\");", "", " }", " @Test\n void shouldGetLongDescriptionForMaterial() {\n SvnMaterial material = new SvnMaterial(\"http://url/\", \"user\", \"password\", true, \"folder\");\n assertThat(material.getLongDescription()).isEqualTo(\"URL: http://url/, Username: user, CheckExternals: true\");\n }", " @Test\n void shouldCopyOverPasswordWhenConvertingToConfig() {\n SvnMaterial material = new SvnMaterial(\"abc\", \"def\", \"ghi\", false);\n SvnMaterialConfig config = (SvnMaterialConfig) material.config();", " assertThat(config.getEncryptedPassword()).isNotNull();\n assertThat(config.getPassword()).isEqualTo(\"ghi\");\n }", " private void assertComplementaryEquals(Object o1, Object o2, boolean value) {\n assertThat(o1.equals(o2)).isEqualTo(value);\n assertThat(o2.equals(o1)).isEqualTo(value);\n }", " @Test\n void shouldGetAttributesWithSecureFields() {\n SvnMaterial material = new SvnMaterial(\"http://username:password@svnrepo.com\", \"user\", \"password\", true);\n Map<String, Object> attributes = material.getAttributes(true);", " assertThat(attributes.get(\"type\")).isEqualTo(\"svn\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"svn-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:password@svnrepo.com\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"user\");\n assertThat(configuration.get(\"password\")).isEqualTo(\"password\");\n assertThat(configuration.get(\"check-externals\")).isEqualTo(true);\n }", " @Test\n void shouldGetAttributesWithoutSecureFields() {\n SvnMaterial material = new SvnMaterial(\"http://username:password@svnrepo.com\", \"user\", \"password\", true);\n Map<String, Object> attributes = material.getAttributes(false);", " assertThat(attributes.get(\"type\")).isEqualTo(\"svn\");\n Map<String, Object> configuration = (Map<String, Object>) attributes.get(\"svn-configuration\");\n assertThat(configuration.get(\"url\")).isEqualTo(\"http://username:******@svnrepo.com\");\n assertThat(configuration.get(\"username\")).isEqualTo(\"user\");\n assertThat(configuration.get(\"password\")).isNull();\n assertThat(configuration.get(\"check-externals\")).isEqualTo(true);\n }", " @Nested\n class hasSecretParams {\n @Test\n void shouldBeTrueIfPasswordHasSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"{{SECRET:[secret_config_id][lookup_password]}}\", false);", " assertThat(svnMaterial.hasSecretParams()).isTrue();\n }", " @Test\n void shouldBeFalseIfPasswordDoesNotHaveSecretParams() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"password\", false);", " assertThat(svnMaterial.hasSecretParams()).isFalse();\n }\n }", " @Nested\n class getSecretParams {\n @Test\n void shouldReturnAListOfSecretParams() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\",\n \"username\", \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }", " @Test\n void shouldBeAnEmptyListInAbsenceOfSecretParamsInMaterialUrlOrPassword() {\n SvnMaterial svnMaterial = new SvnMaterial(\"http://foo.com\", null, \"pass\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(0);\n }\n }", " @Nested\n class passwordForCommandLine {\n @Test\n void shouldReturnPasswordAsConfigured_IfNotDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"badger\", false);", " assertThat(svnMaterial.passwordForCommandLine()).isEqualTo(\"badger\");\n }", " @Test\n void shouldReturnAResolvedPassword_IfPasswordDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " svnMaterial.getSecretParams().findFirst(\"lookup_pass\").ifPresent(secretParam -> secretParam.setValue(\"resolved_password\"));", " assertThat(svnMaterial.passwordForCommandLine()).isEqualTo(\"resolved_password\");\n }", " @Test\n void shouldErrorOutWhenCalledOnAUnResolvedSecretParam_IfPasswordDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThatCode(svnMaterial::passwordForCommandLine)\n .isInstanceOf(UnresolvedSecretParamException.class)\n .hasMessageContaining(\"SecretParam 'lookup_pass' is used before it is resolved.\");\n }\n }", " @Nested\n class setPassword {\n @Test\n void shouldParsePasswordString_IfDefinedAsSecretParam() {\n SvnMaterial svnMaterial = new SvnMaterial(\"url\", null, \"{{SECRET:[secret_config_id][lookup_pass]}}\", false);", " assertThat(svnMaterial.getSecretParams())\n .hasSize(1)\n .contains(new SecretParam(\"secret_config_id\", \"lookup_pass\"));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.server.service;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.PackageMaterialConfig;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;\nimport com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.materials.MaterialConfig;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinition;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinitionMother;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepository;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepositoryMother;\nimport com.thoughtworks.go.domain.scm.SCM;\nimport com.thoughtworks.go.domain.scm.SCMMother;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.HgUrlArgument;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.Test;\nimport org.junit.experimental.theories.DataPoint;\nimport org.junit.experimental.theories.Theories;\nimport org.junit.experimental.theories.Theory;\nimport org.junit.platform.commons.util.AnnotationUtils;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.config.BeanDefinition;\nimport org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;\nimport org.springframework.core.type.filter.AssignableTypeFilter;", "import java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.*;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;", "import static com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother.create;\nimport static com.thoughtworks.go.helper.FilterMother.filterFor;\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.*;\nimport static org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals;\nimport static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;", "@RunWith(Theories.class)\npublic class MagicalMaterialAndMaterialConfigConversionTest {\n private static PackageRepository packageRepo = PackageRepositoryMother.create(\"repo-id\", \"repo-name\", \"pluginid\", \"version\", new Configuration(create(\"k1\", false, \"v1\")));\n private static PackageDefinition packageDefinition = PackageDefinitionMother.create(\"id\", \"name1\", new Configuration(create(\"k2\", false, \"v2\")), packageRepo);\n public static SCM scmConfig = SCMMother.create(\"scm-id\", \"scm-name\", \"plugin-id\", \"1.0\", new Configuration(create(\"k1\", false, \"v1\")));", " private static Map<Class, String[]> fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack = new HashMap<>();\n private MaterialConfigConverter materialConfigConverter = new MaterialConfigConverter();", " @DataPoint\n public static MaterialConfig svnMaterialConfig = svn(url(\"svn-url\"), \"user\", \"pass\", true, new GoCipher(), true, filterFor(\"*.txt\"), false, \"folder\", cis(\"name1\"));\n @DataPoint\n public static MaterialConfig gitMaterialConfig = git(url(\"git-url\"), null, \"pass\", \"branch\", \"submodule\", true, filterFor(\"*.doc\"), false, \"folder\", cis(\"gitMaterial\"), false);\n @DataPoint\n public static MaterialConfig hgMaterialConfig = hg(new HgUrlArgument(\"hg-url\"), null, \"pass\", null, true, filterFor(\"*.png\"), false, \"folder\", cis(\"hgMaterial\"));\n @DataPoint\n public static MaterialConfig p4MaterialConfig = p4(\"localhost:9090\", \"user\", \"pass\", true, \"view\", new GoCipher(), cis(\"p4Material\"), true, filterFor(\"*.jpg\"), false, \"folder\");\n @DataPoint\n public static MaterialConfig tfsMaterialConfig = tfs(url(\"tfs-url\"), \"user\", \"domain\", \"pass\", \"prj-path\", new GoCipher(), true, filterFor(\"*.txt\"), false, \"folder\", cis(\"tfsMaterial\"));\n @DataPoint\n public static MaterialConfig pkgMaterialConfig = new PackageMaterialConfig(cis(\"name\"), \"pkg-id\", packageDefinition);\n @DataPoint\n public static MaterialConfig pluggableSCMMaterialConfig = new PluggableSCMMaterialConfig(cis(\"name\"), scmConfig, \"folder\", filterFor(\"*.txt\"), false);\n @DataPoint\n public static MaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(cis(\"name1\"), cis(\"pipeline1\"), cis(\"stage1\"));", " static {\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(GitMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(HgMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(SvnMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(P4MaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(TfsMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(PackageMaterialConfig.class, new String[]{\"filter\", \"packageId\", \"packageDefinition\", \"fingerprint\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(PluggableSCMMaterialConfig.class, new String[]{\"filter\", \"scmId\", \"scmConfig\", \"fingerprint\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(DependencyMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n }", " @Theory\n public void shouldBeSameObject_WhenConversionIsDoneFromMaterialConfigToMaterialAndBack(MaterialConfig materialConfig) {\n Material materialFromConfig = materialConfigConverter.toMaterial(materialConfig);\n MaterialConfig materialConfigConvertedBackFromMaterial = materialFromConfig.config();", " assertThat(materialConfigConvertedBackFromMaterial, is(materialConfig));\n assertTrue(message(\"Material <-> MaterialConfig conversion failed.\", materialConfigConvertedBackFromMaterial, materialConfig),\n reflectionEquals(materialConfigConvertedBackFromMaterial, materialConfig, fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.get(materialConfig.getClass())));", " assertThat(materialFromConfig.getFingerprint(), is(materialConfig.getFingerprint()));\n assertThat(materialFromConfig.isAutoUpdate(), is(materialConfig.isAutoUpdate()));\n assertThat(materialConfigConvertedBackFromMaterial.getFingerprint(), is(materialConfig.getFingerprint()));\n assertPasswordIsCorrect(materialConfig);\n assertPasswordIsCorrect(materialFromConfig);\n assertPasswordIsCorrect(materialConfigConvertedBackFromMaterial);\n }", " @Theory\n public void shouldBeSameObject_WhenConversionIsDoneFromMaterialToMaterialInstanceAndBack(MaterialConfig materialConfig) {\n Material material = materialConfigConverter.toMaterial(materialConfig);", " MaterialInstance materialInstance = material.createMaterialInstance();\n Material materialConvertedBackFromInstance = materialInstance.toOldMaterial(materialConfig.getName().toString(), materialConfig.getFolder(), \"pass\");", " assertTrue(message(\"Material <-> MaterialInstance conversion failed.\", material, materialConvertedBackFromInstance),\n reflectionEquals(material, materialConvertedBackFromInstance, fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.get(materialConfig.getClass())));", " assertThat(materialInstance.getFingerprint(), is(material.getFingerprint()));\n assertThat(materialConvertedBackFromInstance.getFingerprint(), is(materialInstance.getFingerprint()));\n assertPasswordIsCorrect(material);\n assertPasswordIsCorrect(materialConvertedBackFromInstance);\n }", " @Test\n public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {\n ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);\n provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));\n Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(\"com/thoughtworks\");\n List<Class> reflectionsSubTypesOf = candidateComponents.stream().map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {\n try {\n return Class.forName(s);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toList());", " reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);", " List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();", " assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf, allExpectedMaterialConfigImplementations);\n }", " private void assertThatAllMaterialConfigsInCodeAreTestedHere(List<Class> reflectionsSubTypesOf, List<Class> allExpectedMaterialConfigImplementations) {\n List<Class> missingImplementations = new ArrayList<>(reflectionsSubTypesOf);\n missingImplementations.removeAll(allExpectedMaterialConfigImplementations);\n String message = \"You need to add a DataPoint for these materials in this test: \" + missingImplementations;", " assertThat(message, reflectionsSubTypesOf.size(), is(allExpectedMaterialConfigImplementations.size()));\n assertThat(message, reflectionsSubTypesOf, hasItems(allExpectedMaterialConfigImplementations.toArray(new Class[allExpectedMaterialConfigImplementations.size()])));\n }", " private List<Class> allMaterialConfigsWhichAreDataPointsInThisTest() throws Exception {\n List<Field> fields = AnnotationUtils.findAnnotatedFields(getClass(), DataPoint.class, field -> true);", " ArrayList<Class> allDataPointMaterialConfigClasses = new ArrayList<>();\n for (Field field : fields) {\n allDataPointMaterialConfigClasses.add(field.get(this).getClass());\n }\n return allDataPointMaterialConfigClasses;\n }", " private boolean isNotAConcrete_NonTest_MaterialConfigImplementation(Class aClass) {\n return Pattern.matches(\".*(Test|Dummy).*\", aClass.toString()) || Modifier.isAbstract(aClass.getModifiers());\n }", " private void assertPasswordIsCorrect(Material material) {\n if (material instanceof PasswordAwareMaterial) {\n assertThat(\"Password setting is wrong for: \" + material.getClass(), ((PasswordAwareMaterial) material).getPassword(), is(\"pass\"));", " assertThat(\"Password setting is wrong for: \" + material.getClass(), ReflectionUtil.getField(material, \"password\"), is(nullValue()));\n assertThat(\"Password setting is wrong for: \" + material.getClass(), ReflectionUtil.getField(material, \"encryptedPassword\"), is(not(nullValue())));", " }\n }", " private void assertPasswordIsCorrect(MaterialConfig materialConfig) {\n if (materialConfig instanceof PasswordAwareMaterial) {\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ((PasswordAwareMaterial) materialConfig).getPassword(), is(\"pass\"));\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ReflectionUtil.getField(materialConfig, \"password\"), is(nullValue()));\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ReflectionUtil.getField(materialConfig, \"encryptedPassword\"), is(not(nullValue())));\n }\n }", " private String message(String prefix, Object expected, Object actual) {\n return prefix + \"\\nExpected: \" + reflectionToString(expected) + \"\\n Actual: \" + reflectionToString(actual);\n }", " private static CaseInsensitiveString cis(String value) {\n return new CaseInsensitiveString(value);\n }", " private static UrlArgument url(String url) {\n return new UrlArgument(url);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.server.service;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.PackageMaterialConfig;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;\nimport com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.materials.MaterialConfig;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinition;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinitionMother;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepository;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepositoryMother;\nimport com.thoughtworks.go.domain.scm.SCM;\nimport com.thoughtworks.go.domain.scm.SCMMother;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.ReflectionUtil;\nimport com.thoughtworks.go.util.command.HgUrlArgument;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.Test;\nimport org.junit.experimental.theories.DataPoint;\nimport org.junit.experimental.theories.Theories;\nimport org.junit.experimental.theories.Theory;\nimport org.junit.platform.commons.util.AnnotationUtils;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.config.BeanDefinition;\nimport org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;\nimport org.springframework.core.type.filter.AssignableTypeFilter;", "import java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.*;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;", "import static com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother.create;\nimport static com.thoughtworks.go.helper.FilterMother.filterFor;\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.*;\nimport static org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals;\nimport static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertThat;\nimport static org.junit.Assert.assertTrue;", "@RunWith(Theories.class)\npublic class MagicalMaterialAndMaterialConfigConversionTest {\n private static PackageRepository packageRepo = PackageRepositoryMother.create(\"repo-id\", \"repo-name\", \"pluginid\", \"version\", new Configuration(create(\"k1\", false, \"v1\")));\n private static PackageDefinition packageDefinition = PackageDefinitionMother.create(\"id\", \"name1\", new Configuration(create(\"k2\", false, \"v2\")), packageRepo);\n public static SCM scmConfig = SCMMother.create(\"scm-id\", \"scm-name\", \"plugin-id\", \"1.0\", new Configuration(create(\"k1\", false, \"v1\")));", " private static Map<Class, String[]> fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack = new HashMap<>();\n private MaterialConfigConverter materialConfigConverter = new MaterialConfigConverter();", " @DataPoint\n public static MaterialConfig svnMaterialConfig = svn(url(\"svn-url\"), \"user\", \"pass\", true, new GoCipher(), true, filterFor(\"*.txt\"), false, \"folder\", cis(\"name1\"));\n @DataPoint\n public static MaterialConfig gitMaterialConfig = git(url(\"git-url\"), null, \"pass\", \"branch\", \"submodule\", true, filterFor(\"*.doc\"), false, \"folder\", cis(\"gitMaterial\"), false);\n @DataPoint\n public static MaterialConfig hgMaterialConfig = hg(new HgUrlArgument(\"hg-url\"), null, \"pass\", null, true, filterFor(\"*.png\"), false, \"folder\", cis(\"hgMaterial\"));\n @DataPoint\n public static MaterialConfig p4MaterialConfig = p4(\"localhost:9090\", \"user\", \"pass\", true, \"view\", new GoCipher(), cis(\"p4Material\"), true, filterFor(\"*.jpg\"), false, \"folder\");\n @DataPoint\n public static MaterialConfig tfsMaterialConfig = tfs(url(\"tfs-url\"), \"user\", \"domain\", \"pass\", \"prj-path\", new GoCipher(), true, filterFor(\"*.txt\"), false, \"folder\", cis(\"tfsMaterial\"));\n @DataPoint\n public static MaterialConfig pkgMaterialConfig = new PackageMaterialConfig(cis(\"name\"), \"pkg-id\", packageDefinition);\n @DataPoint\n public static MaterialConfig pluggableSCMMaterialConfig = new PluggableSCMMaterialConfig(cis(\"name\"), scmConfig, \"folder\", filterFor(\"*.txt\"), false);\n @DataPoint\n public static MaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(cis(\"name1\"), cis(\"pipeline1\"), cis(\"stage1\"));", " static {\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(GitMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(HgMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(SvnMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(P4MaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(TfsMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(PackageMaterialConfig.class, new String[]{\"filter\", \"packageId\", \"packageDefinition\", \"fingerprint\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(PluggableSCMMaterialConfig.class, new String[]{\"filter\", \"scmId\", \"scmConfig\", \"fingerprint\"});\n fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.put(DependencyMaterialConfig.class, new String[]{\"filter\", \"secretParamsForPassword\", \"goCipher\"});\n }", " @Theory\n public void shouldBeSameObject_WhenConversionIsDoneFromMaterialConfigToMaterialAndBack(MaterialConfig materialConfig) {\n Material materialFromConfig = materialConfigConverter.toMaterial(materialConfig);\n MaterialConfig materialConfigConvertedBackFromMaterial = materialFromConfig.config();", " assertThat(materialConfigConvertedBackFromMaterial, is(materialConfig));\n assertTrue(message(\"Material <-> MaterialConfig conversion failed.\", materialConfigConvertedBackFromMaterial, materialConfig),\n reflectionEquals(materialConfigConvertedBackFromMaterial, materialConfig, fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.get(materialConfig.getClass())));", " assertThat(materialFromConfig.getFingerprint(), is(materialConfig.getFingerprint()));\n assertThat(materialFromConfig.isAutoUpdate(), is(materialConfig.isAutoUpdate()));\n assertThat(materialConfigConvertedBackFromMaterial.getFingerprint(), is(materialConfig.getFingerprint()));\n assertPasswordIsCorrect(materialConfig);\n assertPasswordIsCorrect(materialFromConfig);\n assertPasswordIsCorrect(materialConfigConvertedBackFromMaterial);\n }", " @Theory\n public void shouldBeSameObject_WhenConversionIsDoneFromMaterialToMaterialInstanceAndBack(MaterialConfig materialConfig) {\n Material material = materialConfigConverter.toMaterial(materialConfig);", " MaterialInstance materialInstance = material.createMaterialInstance();\n Material materialConvertedBackFromInstance = materialInstance.toOldMaterial(materialConfig.getName().toString(), materialConfig.getFolder(), \"pass\");", " assertTrue(message(\"Material <-> MaterialInstance conversion failed.\", material, materialConvertedBackFromInstance),\n reflectionEquals(material, materialConvertedBackFromInstance, fieldsWhichShouldBeIgnoredWhenSavedInDbAndGotBack.get(materialConfig.getClass())));", " assertThat(materialInstance.getFingerprint(), is(material.getFingerprint()));\n assertThat(materialConvertedBackFromInstance.getFingerprint(), is(materialInstance.getFingerprint()));\n assertPasswordIsCorrect(material);\n assertPasswordIsCorrect(materialConvertedBackFromInstance);\n }", " @Test\n public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {\n ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);\n provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));\n Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(\"com/thoughtworks\");\n List<Class> reflectionsSubTypesOf = candidateComponents.stream().map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {\n try {\n return Class.forName(s);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toList());", " reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);", " List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();", " assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf, allExpectedMaterialConfigImplementations);\n }", " private void assertThatAllMaterialConfigsInCodeAreTestedHere(List<Class> reflectionsSubTypesOf, List<Class> allExpectedMaterialConfigImplementations) {\n List<Class> missingImplementations = new ArrayList<>(reflectionsSubTypesOf);\n missingImplementations.removeAll(allExpectedMaterialConfigImplementations);\n String message = \"You need to add a DataPoint for these materials in this test: \" + missingImplementations;", " assertThat(message, reflectionsSubTypesOf.size(), is(allExpectedMaterialConfigImplementations.size()));\n assertThat(message, reflectionsSubTypesOf, hasItems(allExpectedMaterialConfigImplementations.toArray(new Class[allExpectedMaterialConfigImplementations.size()])));\n }", " private List<Class> allMaterialConfigsWhichAreDataPointsInThisTest() throws Exception {\n List<Field> fields = AnnotationUtils.findAnnotatedFields(getClass(), DataPoint.class, field -> true);", " ArrayList<Class> allDataPointMaterialConfigClasses = new ArrayList<>();\n for (Field field : fields) {\n allDataPointMaterialConfigClasses.add(field.get(this).getClass());\n }\n return allDataPointMaterialConfigClasses;\n }", " private boolean isNotAConcrete_NonTest_MaterialConfigImplementation(Class aClass) {\n return Pattern.matches(\".*(Test|Dummy).*\", aClass.toString()) || Modifier.isAbstract(aClass.getModifiers());\n }", " private void assertPasswordIsCorrect(Material material) {\n if (material instanceof PasswordAwareMaterial) {\n assertThat(\"Password setting is wrong for: \" + material.getClass(), ((PasswordAwareMaterial) material).getPassword(), is(\"pass\"));", " assertThat(\"Password setting is wrong for: \" + material.getClass(), ReflectionUtil.getField(material, \"password\"), is(\"pass\"));", " }\n }", " private void assertPasswordIsCorrect(MaterialConfig materialConfig) {\n if (materialConfig instanceof PasswordAwareMaterial) {\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ((PasswordAwareMaterial) materialConfig).getPassword(), is(\"pass\"));\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ReflectionUtil.getField(materialConfig, \"password\"), is(nullValue()));\n assertThat(\"Password setting is wrong for: \" + materialConfig.getClass(), ReflectionUtil.getField(materialConfig, \"encryptedPassword\"), is(not(nullValue())));\n }\n }", " private String message(String prefix, Object expected, Object actual) {\n return prefix + \"\\nExpected: \" + reflectionToString(expected) + \"\\n Actual: \" + reflectionToString(actual);\n }", " private static CaseInsensitiveString cis(String value) {\n return new CaseInsensitiveString(value);\n }", " private static UrlArgument url(String url) {\n return new UrlArgument(url);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;\nimport com.thoughtworks.go.domain.BaseCollection;\nimport com.thoughtworks.go.domain.ConfigVisitor;\nimport com.thoughtworks.go.domain.MaterialRevisions;\nimport com.thoughtworks.go.domain.materials.*;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.ArtifactLogUtil;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.StringUtils;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;", "public class Materials extends BaseCollection<Material> {\n private static final int DEFAULT_INTERVAL = 100;\n private int intervalInSeconds = DEFAULT_INTERVAL;", " public Materials() {\n }", " public Materials(Material... materials) {\n super(materials);\n }", " public Materials(List<Material> materials) {\n this(DEFAULT_INTERVAL, materials);\n }", " public Materials(int intervalInSeconds, List<Material> materials) {\n super(materials);\n this.intervalInSeconds = intervalInSeconds;\n }", " public Materials(MaterialConfigs materialConfigs) {\n for (MaterialConfig materialConfig : materialConfigs) {\n add(convertToMaterial(materialConfig));\n }\n }", " public int interval() {\n return intervalInSeconds;\n }", " /**\n * @deprecated Used only in tests\n */\n public MaterialRevisions latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n MaterialRevisions revisions = new MaterialRevisions();\n for (Material material : this) {\n List<Modification> modifications = new ArrayList<>();\n if (material instanceof SvnMaterial) {\n modifications = ((SvnMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof HgMaterial) {\n modifications = ((HgMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof GitMaterial) {\n modifications = ((GitMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof P4Material) {\n modifications = ((P4Material) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof TfsMaterial) {\n modifications = ((TfsMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof DependencyMaterial) {\n modifications = ((DependencyMaterial) material).latestModification(baseDir, execCtx);\n }\n revisions.addRevision(material, modifications);\n }\n return revisions;\n }", " public void cleanUp(File baseFolder, ConsoleOutputStreamConsumer consumer) {\n if (hasMaterialsWithNoDestinationFolder()) {\n return;\n }", " DirectoryCleaner cleaner = new DirectoryCleaner(baseFolder, consumer);\n cleaner.allowed(allowedFolders());\n cleaner.clean();\n }", " private List<String> allowedFolders() {\n ArrayList<String> allowed = new ArrayList<>();\n for (Material material : this) {\n if (!StringUtils.isBlank(material.getFolder())) {\n allowed.add(material.getFolder());\n }\n }\n allowed.add(ArtifactLogUtil.CRUISE_OUTPUT_FOLDER);\n return allowed;\n }", " boolean hasMaterialsWithNoDestinationFolder() {\n for (Material material : this) {\n AbstractMaterial abstractMaterial = (AbstractMaterial) material;\n if (abstractMaterial.supportsDestinationFolder() && !abstractMaterial.hasDestinationFolder()) {\n return true;\n }\n }\n return false;\n }", " public void accept(ConfigVisitor visitor) {\n for (Material material : this) {\n visitor.visit(material);\n }\n }", " public int count(Class<? extends Material> materialClass) {\n int count = 0;\n for (Material material : this) {\n if (materialClass.isInstance(material)) {\n count++;\n }\n }\n return count;\n }", " public Material byFolder(String folder) {\n for (Material material : this) {\n if ((material instanceof ScmMaterial || material instanceof PluggableSCMMaterial) && Objects.equals(folder, material.getFolder())) {\n return material;\n }\n }\n return null;\n }", " public Material getByFingerPrint(String fingerPrint) {\n for (Material material : this) {\n if (material.getPipelineUniqueFingerprint().equals(fingerPrint)) {\n return material;\n }\n }\n return null;\n }", " public Material get(Material other) {\n for (Material material : this) {\n if (material.isSameFlyweight(other)) {\n return material;\n }\n }\n throw new RuntimeException(\"Material not found: \" + other);//IMP: because, config can change between BCPS call and build cause production - shilpa/jj\n }", " /*\n To two methods below are to avoid creating methods on already long Material interface with a No Op implementations.\n */", " private List<ScmMaterial> filterScmMaterials() {\n List<ScmMaterial> scmMaterials = new ArrayList<>();\n for (Material material : this) {\n if (material instanceof ScmMaterial) {\n scmMaterials.add((ScmMaterial) material);\n }\n }\n return scmMaterials;\n }", " public boolean scmMaterialsHaveDestination() {\n for (ScmMaterial scmMaterial : filterScmMaterials()) {\n if (!scmMaterial.hasDestinationFolder()) {\n return false;\n }\n }\n return true;\n }", " public SvnMaterial getSvnMaterial() {\n return getExistingOrDefaultMaterial(new SvnMaterial(\"\", \"\", \"\", false));\n }", " public TfsMaterial getTfsMaterial() {", " return getExistingOrDefaultMaterial(new TfsMaterial(new GoCipher(), new UrlArgument(\"\"), \"\", \"\", \"\", \"\"));", " }", " public HgMaterial getHgMaterial() {\n return getExistingOrDefaultMaterial(new HgMaterial(\"\", null));\n }", " public GitMaterial getGitMaterial() {\n return getExistingOrDefaultMaterial(new GitMaterial(\"\"));\n }", " public P4Material getP4Material() {\n return getExistingOrDefaultMaterial(new P4Material(\"\", \"\"));\n }", " public DependencyMaterial getDependencyMaterial() {\n return getExistingOrDefaultMaterial(new DependencyMaterial(new CaseInsensitiveString(\"\"), new CaseInsensitiveString(\"\")));\n }", " private <T extends Material> T getExistingOrDefaultMaterial(T defaultMaterial) {\n for (Material material : this) {\n if (material.getClass().isAssignableFrom(defaultMaterial.getClass())) {\n return (T) material;\n }\n }\n return defaultMaterial;\n }", " public String getMaterialOptions() {\n return first() == null ? \"\" : first().getType();\n }", " private Material convertToMaterial(MaterialConfig materialConfig) {\n if (SvnMaterial.TYPE.equals(materialConfig.getType())) {\n return new SvnMaterial((SvnMaterialConfig) materialConfig);\n } else if (HgMaterial.TYPE.equals(materialConfig.getType())) {\n return new HgMaterial((HgMaterialConfig) materialConfig);\n } else if (GitMaterial.TYPE.equals(materialConfig.getType())) {\n return new GitMaterial((GitMaterialConfig) materialConfig);\n } else if (P4Material.TYPE.equals(materialConfig.getType())) {\n return new P4Material((P4MaterialConfig) materialConfig);\n } else if (DependencyMaterial.TYPE.equals(materialConfig.getType())) {\n return new DependencyMaterial((DependencyMaterialConfig) materialConfig);\n } else if (TfsMaterial.TYPE.equals(materialConfig.getType())) {\n return new TfsMaterial((TfsMaterialConfig) materialConfig);\n } else if (PackageMaterial.TYPE.equals(materialConfig.getType())) {\n return new PackageMaterial((PackageMaterialConfig) materialConfig);\n } else if (PluggableSCMMaterial.TYPE.equals(materialConfig.getType())) {\n return new PluggableSCMMaterial((PluggableSCMMaterialConfig) materialConfig);\n } else if (TestingMaterial.TYPE.equals(materialConfig.getType())) {\n return new TestingMaterial((TestingMaterialConfig) materialConfig);\n }\n throw new RuntimeException(\"Unexpected material type: \" + materialConfig.getClass() + \": \" + materialConfig);\n }", " public MaterialConfigs convertToConfigs() {\n MaterialConfigs configs = new MaterialConfigs();\n for (Material material : this) {\n configs.add(material.config());\n }\n return configs;\n }", " public boolean hasMaterialConfigWithFingerprint(MaterialConfig materialConfig) {\n for (Material material : this) {\n if (material.getFingerprint().equals(materialConfig.getFingerprint())) {\n return true;\n }\n }\n return false;\n }", "\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;\nimport com.thoughtworks.go.domain.BaseCollection;\nimport com.thoughtworks.go.domain.ConfigVisitor;\nimport com.thoughtworks.go.domain.MaterialRevisions;\nimport com.thoughtworks.go.domain.materials.*;", "", "import com.thoughtworks.go.util.ArtifactLogUtil;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.StringUtils;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;", "public class Materials extends BaseCollection<Material> {\n private static final int DEFAULT_INTERVAL = 100;\n private int intervalInSeconds = DEFAULT_INTERVAL;", " public Materials() {\n }", " public Materials(Material... materials) {\n super(materials);\n }", " public Materials(List<Material> materials) {\n this(DEFAULT_INTERVAL, materials);\n }", " public Materials(int intervalInSeconds, List<Material> materials) {\n super(materials);\n this.intervalInSeconds = intervalInSeconds;\n }", " public Materials(MaterialConfigs materialConfigs) {\n for (MaterialConfig materialConfig : materialConfigs) {\n add(convertToMaterial(materialConfig));\n }\n }", " public int interval() {\n return intervalInSeconds;\n }", " /**\n * @deprecated Used only in tests\n */\n public MaterialRevisions latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n MaterialRevisions revisions = new MaterialRevisions();\n for (Material material : this) {\n List<Modification> modifications = new ArrayList<>();\n if (material instanceof SvnMaterial) {\n modifications = ((SvnMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof HgMaterial) {\n modifications = ((HgMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof GitMaterial) {\n modifications = ((GitMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof P4Material) {\n modifications = ((P4Material) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof TfsMaterial) {\n modifications = ((TfsMaterial) material).latestModification(baseDir, execCtx);\n }\n if (material instanceof DependencyMaterial) {\n modifications = ((DependencyMaterial) material).latestModification(baseDir, execCtx);\n }\n revisions.addRevision(material, modifications);\n }\n return revisions;\n }", " public void cleanUp(File baseFolder, ConsoleOutputStreamConsumer consumer) {\n if (hasMaterialsWithNoDestinationFolder()) {\n return;\n }", " DirectoryCleaner cleaner = new DirectoryCleaner(baseFolder, consumer);\n cleaner.allowed(allowedFolders());\n cleaner.clean();\n }", " private List<String> allowedFolders() {\n ArrayList<String> allowed = new ArrayList<>();\n for (Material material : this) {\n if (!StringUtils.isBlank(material.getFolder())) {\n allowed.add(material.getFolder());\n }\n }\n allowed.add(ArtifactLogUtil.CRUISE_OUTPUT_FOLDER);\n return allowed;\n }", " boolean hasMaterialsWithNoDestinationFolder() {\n for (Material material : this) {\n AbstractMaterial abstractMaterial = (AbstractMaterial) material;\n if (abstractMaterial.supportsDestinationFolder() && !abstractMaterial.hasDestinationFolder()) {\n return true;\n }\n }\n return false;\n }", " public void accept(ConfigVisitor visitor) {\n for (Material material : this) {\n visitor.visit(material);\n }\n }", " public int count(Class<? extends Material> materialClass) {\n int count = 0;\n for (Material material : this) {\n if (materialClass.isInstance(material)) {\n count++;\n }\n }\n return count;\n }", " public Material byFolder(String folder) {\n for (Material material : this) {\n if ((material instanceof ScmMaterial || material instanceof PluggableSCMMaterial) && Objects.equals(folder, material.getFolder())) {\n return material;\n }\n }\n return null;\n }", " public Material getByFingerPrint(String fingerPrint) {\n for (Material material : this) {\n if (material.getPipelineUniqueFingerprint().equals(fingerPrint)) {\n return material;\n }\n }\n return null;\n }", " public Material get(Material other) {\n for (Material material : this) {\n if (material.isSameFlyweight(other)) {\n return material;\n }\n }\n throw new RuntimeException(\"Material not found: \" + other);//IMP: because, config can change between BCPS call and build cause production - shilpa/jj\n }", " /*\n To two methods below are to avoid creating methods on already long Material interface with a No Op implementations.\n */", " private List<ScmMaterial> filterScmMaterials() {\n List<ScmMaterial> scmMaterials = new ArrayList<>();\n for (Material material : this) {\n if (material instanceof ScmMaterial) {\n scmMaterials.add((ScmMaterial) material);\n }\n }\n return scmMaterials;\n }", " public boolean scmMaterialsHaveDestination() {\n for (ScmMaterial scmMaterial : filterScmMaterials()) {\n if (!scmMaterial.hasDestinationFolder()) {\n return false;\n }\n }\n return true;\n }", " public SvnMaterial getSvnMaterial() {\n return getExistingOrDefaultMaterial(new SvnMaterial(\"\", \"\", \"\", false));\n }", " public TfsMaterial getTfsMaterial() {", " return getExistingOrDefaultMaterial(new TfsMaterial(new UrlArgument(\"\"), \"\", \"\", \"\", \"\"));", " }", " public HgMaterial getHgMaterial() {\n return getExistingOrDefaultMaterial(new HgMaterial(\"\", null));\n }", " public GitMaterial getGitMaterial() {\n return getExistingOrDefaultMaterial(new GitMaterial(\"\"));\n }", " public P4Material getP4Material() {\n return getExistingOrDefaultMaterial(new P4Material(\"\", \"\"));\n }", " public DependencyMaterial getDependencyMaterial() {\n return getExistingOrDefaultMaterial(new DependencyMaterial(new CaseInsensitiveString(\"\"), new CaseInsensitiveString(\"\")));\n }", " private <T extends Material> T getExistingOrDefaultMaterial(T defaultMaterial) {\n for (Material material : this) {\n if (material.getClass().isAssignableFrom(defaultMaterial.getClass())) {\n return (T) material;\n }\n }\n return defaultMaterial;\n }", " public String getMaterialOptions() {\n return first() == null ? \"\" : first().getType();\n }", " private Material convertToMaterial(MaterialConfig materialConfig) {\n if (SvnMaterial.TYPE.equals(materialConfig.getType())) {\n return new SvnMaterial((SvnMaterialConfig) materialConfig);\n } else if (HgMaterial.TYPE.equals(materialConfig.getType())) {\n return new HgMaterial((HgMaterialConfig) materialConfig);\n } else if (GitMaterial.TYPE.equals(materialConfig.getType())) {\n return new GitMaterial((GitMaterialConfig) materialConfig);\n } else if (P4Material.TYPE.equals(materialConfig.getType())) {\n return new P4Material((P4MaterialConfig) materialConfig);\n } else if (DependencyMaterial.TYPE.equals(materialConfig.getType())) {\n return new DependencyMaterial((DependencyMaterialConfig) materialConfig);\n } else if (TfsMaterial.TYPE.equals(materialConfig.getType())) {\n return new TfsMaterial((TfsMaterialConfig) materialConfig);\n } else if (PackageMaterial.TYPE.equals(materialConfig.getType())) {\n return new PackageMaterial((PackageMaterialConfig) materialConfig);\n } else if (PluggableSCMMaterial.TYPE.equals(materialConfig.getType())) {\n return new PluggableSCMMaterial((PluggableSCMMaterialConfig) materialConfig);\n } else if (TestingMaterial.TYPE.equals(materialConfig.getType())) {\n return new TestingMaterial((TestingMaterialConfig) materialConfig);\n }\n throw new RuntimeException(\"Unexpected material type: \" + materialConfig.getClass() + \": \" + materialConfig);\n }", " public MaterialConfigs convertToConfigs() {\n MaterialConfigs configs = new MaterialConfigs();\n for (Material material : this) {\n configs.add(material.config());\n }\n return configs;\n }", " public boolean hasMaterialConfigWithFingerprint(MaterialConfig materialConfig) {\n for (Material material : this) {\n if (material.getFingerprint().equals(materialConfig.getFingerprint())) {\n return true;\n }\n }\n return false;\n }", "\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.PipelineConfig;\nimport com.thoughtworks.go.config.SecretParamAware;\nimport com.thoughtworks.go.config.SecretParams;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.*;", "import com.thoughtworks.go.security.CryptoException;\nimport com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.ProcessOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.StringUtils;", "import javax.annotation.PostConstruct;\nimport java.io.File;\nimport java.util.Map;\nimport java.util.Optional;\n", "import static com.thoughtworks.go.util.ExceptionUtils.bomb;", "import static com.thoughtworks.go.util.command.EnvironmentVariableContext.escapeEnvironmentVariable;", "import static org.apache.commons.lang3.StringUtils.isBlank;", "", "/**\n * @understands a source control repository and its configuration\n */\npublic abstract class ScmMaterial extends AbstractMaterial implements SecretParamAware {", " public static final String GO_REVISION = \"GO_REVISION\";\n public static final String GO_TO_REVISION = \"GO_TO_REVISION\";\n public static final String GO_FROM_REVISION = \"GO_FROM_REVISION\";\n public static final String GO_MATERIAL_URL = \"GO_MATERIAL_URL\";", " protected final GoCipher goCipher;", "\n protected Filter filter;\n protected String folder;\n protected boolean autoUpdate = true;\n protected boolean invertFilter = false;\n protected String userName;\n protected String password;", " protected String encryptedPassword;", " protected SecretParams secretParamsForPassword;\n", " public ScmMaterial(String typeName, GoCipher goCipher) {", " super(typeName);", " this.goCipher = goCipher;", " }", " @Override\n protected void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria) {\n basicCriteria.put(\"dest\", folder);\n }", " public File workingdir(File baseFolder) {\n if (getFolder() == null) {\n return baseFolder;\n }\n return new File(baseFolder, getFolder());\n }", " public String updatingTarget() {\n return StringUtils.isEmpty(getFolder()) ? \"files\" : getFolder();\n }", " @Override\n public void toJson(Map json, Revision revision) {\n json.put(\"folder\", getFolder() == null ? \"\" : getFolder());\n json.put(\"scmType\", getTypeForDisplay());\n json.put(\"location\", getLocation());\n if (!CaseInsensitiveString.isBlank(getName())) {\n json.put(\"materialName\", CaseInsensitiveString.str(getName()));\n }\n json.put(\"action\", \"Modified\");\n }", " //most of the material such as hg, git, p4 all print the file from the root without '/'\n //but subversion print it with '/', we standarize it here. look at the implementation of subversion as well.", " @Override\n public boolean matches(String name, String regex) {\n if (regex.startsWith(\"/\")) {\n regex = regex.substring(1);\n }\n return name.matches(regex);\n }", " public void checkout(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n InMemoryStreamConsumer output = ProcessOutputStreamConsumer.inMemoryConsumer();\n this.updateTo(output, baseDir, new RevisionContext(revision), execCtx);\n }", " public String getUserName() {\n return this.userName;\n }", " /* Needed although there is a getUserName above */\n public String getUsername() {\n return userName;\n }", " public final void setPassword(String password) {\n resetPassword(password);\n }", " private void resetPassword(String passwordToSet) {", " if (StringUtils.isBlank(passwordToSet)) {\n encryptedPassword = null;\n }", " setPasswordIfNotBlank(passwordToSet);\n }", " private void setPasswordIfNotBlank(String password) {\n this.password = StringUtils.stripToNull(password);\n this.secretParamsForPassword = SecretParams.parse(password);", " this.encryptedPassword = StringUtils.stripToNull(encryptedPassword);", " if (this.password == null) {\n return;\n }\n try {\n this.encryptedPassword = this.goCipher.encrypt(password);\n } catch (Exception e) {\n bomb(\"Password encryption failed. Please verify your cipher key.\", e);\n }\n this.password = null;", " }", " @PostConstruct\n public void ensureEncrypted() {\n this.userName = StringUtils.stripToNull(this.userName);\n setPasswordIfNotBlank(password);\n }", " public void setUserName(String userName) {\n this.userName = userName;\n }\n", " public final void setEncryptedPassword(String encryptedPassword) {\n this.encryptedPassword = encryptedPassword;\n }", " public final String getEncryptedPassword() {\n return encryptedPassword;\n }\n", " public String getPassword() {", " return currentPassword();", " }", " public String passwordForCommandLine() {\n return secretParamsForPassword == null || secretParamsForPassword.isEmpty() ? getPassword() : secretParamsForPassword.substitute(getPassword());\n }", " @Override\n public boolean hasSecretParams() {\n return this.secretParamsForPassword != null && !this.secretParamsForPassword.isEmpty();\n }", " @Override\n public SecretParams getSecretParams() {\n return secretParamsForPassword;", " }", " public final String currentPassword() {\n try {\n return isBlank(encryptedPassword) ? null : this.goCipher.decrypt(encryptedPassword);\n } catch (CryptoException e) {\n throw new RuntimeException(\"Could not decrypt the password to get the real password\", e);\n }", " }", " public abstract boolean isCheckExternals();", " public abstract String getUrl();", " public abstract String urlForCommandLine();", " protected abstract UrlArgument getUrlArgument();", " protected abstract String getLocation();", " public void setFilter(Filter filter) {\n this.filter = filter;\n }", " @Override\n public void emailContent(StringBuilder content, Modification modification) {\n content.append(getTypeForDisplay() + \": \" + getLocation()).append('\\n').append(\n String.format(\"revision: %s, modified by %s on %s\", modification.getRevision(),\n modification.getUserName(), modification.getModifiedTime()))\n .append('\\n')\n .append(Optional.ofNullable(modification.getComment()).orElse(\"\"));", " }", " @Override\n public String getDescription() {\n return getUriForDisplay();\n }", " @Override\n public String getUriForDisplay() {\n return this.getUrlArgument().forDisplay();\n }", " @Override\n public void populateEnvironmentContext(EnvironmentVariableContext environmentVariableContext, MaterialRevision materialRevision, File workingDir) {\n String toRevision = materialRevision.getRevision().getRevision();\n String fromRevision = materialRevision.getOldestRevision().getRevision();", " setGoRevisionVariables(environmentVariableContext, fromRevision, toRevision);\n setGoMaterialVariables(environmentVariableContext);\n }", " protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n setVariableWithName(environmentVariableContext, this.getUrlArgument().withoutCredentials(), GO_MATERIAL_URL);\n }", " private void setGoRevisionVariables(EnvironmentVariableContext environmentVariableContext, String fromRevision, String toRevision) {\n setVariableWithName(environmentVariableContext, toRevision, GO_REVISION);\n setVariableWithName(environmentVariableContext, toRevision, GO_TO_REVISION);\n setVariableWithName(environmentVariableContext, fromRevision, GO_FROM_REVISION);\n }", " protected void setVariableWithName(EnvironmentVariableContext environmentVariableContext, String value, String propertyName) {\n String materialNameForEnvironmentVariable = getMaterialNameForEnvironmentVariable();\n if (StringUtils.isNotBlank(materialNameForEnvironmentVariable)) {\n environmentVariableContext.setProperty(propertyName + \"_\" + materialNameForEnvironmentVariable, value, false);\n } else {\n environmentVariableContext.setProperty(propertyName, value, false);\n }\n }", " @Override\n public String getMaterialNameForEnvironmentVariable() {\n if (!CaseInsensitiveString.isBlank(this.name)) {\n return escapeEnvironmentVariable(this.name.toUpper());\n }", " return escapeEnvironmentVariable(folder);\n }", " @Override\n public String getFolder() {\n return folder;\n }", " @Override\n public String getDisplayName() {\n return name == null ? getUriForDisplay() : CaseInsensitiveString.str(name);\n }", " @Override\n public boolean isAutoUpdate() {\n return autoUpdate;\n }", " public boolean getAutoUpdate() {\n return autoUpdate;\n }", " public void setAutoUpdate(boolean value) {\n autoUpdate = value;\n }", " public boolean isInvertFilter() {\n return invertFilter;\n }", " public boolean getInvertFilter() {\n return invertFilter;\n }", " public void setInvertFilter(boolean value) {\n invertFilter = value;\n }", " @Override\n public final MatchedRevision createMatchedRevision(Modification modification, String searchString) {\n return new MatchedRevision(searchString, getShortRevision(modification.getRevision()), modification.getRevision(), modification.getUserName(), modification.getModifiedTime(), modification.getComment());\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " ScmMaterial that = (ScmMaterial) o;", " return folder != null ? folder.equals(that.folder) : that.folder == null;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (folder != null ? folder.hashCode() : 0);\n return result;\n }", " public static String changesetUrl(Modification modification, String baseUrl, final long id) {\n return baseUrl + \"/api/materials/\" + id + \"/changeset/\" + modification.getRevision() + \".xml\";\n }", " @Override\n public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) {\n return false;\n }", " // TODO: Consider renaming this to dest since we use that word in the UI & Config\n public void setFolder(String folder) {\n this.folder = folder;\n }", " @Override\n public Revision oldestRevision(Modifications modifications) {\n return Modification.oldestRevision(modifications);\n }", " @Override\n public boolean supportsDestinationFolder() {\n return true;\n }\n}" ]
[ 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.PipelineConfig;\nimport com.thoughtworks.go.config.SecretParamAware;\nimport com.thoughtworks.go.config.SecretParams;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.materials.*;", "", "import com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.ProcessOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.StringUtils;", "import javax.annotation.PostConstruct;\nimport java.io.File;\nimport java.util.Map;\nimport java.util.Optional;\n", "", "import static com.thoughtworks.go.util.command.EnvironmentVariableContext.escapeEnvironmentVariable;", "", "", "/**\n * @understands a source control repository and its configuration\n */\npublic abstract class ScmMaterial extends AbstractMaterial implements SecretParamAware {", " public static final String GO_REVISION = \"GO_REVISION\";\n public static final String GO_TO_REVISION = \"GO_TO_REVISION\";\n public static final String GO_FROM_REVISION = \"GO_FROM_REVISION\";\n public static final String GO_MATERIAL_URL = \"GO_MATERIAL_URL\";", "", "\n protected Filter filter;\n protected String folder;\n protected boolean autoUpdate = true;\n protected boolean invertFilter = false;\n protected String userName;\n protected String password;", "", " protected SecretParams secretParamsForPassword;\n", " public ScmMaterial(String typeName) {", " super(typeName);", "", " }", " @Override\n protected void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria) {\n basicCriteria.put(\"dest\", folder);\n }", " public File workingdir(File baseFolder) {\n if (getFolder() == null) {\n return baseFolder;\n }\n return new File(baseFolder, getFolder());\n }", " public String updatingTarget() {\n return StringUtils.isEmpty(getFolder()) ? \"files\" : getFolder();\n }", " @Override\n public void toJson(Map json, Revision revision) {\n json.put(\"folder\", getFolder() == null ? \"\" : getFolder());\n json.put(\"scmType\", getTypeForDisplay());\n json.put(\"location\", getLocation());\n if (!CaseInsensitiveString.isBlank(getName())) {\n json.put(\"materialName\", CaseInsensitiveString.str(getName()));\n }\n json.put(\"action\", \"Modified\");\n }", " //most of the material such as hg, git, p4 all print the file from the root without '/'\n //but subversion print it with '/', we standarize it here. look at the implementation of subversion as well.", " @Override\n public boolean matches(String name, String regex) {\n if (regex.startsWith(\"/\")) {\n regex = regex.substring(1);\n }\n return name.matches(regex);\n }", " public void checkout(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n InMemoryStreamConsumer output = ProcessOutputStreamConsumer.inMemoryConsumer();\n this.updateTo(output, baseDir, new RevisionContext(revision), execCtx);\n }", " public String getUserName() {\n return this.userName;\n }", " /* Needed although there is a getUserName above */\n public String getUsername() {\n return userName;\n }", " public final void setPassword(String password) {\n resetPassword(password);\n }", " private void resetPassword(String passwordToSet) {", "", " setPasswordIfNotBlank(passwordToSet);\n }", " private void setPasswordIfNotBlank(String password) {\n this.password = StringUtils.stripToNull(password);\n this.secretParamsForPassword = SecretParams.parse(password);", "", " }", " @PostConstruct\n public void ensureEncrypted() {\n this.userName = StringUtils.stripToNull(this.userName);\n setPasswordIfNotBlank(password);\n }", " public void setUserName(String userName) {\n this.userName = userName;\n }\n", "", " public String getPassword() {", " return password;", " }", " public String passwordForCommandLine() {\n return secretParamsForPassword == null || secretParamsForPassword.isEmpty() ? getPassword() : secretParamsForPassword.substitute(getPassword());\n }", " @Override\n public boolean hasSecretParams() {\n return this.secretParamsForPassword != null && !this.secretParamsForPassword.isEmpty();\n }", " @Override\n public SecretParams getSecretParams() {\n return secretParamsForPassword;", "", " }", " public abstract boolean isCheckExternals();", " public abstract String getUrl();", " public abstract String urlForCommandLine();", " protected abstract UrlArgument getUrlArgument();", " protected abstract String getLocation();", " public void setFilter(Filter filter) {\n this.filter = filter;\n }", " @Override\n public void emailContent(StringBuilder content, Modification modification) {\n content.append(getTypeForDisplay() + \": \" + getLocation()).append('\\n').append(\n String.format(\"revision: %s, modified by %s on %s\", modification.getRevision(),\n modification.getUserName(), modification.getModifiedTime()))\n .append('\\n')\n .append(Optional.ofNullable(modification.getComment()).orElse(\"\"));", " }", " @Override\n public String getDescription() {\n return getUriForDisplay();\n }", " @Override\n public String getUriForDisplay() {\n return this.getUrlArgument().forDisplay();\n }", " @Override\n public void populateEnvironmentContext(EnvironmentVariableContext environmentVariableContext, MaterialRevision materialRevision, File workingDir) {\n String toRevision = materialRevision.getRevision().getRevision();\n String fromRevision = materialRevision.getOldestRevision().getRevision();", " setGoRevisionVariables(environmentVariableContext, fromRevision, toRevision);\n setGoMaterialVariables(environmentVariableContext);\n }", " protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n setVariableWithName(environmentVariableContext, this.getUrlArgument().withoutCredentials(), GO_MATERIAL_URL);\n }", " private void setGoRevisionVariables(EnvironmentVariableContext environmentVariableContext, String fromRevision, String toRevision) {\n setVariableWithName(environmentVariableContext, toRevision, GO_REVISION);\n setVariableWithName(environmentVariableContext, toRevision, GO_TO_REVISION);\n setVariableWithName(environmentVariableContext, fromRevision, GO_FROM_REVISION);\n }", " protected void setVariableWithName(EnvironmentVariableContext environmentVariableContext, String value, String propertyName) {\n String materialNameForEnvironmentVariable = getMaterialNameForEnvironmentVariable();\n if (StringUtils.isNotBlank(materialNameForEnvironmentVariable)) {\n environmentVariableContext.setProperty(propertyName + \"_\" + materialNameForEnvironmentVariable, value, false);\n } else {\n environmentVariableContext.setProperty(propertyName, value, false);\n }\n }", " @Override\n public String getMaterialNameForEnvironmentVariable() {\n if (!CaseInsensitiveString.isBlank(this.name)) {\n return escapeEnvironmentVariable(this.name.toUpper());\n }", " return escapeEnvironmentVariable(folder);\n }", " @Override\n public String getFolder() {\n return folder;\n }", " @Override\n public String getDisplayName() {\n return name == null ? getUriForDisplay() : CaseInsensitiveString.str(name);\n }", " @Override\n public boolean isAutoUpdate() {\n return autoUpdate;\n }", " public boolean getAutoUpdate() {\n return autoUpdate;\n }", " public void setAutoUpdate(boolean value) {\n autoUpdate = value;\n }", " public boolean isInvertFilter() {\n return invertFilter;\n }", " public boolean getInvertFilter() {\n return invertFilter;\n }", " public void setInvertFilter(boolean value) {\n invertFilter = value;\n }", " @Override\n public final MatchedRevision createMatchedRevision(Modification modification, String searchString) {\n return new MatchedRevision(searchString, getShortRevision(modification.getRevision()), modification.getRevision(), modification.getUserName(), modification.getModifiedTime(), modification.getComment());\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " ScmMaterial that = (ScmMaterial) o;", " return folder != null ? folder.equals(that.folder) : that.folder == null;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (folder != null ? folder.hashCode() : 0);\n return result;\n }", " public static String changesetUrl(Modification modification, String baseUrl, final long id) {\n return baseUrl + \"/api/materials/\" + id + \"/changeset/\" + modification.getRevision() + \".xml\";\n }", " @Override\n public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) {\n return false;\n }", " // TODO: Consider renaming this to dest since we use that word in the UI & Config\n public void setFolder(String folder) {\n this.folder = folder;\n }", " @Override\n public Revision oldestRevision(Modifications modifications) {\n return Modification.oldestRevision(modifications);\n }", " @Override\n public boolean supportsDestinationFolder() {\n return true;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.git;", "import com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.git.GitCommand;\nimport com.thoughtworks.go.domain.materials.git.GitMaterialInstance;\nimport com.thoughtworks.go.domain.materials.git.GitVersion;\nimport com.thoughtworks.go.domain.materials.svn.MaterialUrl;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.transaction.support.TransactionSynchronization;\nimport org.springframework.transaction.support.TransactionSynchronizationAdapter;", "import java.io.File;\nimport java.net.URISyntaxException;\nimport java.util.*;", "import static com.thoughtworks.go.config.materials.git.RefSpecHelper.localBranch;\nimport static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static com.thoughtworks.go.util.FileUtil.deleteDirectoryNoisily;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isAllBlank;\nimport static org.apache.commons.lang3.StringUtils.isBlank;", "public class GitMaterial extends ScmMaterial implements PasswordAwareMaterial {\n public static final int UNSHALLOW_TRYOUT_STEP = 100;\n public static final int DEFAULT_SHALLOW_CLONE_DEPTH = 2;\n public static final String GO_MATERIAL_BRANCH = \"GO_MATERIAL_BRANCH\";\n //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"GitMaterial\";\n public static final String ERR_GIT_OLD_VERSION = \"Please install Git-core 1.9 or above. Currently installed version is \";\n private static final Logger LOG = LoggerFactory.getLogger(GitMaterial.class);\n private static final String ERR_GIT_NOT_FOUND = \"Failed to find 'git' on your PATH. Please ensure 'git' is executable by the Go Server and on the Go Agents where this material will be used.\";\n private final UrlArgument url;\n private String refSpecOrBranch = GitMaterialConfig.DEFAULT_BRANCH;\n private boolean shallowClone = false;\n private String submoduleFolder;", " public GitMaterial(String url) {", " super(TYPE, new GoCipher());", " this.url = new UrlArgument(url);\n }", " public GitMaterial(String url, boolean shallowClone) {\n this(url, null, null, shallowClone);\n }", "\n public GitMaterial(String url, String refSpecOrBranch) {\n this(url);\n if (refSpecOrBranch != null) {\n this.refSpecOrBranch = refSpecOrBranch;\n }\n }", " public GitMaterial(String url, String refSpecOrBranch, String folder) {\n this(url, refSpecOrBranch);\n this.folder = folder;\n }", " public GitMaterial(String url, String refSpecOrBranch, String folder, Boolean shallowClone) {\n this(url, refSpecOrBranch, folder);\n if (shallowClone != null) {\n this.shallowClone = shallowClone;\n }\n }", " public GitMaterial(GitMaterialConfig config) {\n this(config.getUrl(), config.getBranch(), config.getFolder(), config.isShallowClone());\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.name = config.getName();\n this.submoduleFolder = config.getSubmoduleFolder();\n this.invertFilter = config.getInvertFilter();\n this.userName = config.getUserName();\n setPassword(config.getPassword());\n }", " @Override\n public MaterialConfig config() {\n GitMaterialConfig gitMaterialConfig = new GitMaterialConfig();\n gitMaterialConfig.setUrl(this.url.originalArgument());\n gitMaterialConfig.setUserName(this.userName);\n gitMaterialConfig.setPassword(getPassword());\n gitMaterialConfig.setSubmoduleFolder(this.submoduleFolder);\n gitMaterialConfig.setAutoUpdate(this.autoUpdate);\n gitMaterialConfig.setFilter(this.filter);\n gitMaterialConfig.setInvertFilter(this.invertFilter);\n gitMaterialConfig.setFolder(this.folder);\n gitMaterialConfig.setName(this.name);\n gitMaterialConfig.setShallowClone(this.shallowClone);\n Optional.ofNullable(this.refSpecOrBranch).ifPresent(gitMaterialConfig::setBranch);\n return gitMaterialConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n return getGit(baseDir, execCtx).latestModification();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n GitCommand gitCommand = getGit(baseDir, execCtx);\n if (!execCtx.isGitShallowClone()) {\n fullyUnshallow(gitCommand, inMemoryConsumer());\n }\n if (gitCommand.containsRevisionInBranch(revision)) {\n return gitCommand.modificationsSince(revision);\n } else {\n return latestModification(baseDir, execCtx);\n }\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new GitMaterialInstance(url.originalArgument(), userName, refSpecOrBranch, submoduleFolder, UUID.randomUUID().toString());\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n try {\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), getUriForDisplay()));\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n GitCommand git = git(outputStreamConsumer, workingDir, revisionContext.numberOfModifications() + 1, execCtx);\n git.fetch(outputStreamConsumer);\n unshallowIfNeeded(git, outputStreamConsumer, revisionContext.getOldestRevision());\n git.resetWorkingDir(outputStreamConsumer, revision, shallowClone);\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n GitCommand gitCommand = new GitCommand(null, null, refSpecOrBranch, false, secrets());\n try {\n gitCommand.checkConnection(new UrlArgument(urlForCommandLine()));\n return ValidationBean.valid();\n } catch (Exception e) {\n try {\n return handleException(e, gitCommand.version());\n } catch (Exception notInstallGitException) {\n return ValidationBean.notValid(ERR_GIT_NOT_FOUND);\n }\n }\n }", " public ValidationBean handleException(Exception e, GitVersion gitVersion) {\n ValidationBean defaultResponse = ValidationBean.notValid(e.getMessage());\n try {\n if (!gitVersion.isMinimumSupportedVersionOrHigher()) {\n return ValidationBean.notValid(ERR_GIT_OLD_VERSION + gitVersion.getVersion().toString());\n } else {\n return defaultResponse;\n }\n } catch (Exception ex) {\n return defaultResponse;\n }\n }", " /**\n * @deprecated Breaks encapsulation really badly. But we need it for IBatis :-(\n */\n @Override\n public String getUrl() {\n return url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n try {\n if (credentialsAreNotProvided()) {\n return this.url.originalArgument();\n }", " return new URIBuilder(this.url.originalArgument())\n .setUserInfo(new UrlUserInfo(this.userName, this.passwordForCommandLine()).asString())\n .build().toString();", " } catch (URISyntaxException e) {\n return this.url.originalArgument();\n }\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Branch: %s\", url.forDisplay(), refSpecOrBranch);\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n GitMaterial that = (GitMaterial) o;\n return Objects.equals(url, that.url) &&\n Objects.equals(refSpecOrBranch, that.refSpecOrBranch) &&\n Objects.equals(submoduleFolder, that.submoduleFolder);\n }", " @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), url, refSpecOrBranch, submoduleFolder);\n }", " @Override\n public String getTypeForDisplay() {\n return \"Git\";\n }", " public String getBranch() {\n return this.refSpecOrBranch;\n }", " public String getSubmoduleFolder() {\n return submoduleFolder;\n }", " public void setSubmoduleFolder(String submoduleFolder) {\n this.submoduleFolder = submoduleFolder;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " public boolean isShallowClone() {\n return shallowClone;\n }", " @Override\n public String getShortRevision(String revision) {\n if (revision == null) return null;\n if (revision.length() < 7) return revision;\n return revision.substring(0, 7);\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"git\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"branch\", refSpecOrBranch);\n configurationMap.put(\"shallow-clone\", shallowClone);\n materialMap.put(\"git-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return GitMaterialInstance.class;\n }", " @Override\n public String toString() {\n return \"GitMaterial{\" +\n \"url=\" + url +\n \", branch='\" + refSpecOrBranch + '\\'' +\n \", shallowClone=\" + shallowClone +\n \", submoduleFolder='\" + submoduleFolder + '\\'' +\n '}';\n }", " @Override\n public void updateFromConfig(MaterialConfig materialConfig) {\n super.updateFromConfig(materialConfig);\n this.shallowClone = ((GitMaterialConfig) materialConfig).isShallowClone();\n }", " public GitMaterial withShallowClone(boolean value) {\n GitMaterialConfig config = (GitMaterialConfig) config();\n config.setShallowClone(value);\n GitMaterial gitMaterial = new GitMaterial(config);\n gitMaterial.secretParamsForPassword = this.secretParamsForPassword;", " return gitMaterial;\n }", " public String effectiveLocalBranch() {\n return localBranch(isBlank(refSpecOrBranch) ? GitMaterialConfig.DEFAULT_BRANCH : refSpecOrBranch);\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(\"branch\", refSpecOrBranch);\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n parameters.put(\"url\", url);\n parameters.put(\"branch\", refSpecOrBranch);\n parameters.put(\"shallowClone\", shallowClone);\n }", " @Override\n protected String getLocation() {\n return url.forDisplay();\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n setVariableWithName(environmentVariableContext, effectiveLocalBranch(), GO_MATERIAL_BRANCH);\n }", " private GitCommand getGit(File workingdir, SubprocessExecutionContext executionContext) {\n InMemoryStreamConsumer output = inMemoryConsumer();\n try {\n return git(output, workingdir, DEFAULT_SHALLOW_CLONE_DEPTH, executionContext);\n } catch (Exception e) {\n throw bomb(e.getMessage() + \" \" + output.getStdError(), e);\n }\n }", " private GitCommand git(ConsoleOutputStreamConsumer outputStreamConsumer, final File workingFolder, int preferredCloneDepth, SubprocessExecutionContext executionContext) throws Exception {\n if (isSubmoduleFolder()) {\n return new GitCommand(getFingerprint(), new File(workingFolder.getPath()), GitMaterialConfig.DEFAULT_BRANCH, true, secrets());\n }", " GitCommand gitCommand = new GitCommand(getFingerprint(), workingFolder, refSpecOrBranch, false, secrets());\n if (!isGitRepository(workingFolder) || isRepositoryChanged(gitCommand, workingFolder)) {\n LOG.debug(\"Invalid git working copy or repository changed. Delete folder: {}\", workingFolder);\n deleteDirectoryNoisily(workingFolder);\n }\n createParentFolderIfNotExist(workingFolder);\n if (!workingFolder.exists()) {\n TransactionSynchronizationManager txManager = new TransactionSynchronizationManager();\n if (txManager.isActualTransactionActive()) {\n txManager.registerSynchronization(new TransactionSynchronizationAdapter() {\n @Override\n public void afterCompletion(int status) {\n if (status != TransactionSynchronization.STATUS_COMMITTED) {\n FileUtils.deleteQuietly(workingFolder);\n }\n }\n });\n }\n int cloneDepth = shallowClone ? preferredCloneDepth : Integer.MAX_VALUE;\n int returnValue;\n if (executionContext.isServer()) {\n returnValue = gitCommand.cloneWithNoCheckout(outputStreamConsumer, urlForCommandLine());\n } else {\n returnValue = gitCommand.clone(outputStreamConsumer, urlForCommandLine(), cloneDepth);\n }\n bombIfFailedToRunCommandLine(returnValue, \"Failed to run git clone command\");\n }\n return gitCommand;\n }", " private List<SecretString> secrets() {\n SecretString secretSubstitution = line -> line.replace(urlForCommandLine(), getUriForDisplay());\n return Collections.singletonList(secretSubstitution);\n }", " // Unshallow local repo to include a revision operating on via two step process:\n // First try to fetch forward 100 level with \"git fetch -depth 100\". If revision still missing,\n // unshallow the whole repo with \"git fetch --2147483647\".\n private void unshallowIfNeeded(GitCommand gitCommand, ConsoleOutputStreamConsumer streamConsumer, Revision revision) {\n if (gitCommand.isShallow() && !gitCommand.containsRevisionInBranch(revision)) {\n gitCommand.unshallow(streamConsumer, UNSHALLOW_TRYOUT_STEP);", " if (gitCommand.isShallow() && !gitCommand.containsRevisionInBranch(revision)) {\n fullyUnshallow(gitCommand, streamConsumer);\n }\n }\n }", " private void fullyUnshallow(GitCommand gitCommand, ConsoleOutputStreamConsumer streamConsumer) {\n if (gitCommand.isShallow()) {\n gitCommand.unshallow(streamConsumer, Integer.MAX_VALUE);\n }\n }", " private boolean isSubmoduleFolder() {\n return getSubmoduleFolder() != null;\n }", " private boolean isGitRepository(File workingFolder) {\n return new File(workingFolder, \".git\").isDirectory();\n }", " private boolean isRepositoryChanged(GitCommand command, File workingDirectory) {\n UrlArgument currentWorkingUrl = command.workingRepositoryUrl();\n LOG.trace(\"Current repository url of [{}]: {}\", workingDirectory, currentWorkingUrl);\n LOG.trace(\"Target repository url: {}\", url);\n return !MaterialUrl.sameUrl(url.forDisplay(), currentWorkingUrl.forDisplay())\n || !isRemoteFetchConfigEqual(command)\n || !isBranchEqual(command)\n || (!shallowClone && command.isShallow());\n }", " private boolean isRemoteFetchConfigEqual(GitCommand command) {\n if (command.hasRefSpec()) {\n try {\n return (\"+\" + command.expandRefSpec()).equals(command.getConfigValue(\"remote.origin.fetch\"));\n } catch (Throwable ignored) {\n return false;\n }\n }\n return true;\n }", " private boolean isBranchEqual(GitCommand command) {\n return effectiveLocalBranch().equals(command.getCurrentBranch());\n }", " private boolean credentialsAreNotProvided() {\n return isAllBlank(this.userName, this.getPassword());\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.git;", "import com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.git.GitCommand;\nimport com.thoughtworks.go.domain.materials.git.GitMaterialInstance;\nimport com.thoughtworks.go.domain.materials.git.GitVersion;\nimport com.thoughtworks.go.domain.materials.svn.MaterialUrl;", "", "import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.transaction.support.TransactionSynchronization;\nimport org.springframework.transaction.support.TransactionSynchronizationAdapter;", "import java.io.File;\nimport java.net.URISyntaxException;\nimport java.util.*;", "import static com.thoughtworks.go.config.materials.git.RefSpecHelper.localBranch;\nimport static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static com.thoughtworks.go.util.FileUtil.deleteDirectoryNoisily;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isAllBlank;\nimport static org.apache.commons.lang3.StringUtils.isBlank;", "public class GitMaterial extends ScmMaterial implements PasswordAwareMaterial {\n public static final int UNSHALLOW_TRYOUT_STEP = 100;\n public static final int DEFAULT_SHALLOW_CLONE_DEPTH = 2;\n public static final String GO_MATERIAL_BRANCH = \"GO_MATERIAL_BRANCH\";\n //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"GitMaterial\";\n public static final String ERR_GIT_OLD_VERSION = \"Please install Git-core 1.9 or above. Currently installed version is \";\n private static final Logger LOG = LoggerFactory.getLogger(GitMaterial.class);\n private static final String ERR_GIT_NOT_FOUND = \"Failed to find 'git' on your PATH. Please ensure 'git' is executable by the Go Server and on the Go Agents where this material will be used.\";\n private final UrlArgument url;\n private String refSpecOrBranch = GitMaterialConfig.DEFAULT_BRANCH;\n private boolean shallowClone = false;\n private String submoduleFolder;", " public GitMaterial(String url) {", " super(TYPE);", " this.url = new UrlArgument(url);\n }", " public GitMaterial(String url, boolean shallowClone) {\n this(url, null, null, shallowClone);\n }", "\n public GitMaterial(String url, String refSpecOrBranch) {\n this(url);\n if (refSpecOrBranch != null) {\n this.refSpecOrBranch = refSpecOrBranch;\n }\n }", " public GitMaterial(String url, String refSpecOrBranch, String folder) {\n this(url, refSpecOrBranch);\n this.folder = folder;\n }", " public GitMaterial(String url, String refSpecOrBranch, String folder, Boolean shallowClone) {\n this(url, refSpecOrBranch, folder);\n if (shallowClone != null) {\n this.shallowClone = shallowClone;\n }\n }", " public GitMaterial(GitMaterialConfig config) {\n this(config.getUrl(), config.getBranch(), config.getFolder(), config.isShallowClone());\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.name = config.getName();\n this.submoduleFolder = config.getSubmoduleFolder();\n this.invertFilter = config.getInvertFilter();\n this.userName = config.getUserName();\n setPassword(config.getPassword());\n }", " @Override\n public MaterialConfig config() {\n GitMaterialConfig gitMaterialConfig = new GitMaterialConfig();\n gitMaterialConfig.setUrl(this.url.originalArgument());\n gitMaterialConfig.setUserName(this.userName);\n gitMaterialConfig.setPassword(getPassword());\n gitMaterialConfig.setSubmoduleFolder(this.submoduleFolder);\n gitMaterialConfig.setAutoUpdate(this.autoUpdate);\n gitMaterialConfig.setFilter(this.filter);\n gitMaterialConfig.setInvertFilter(this.invertFilter);\n gitMaterialConfig.setFolder(this.folder);\n gitMaterialConfig.setName(this.name);\n gitMaterialConfig.setShallowClone(this.shallowClone);\n Optional.ofNullable(this.refSpecOrBranch).ifPresent(gitMaterialConfig::setBranch);\n return gitMaterialConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n return getGit(baseDir, execCtx).latestModification();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n GitCommand gitCommand = getGit(baseDir, execCtx);\n if (!execCtx.isGitShallowClone()) {\n fullyUnshallow(gitCommand, inMemoryConsumer());\n }\n if (gitCommand.containsRevisionInBranch(revision)) {\n return gitCommand.modificationsSince(revision);\n } else {\n return latestModification(baseDir, execCtx);\n }\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new GitMaterialInstance(url.originalArgument(), userName, refSpecOrBranch, submoduleFolder, UUID.randomUUID().toString());\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n try {\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), getUriForDisplay()));\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n GitCommand git = git(outputStreamConsumer, workingDir, revisionContext.numberOfModifications() + 1, execCtx);\n git.fetch(outputStreamConsumer);\n unshallowIfNeeded(git, outputStreamConsumer, revisionContext.getOldestRevision());\n git.resetWorkingDir(outputStreamConsumer, revision, shallowClone);\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n GitCommand gitCommand = new GitCommand(null, null, refSpecOrBranch, false, secrets());\n try {\n gitCommand.checkConnection(new UrlArgument(urlForCommandLine()));\n return ValidationBean.valid();\n } catch (Exception e) {\n try {\n return handleException(e, gitCommand.version());\n } catch (Exception notInstallGitException) {\n return ValidationBean.notValid(ERR_GIT_NOT_FOUND);\n }\n }\n }", " public ValidationBean handleException(Exception e, GitVersion gitVersion) {\n ValidationBean defaultResponse = ValidationBean.notValid(e.getMessage());\n try {\n if (!gitVersion.isMinimumSupportedVersionOrHigher()) {\n return ValidationBean.notValid(ERR_GIT_OLD_VERSION + gitVersion.getVersion().toString());\n } else {\n return defaultResponse;\n }\n } catch (Exception ex) {\n return defaultResponse;\n }\n }", " /**\n * @deprecated Breaks encapsulation really badly. But we need it for IBatis :-(\n */\n @Override\n public String getUrl() {\n return url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n try {\n if (credentialsAreNotProvided()) {\n return this.url.originalArgument();\n }", " return new URIBuilder(this.url.originalArgument())\n .setUserInfo(new UrlUserInfo(this.userName, this.passwordForCommandLine()).asString())\n .build().toString();", " } catch (URISyntaxException e) {\n return this.url.originalArgument();\n }\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Branch: %s\", url.forDisplay(), refSpecOrBranch);\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n GitMaterial that = (GitMaterial) o;\n return Objects.equals(url, that.url) &&\n Objects.equals(refSpecOrBranch, that.refSpecOrBranch) &&\n Objects.equals(submoduleFolder, that.submoduleFolder);\n }", " @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), url, refSpecOrBranch, submoduleFolder);\n }", " @Override\n public String getTypeForDisplay() {\n return \"Git\";\n }", " public String getBranch() {\n return this.refSpecOrBranch;\n }", " public String getSubmoduleFolder() {\n return submoduleFolder;\n }", " public void setSubmoduleFolder(String submoduleFolder) {\n this.submoduleFolder = submoduleFolder;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " public boolean isShallowClone() {\n return shallowClone;\n }", " @Override\n public String getShortRevision(String revision) {\n if (revision == null) return null;\n if (revision.length() < 7) return revision;\n return revision.substring(0, 7);\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"git\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"branch\", refSpecOrBranch);\n configurationMap.put(\"shallow-clone\", shallowClone);\n materialMap.put(\"git-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return GitMaterialInstance.class;\n }", " @Override\n public String toString() {\n return \"GitMaterial{\" +\n \"url=\" + url +\n \", branch='\" + refSpecOrBranch + '\\'' +\n \", shallowClone=\" + shallowClone +\n \", submoduleFolder='\" + submoduleFolder + '\\'' +\n '}';\n }", " @Override\n public void updateFromConfig(MaterialConfig materialConfig) {\n super.updateFromConfig(materialConfig);\n this.shallowClone = ((GitMaterialConfig) materialConfig).isShallowClone();\n }", " public GitMaterial withShallowClone(boolean value) {\n GitMaterialConfig config = (GitMaterialConfig) config();\n config.setShallowClone(value);\n GitMaterial gitMaterial = new GitMaterial(config);\n gitMaterial.secretParamsForPassword = this.secretParamsForPassword;", " return gitMaterial;\n }", " public String effectiveLocalBranch() {\n return localBranch(isBlank(refSpecOrBranch) ? GitMaterialConfig.DEFAULT_BRANCH : refSpecOrBranch);\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(\"branch\", refSpecOrBranch);\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n parameters.put(\"url\", url);\n parameters.put(\"branch\", refSpecOrBranch);\n parameters.put(\"shallowClone\", shallowClone);\n }", " @Override\n protected String getLocation() {\n return url.forDisplay();\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n setVariableWithName(environmentVariableContext, effectiveLocalBranch(), GO_MATERIAL_BRANCH);\n }", " private GitCommand getGit(File workingdir, SubprocessExecutionContext executionContext) {\n InMemoryStreamConsumer output = inMemoryConsumer();\n try {\n return git(output, workingdir, DEFAULT_SHALLOW_CLONE_DEPTH, executionContext);\n } catch (Exception e) {\n throw bomb(e.getMessage() + \" \" + output.getStdError(), e);\n }\n }", " private GitCommand git(ConsoleOutputStreamConsumer outputStreamConsumer, final File workingFolder, int preferredCloneDepth, SubprocessExecutionContext executionContext) throws Exception {\n if (isSubmoduleFolder()) {\n return new GitCommand(getFingerprint(), new File(workingFolder.getPath()), GitMaterialConfig.DEFAULT_BRANCH, true, secrets());\n }", " GitCommand gitCommand = new GitCommand(getFingerprint(), workingFolder, refSpecOrBranch, false, secrets());\n if (!isGitRepository(workingFolder) || isRepositoryChanged(gitCommand, workingFolder)) {\n LOG.debug(\"Invalid git working copy or repository changed. Delete folder: {}\", workingFolder);\n deleteDirectoryNoisily(workingFolder);\n }\n createParentFolderIfNotExist(workingFolder);\n if (!workingFolder.exists()) {\n TransactionSynchronizationManager txManager = new TransactionSynchronizationManager();\n if (txManager.isActualTransactionActive()) {\n txManager.registerSynchronization(new TransactionSynchronizationAdapter() {\n @Override\n public void afterCompletion(int status) {\n if (status != TransactionSynchronization.STATUS_COMMITTED) {\n FileUtils.deleteQuietly(workingFolder);\n }\n }\n });\n }\n int cloneDepth = shallowClone ? preferredCloneDepth : Integer.MAX_VALUE;\n int returnValue;\n if (executionContext.isServer()) {\n returnValue = gitCommand.cloneWithNoCheckout(outputStreamConsumer, urlForCommandLine());\n } else {\n returnValue = gitCommand.clone(outputStreamConsumer, urlForCommandLine(), cloneDepth);\n }\n bombIfFailedToRunCommandLine(returnValue, \"Failed to run git clone command\");\n }\n return gitCommand;\n }", " private List<SecretString> secrets() {\n SecretString secretSubstitution = line -> line.replace(urlForCommandLine(), getUriForDisplay());\n return Collections.singletonList(secretSubstitution);\n }", " // Unshallow local repo to include a revision operating on via two step process:\n // First try to fetch forward 100 level with \"git fetch -depth 100\". If revision still missing,\n // unshallow the whole repo with \"git fetch --2147483647\".\n private void unshallowIfNeeded(GitCommand gitCommand, ConsoleOutputStreamConsumer streamConsumer, Revision revision) {\n if (gitCommand.isShallow() && !gitCommand.containsRevisionInBranch(revision)) {\n gitCommand.unshallow(streamConsumer, UNSHALLOW_TRYOUT_STEP);", " if (gitCommand.isShallow() && !gitCommand.containsRevisionInBranch(revision)) {\n fullyUnshallow(gitCommand, streamConsumer);\n }\n }\n }", " private void fullyUnshallow(GitCommand gitCommand, ConsoleOutputStreamConsumer streamConsumer) {\n if (gitCommand.isShallow()) {\n gitCommand.unshallow(streamConsumer, Integer.MAX_VALUE);\n }\n }", " private boolean isSubmoduleFolder() {\n return getSubmoduleFolder() != null;\n }", " private boolean isGitRepository(File workingFolder) {\n return new File(workingFolder, \".git\").isDirectory();\n }", " private boolean isRepositoryChanged(GitCommand command, File workingDirectory) {\n UrlArgument currentWorkingUrl = command.workingRepositoryUrl();\n LOG.trace(\"Current repository url of [{}]: {}\", workingDirectory, currentWorkingUrl);\n LOG.trace(\"Target repository url: {}\", url);\n return !MaterialUrl.sameUrl(url.forDisplay(), currentWorkingUrl.forDisplay())\n || !isRemoteFetchConfigEqual(command)\n || !isBranchEqual(command)\n || (!shallowClone && command.isShallow());\n }", " private boolean isRemoteFetchConfigEqual(GitCommand command) {\n if (command.hasRefSpec()) {\n try {\n return (\"+\" + command.expandRefSpec()).equals(command.getConfigValue(\"remote.origin.fetch\"));\n } catch (Throwable ignored) {\n return false;\n }\n }\n return true;\n }", " private boolean isBranchEqual(GitCommand command) {\n return effectiveLocalBranch().equals(command.getCurrentBranch());\n }", " private boolean credentialsAreNotProvided() {\n return isAllBlank(this.userName, this.getPassword());\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.mercurial;", "import com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.mercurial.HgCommand;\nimport com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance;\nimport com.thoughtworks.go.domain.materials.mercurial.HgVersion;\nimport com.thoughtworks.go.domain.materials.svn.MaterialUrl;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.net.URISyntaxException;\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "import static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isAllBlank;\nimport static org.apache.commons.lang3.StringUtils.isNotBlank;", "/**\n * @understands configuration for mercurial version control\n */\npublic class HgMaterial extends ScmMaterial implements PasswordAwareMaterial {\n private static final Pattern HG_VERSION_PATTERN = Pattern.compile(\".*\\\\(.*\\\\s+(\\\\d(\\\\.\\\\d)+.*)\\\\)\");\n private static final Logger LOGGER = LoggerFactory.getLogger(HgMaterial.class);\n private HgUrlArgument url;", " //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"HgMaterial\";\n private static final String ERROR_OLD_VERSION = \"Please install Mercurial Version 1.0 or above.\"\n + \" The current installed hg is \";\n private static final String ERR_NO_HG_INSTALLED =\n \"Failed to find 'hg' on your PATH. Please ensure 'hg' is executable by the Go Server and on the Go Agents where this material will be used.\";", " private final String HG_DEFAULT_BRANCH = \"default\";\n private String branch;", " private HgMaterial() {", " super(TYPE, new GoCipher());", " }", " public HgMaterial(String url, String folder) {\n this();\n this.url = new HgUrlArgument(url);\n this.folder = folder;\n }", " public HgMaterial(HgMaterialConfig config) {\n this(config.getUrl(), config.getFolder());\n this.userName = config.getUserName();\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.name = config.getName();\n this.userName = config.getUserName();\n this.branch = config.getBranch();\n setPassword(config.getPassword());\n }", " @Override\n public MaterialConfig config() {\n HgMaterialConfig hgConfig = new HgMaterialConfig();\n hgConfig.setUrl(this.url.originalArgument());\n hgConfig.setUserName(this.userName);\n hgConfig.setPassword(getPassword());\n hgConfig.setBranchAttribute(this.branch);\n hgConfig.setAutoUpdate(this.autoUpdate);\n hgConfig.setFilter(this.filter);\n hgConfig.setInvertFilter(this.invertFilter);\n hgConfig.setFolder(this.folder);\n hgConfig.setName(this.name);\n return hgConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n HgCommand hgCommand = getHg(baseDir);\n return hgCommand.latestOneModificationAsModifications();\n }", "\n public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return getHg(baseDir).modificationsSince(revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new HgMaterialInstance(url.originalArgument(), userName, branch, UUID.randomUUID().toString());\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n if (isNotBlank(branch)) {\n parameters.put(\"branch\", branch);\n }\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n parameters.put(\"url\", url);\n }", " private HgCommand getHg(File baseDir) {\n InMemoryStreamConsumer output =\n ProcessOutputStreamConsumer.inMemoryConsumer();\n HgCommand hgCommand = null;\n try {\n hgCommand = hg(baseDir, output);\n } catch (Exception e) {\n bomb(e.getMessage() + \" \" + output.getStdError(), e);\n }", " return hgCommand;\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n try {\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url.forDisplay()));\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n hg(workingDir, outputStreamConsumer).updateTo(revision, outputStreamConsumer);\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public void add(File baseDir, ProcessOutputStreamConsumer outputStreamConsumer, File file) throws Exception {\n hg(baseDir, outputStreamConsumer).add(outputStreamConsumer, file);\n }", " public void commit(File baseDir, ProcessOutputStreamConsumer consumer, String comment, String username)\n throws Exception {\n hg(baseDir, consumer).commit(consumer, comment, username);\n }", " public void push(File baseDir, ProcessOutputStreamConsumer consumer) throws Exception {\n hg(baseDir, consumer).push(consumer);\n }", " boolean isVersionOneDotZeroOrHigher(String hgout) {\n String hgVersion = parseHgVersion(hgout);\n Float aFloat = NumberUtils.createFloat(hgVersion.subSequence(0, 3).toString());\n return aFloat >= 1;\n }", " private String parseHgVersion(String hgOut) {\n String[] lines = hgOut.split(\"\\n\");\n String firstLine = lines[0];\n Matcher m = HG_VERSION_PATTERN.matcher(firstLine);\n if (m.matches()) {\n return m.group(1);\n } else {\n throw bomb(\"can not parse hgout : \" + hgOut);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n HgCommand hgCommand = new HgCommand(null, null, null, null, secrets());\n try {\n hgCommand.checkConnection(new HgUrlArgument(urlForCommandLine()));\n return ValidationBean.valid();\n } catch (Exception e) {\n try {\n return handleException(e, hgCommand.version());\n } catch (Exception ex) {\n return ValidationBean.notValid(ERR_NO_HG_INSTALLED);\n }\n }\n }", " ValidationBean handleException(Exception e, HgVersion version) {\n ValidationBean defaultResponse = ValidationBean.notValid(\n \"Repository \" + url.forDisplay() + \" not found!\" + \" : \\n\" + e.getMessage());\n try {\n if (version.isOlderThanOneDotZero()) {\n return ValidationBean.notValid(ERROR_OLD_VERSION + version.toString());\n } else {\n return defaultResponse;\n }\n } catch (Exception e1) {\n LOGGER.debug(\"Problem validating HG\", e);\n return defaultResponse;\n }\n }", "\n private HgCommand hg(File workingFolder, ConsoleOutputStreamConsumer outputStreamConsumer) throws Exception {\n UrlArgument urlArgument = new HgUrlArgument(urlForCommandLine());\n HgCommand hgCommand = new HgCommand(getFingerprint(), workingFolder, getBranch(), urlArgument.forCommandLine(), secrets());\n if (!isHgRepository(workingFolder) || isRepositoryChanged(hgCommand)) {\n LOGGER.debug(\"Invalid hg working copy or repository changed. Delete folder: {}\", workingFolder);\n FileUtils.deleteQuietly(workingFolder);\n }\n if (!workingFolder.exists()) {\n createParentFolderIfNotExist(workingFolder);\n int returnValue = hgCommand.clone(outputStreamConsumer, urlArgument);\n bombIfFailedToRunCommandLine(returnValue, \"Failed to run hg clone command\");\n }\n return hgCommand;\n }", " protected List<SecretString> secrets() {\n SecretString secretSubstitution = line -> line.replace(urlForCommandLine(), getUriForDisplay());\n return Collections.singletonList(secretSubstitution);\n }", " private boolean isHgRepository(File workingFolder) {\n return new File(workingFolder, \".hg\").isDirectory();\n }", " private boolean isRepositoryChanged(HgCommand hgCommand) {\n ConsoleResult result = hgCommand.workingRepositoryUrl();\n return !MaterialUrl.sameUrl(url.defaultRemoteUrl(), new HgUrlArgument(result.outputAsString()).defaultRemoteUrl());\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n try {\n if (credentialsAreNotProvided()) {\n return this.url.originalArgument();\n }", " return new URIBuilder(this.url.originalArgument())\n .setUserInfo(new UrlUserInfo(this.userName, this.passwordForCommandLine()).asString())\n .build().toString();", " } catch (URISyntaxException e) {\n return this.url.originalArgument();\n }\n }", " private boolean credentialsAreNotProvided() {\n return isAllBlank(this.userName, this.getPassword());\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " public HgUrlArgument getHgUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s\", url.forDisplay());\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " HgMaterial that = (HgMaterial) o;", " if (url != null ? !url.equals(that.url) : that.url != null) {\n return false;\n }", " if (branch != null ? !branch.equals(that.branch) : that.branch != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (branch != null ? branch.hashCode() : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return getUrlArgument().forDisplay();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Mercurial\";\n }", " @Override\n public String getShortRevision(String revision) {\n if (revision == null) return null;\n if (revision.length() < 12) return revision;\n return revision.substring(0, 12);\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"mercurial\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n materialMap.put(\"mercurial-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return HgMaterialInstance.class;\n }", " @Override\n public String toString() {\n return \"HgMaterial{\" +\n \"url=\" + url +\n '}';\n }", " public void setBranch(String branch) {\n this.branch = branch;\n }", "\n public String getBranch() {\n if (isNotBlank(branch)) {\n return branch;\n }", " return getBranchFromUrl();\n }", " private String getBranchFromUrl() {\n String[] componentsOfUrl = StringUtils.split(url.originalArgument(), HgUrlArgument.DOUBLE_HASH);\n if (componentsOfUrl.length > 1) {\n return componentsOfUrl[1];\n }\n return HG_DEFAULT_BRANCH;\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n setVariableWithName(environmentVariableContext, getBranch(), GitMaterial.GO_MATERIAL_BRANCH);\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.mercurial;", "import com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.mercurial.HgCommand;\nimport com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance;\nimport com.thoughtworks.go.domain.materials.mercurial.HgVersion;\nimport com.thoughtworks.go.domain.materials.svn.MaterialUrl;", "", "import com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.*;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.apache.http.client.utils.URIBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.net.URISyntaxException;\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "import static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isAllBlank;\nimport static org.apache.commons.lang3.StringUtils.isNotBlank;", "/**\n * @understands configuration for mercurial version control\n */\npublic class HgMaterial extends ScmMaterial implements PasswordAwareMaterial {\n private static final Pattern HG_VERSION_PATTERN = Pattern.compile(\".*\\\\(.*\\\\s+(\\\\d(\\\\.\\\\d)+.*)\\\\)\");\n private static final Logger LOGGER = LoggerFactory.getLogger(HgMaterial.class);\n private HgUrlArgument url;", " //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"HgMaterial\";\n private static final String ERROR_OLD_VERSION = \"Please install Mercurial Version 1.0 or above.\"\n + \" The current installed hg is \";\n private static final String ERR_NO_HG_INSTALLED =\n \"Failed to find 'hg' on your PATH. Please ensure 'hg' is executable by the Go Server and on the Go Agents where this material will be used.\";", " private final String HG_DEFAULT_BRANCH = \"default\";\n private String branch;", " private HgMaterial() {", " super(TYPE);", " }", " public HgMaterial(String url, String folder) {\n this();\n this.url = new HgUrlArgument(url);\n this.folder = folder;\n }", " public HgMaterial(HgMaterialConfig config) {\n this(config.getUrl(), config.getFolder());\n this.userName = config.getUserName();\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.name = config.getName();\n this.userName = config.getUserName();\n this.branch = config.getBranch();\n setPassword(config.getPassword());\n }", " @Override\n public MaterialConfig config() {\n HgMaterialConfig hgConfig = new HgMaterialConfig();\n hgConfig.setUrl(this.url.originalArgument());\n hgConfig.setUserName(this.userName);\n hgConfig.setPassword(getPassword());\n hgConfig.setBranchAttribute(this.branch);\n hgConfig.setAutoUpdate(this.autoUpdate);\n hgConfig.setFilter(this.filter);\n hgConfig.setInvertFilter(this.invertFilter);\n hgConfig.setFolder(this.folder);\n hgConfig.setName(this.name);\n return hgConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n HgCommand hgCommand = getHg(baseDir);\n return hgCommand.latestOneModificationAsModifications();\n }", "\n public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return getHg(baseDir).modificationsSince(revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new HgMaterialInstance(url.originalArgument(), userName, branch, UUID.randomUUID().toString());\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n if (isNotBlank(branch)) {\n parameters.put(\"branch\", branch);\n }\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n parameters.put(\"url\", url);\n }", " private HgCommand getHg(File baseDir) {\n InMemoryStreamConsumer output =\n ProcessOutputStreamConsumer.inMemoryConsumer();\n HgCommand hgCommand = null;\n try {\n hgCommand = hg(baseDir, output);\n } catch (Exception e) {\n bomb(e.getMessage() + \" \" + output.getStdError(), e);\n }", " return hgCommand;\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n try {\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url.forDisplay()));\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n hg(workingDir, outputStreamConsumer).updateTo(revision, outputStreamConsumer);\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public void add(File baseDir, ProcessOutputStreamConsumer outputStreamConsumer, File file) throws Exception {\n hg(baseDir, outputStreamConsumer).add(outputStreamConsumer, file);\n }", " public void commit(File baseDir, ProcessOutputStreamConsumer consumer, String comment, String username)\n throws Exception {\n hg(baseDir, consumer).commit(consumer, comment, username);\n }", " public void push(File baseDir, ProcessOutputStreamConsumer consumer) throws Exception {\n hg(baseDir, consumer).push(consumer);\n }", " boolean isVersionOneDotZeroOrHigher(String hgout) {\n String hgVersion = parseHgVersion(hgout);\n Float aFloat = NumberUtils.createFloat(hgVersion.subSequence(0, 3).toString());\n return aFloat >= 1;\n }", " private String parseHgVersion(String hgOut) {\n String[] lines = hgOut.split(\"\\n\");\n String firstLine = lines[0];\n Matcher m = HG_VERSION_PATTERN.matcher(firstLine);\n if (m.matches()) {\n return m.group(1);\n } else {\n throw bomb(\"can not parse hgout : \" + hgOut);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n HgCommand hgCommand = new HgCommand(null, null, null, null, secrets());\n try {\n hgCommand.checkConnection(new HgUrlArgument(urlForCommandLine()));\n return ValidationBean.valid();\n } catch (Exception e) {\n try {\n return handleException(e, hgCommand.version());\n } catch (Exception ex) {\n return ValidationBean.notValid(ERR_NO_HG_INSTALLED);\n }\n }\n }", " ValidationBean handleException(Exception e, HgVersion version) {\n ValidationBean defaultResponse = ValidationBean.notValid(\n \"Repository \" + url.forDisplay() + \" not found!\" + \" : \\n\" + e.getMessage());\n try {\n if (version.isOlderThanOneDotZero()) {\n return ValidationBean.notValid(ERROR_OLD_VERSION + version.toString());\n } else {\n return defaultResponse;\n }\n } catch (Exception e1) {\n LOGGER.debug(\"Problem validating HG\", e);\n return defaultResponse;\n }\n }", "\n private HgCommand hg(File workingFolder, ConsoleOutputStreamConsumer outputStreamConsumer) throws Exception {\n UrlArgument urlArgument = new HgUrlArgument(urlForCommandLine());\n HgCommand hgCommand = new HgCommand(getFingerprint(), workingFolder, getBranch(), urlArgument.forCommandLine(), secrets());\n if (!isHgRepository(workingFolder) || isRepositoryChanged(hgCommand)) {\n LOGGER.debug(\"Invalid hg working copy or repository changed. Delete folder: {}\", workingFolder);\n FileUtils.deleteQuietly(workingFolder);\n }\n if (!workingFolder.exists()) {\n createParentFolderIfNotExist(workingFolder);\n int returnValue = hgCommand.clone(outputStreamConsumer, urlArgument);\n bombIfFailedToRunCommandLine(returnValue, \"Failed to run hg clone command\");\n }\n return hgCommand;\n }", " protected List<SecretString> secrets() {\n SecretString secretSubstitution = line -> line.replace(urlForCommandLine(), getUriForDisplay());\n return Collections.singletonList(secretSubstitution);\n }", " private boolean isHgRepository(File workingFolder) {\n return new File(workingFolder, \".hg\").isDirectory();\n }", " private boolean isRepositoryChanged(HgCommand hgCommand) {\n ConsoleResult result = hgCommand.workingRepositoryUrl();\n return !MaterialUrl.sameUrl(url.defaultRemoteUrl(), new HgUrlArgument(result.outputAsString()).defaultRemoteUrl());\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n try {\n if (credentialsAreNotProvided()) {\n return this.url.originalArgument();\n }", " return new URIBuilder(this.url.originalArgument())\n .setUserInfo(new UrlUserInfo(this.userName, this.passwordForCommandLine()).asString())\n .build().toString();", " } catch (URISyntaxException e) {\n return this.url.originalArgument();\n }\n }", " private boolean credentialsAreNotProvided() {\n return isAllBlank(this.userName, this.getPassword());\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " public HgUrlArgument getHgUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s\", url.forDisplay());\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " HgMaterial that = (HgMaterial) o;", " if (url != null ? !url.equals(that.url) : that.url != null) {\n return false;\n }", " if (branch != null ? !branch.equals(that.branch) : that.branch != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (branch != null ? branch.hashCode() : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return getUrlArgument().forDisplay();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Mercurial\";\n }", " @Override\n public String getShortRevision(String revision) {\n if (revision == null) return null;\n if (revision.length() < 12) return revision;\n return revision.substring(0, 12);\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"mercurial\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n materialMap.put(\"mercurial-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return HgMaterialInstance.class;\n }", " @Override\n public String toString() {\n return \"HgMaterial{\" +\n \"url=\" + url +\n '}';\n }", " public void setBranch(String branch) {\n this.branch = branch;\n }", "\n public String getBranch() {\n if (isNotBlank(branch)) {\n return branch;\n }", " return getBranchFromUrl();\n }", " private String getBranchFromUrl() {\n String[] componentsOfUrl = StringUtils.split(url.originalArgument(), HgUrlArgument.DOUBLE_HASH);\n if (componentsOfUrl.length > 1) {\n return componentsOfUrl[1];\n }\n return HG_DEFAULT_BRANCH;\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n setVariableWithName(environmentVariableContext, getBranch(), GitMaterial.GO_MATERIAL_BRANCH);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.perforce;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.perforce.P4Client;\nimport com.thoughtworks.go.domain.materials.perforce.P4MaterialInstance;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.FileUtil;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.SystemUtil;\nimport com.thoughtworks.go.util.TempFiles;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.io.FileUtils;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static java.lang.Long.parseLong;\nimport static java.lang.String.format;\nimport static java.nio.charset.StandardCharsets.UTF_8;", "public class P4Material extends ScmMaterial implements PasswordEncrypter, PasswordAwareMaterial {\n private String serverAndPort;\n private Boolean useTickets = false;\n private P4MaterialView view;", " // Database stuff\n //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"P4Material\";\n", " private P4Material(GoCipher goCipher) {\n super(TYPE, goCipher);\n }", " public P4Material(String serverAndPort, String view, GoCipher goCipher) {\n this(goCipher);", " bombIfNull(serverAndPort, \"null serverAndPort\");\n this.serverAndPort = serverAndPort;\n setView(view);\n }\n", " public P4Material(String serverAndPort, String view) {\n this(serverAndPort, view, new GoCipher());\n }", " public P4Material(String url, String view, String userName) {\n this(url, view);", " this.userName = userName;\n }\n", " public P4Material(String url, String view, String userName, String folder) {\n this(url, view, userName, folder, new GoCipher());\n }\n", " public P4Material(P4MaterialConfig config) {", " this(config.getUrl(), config.getView(), config.getUserName(), config.getFolder(), config.getGoCipher());", " this.name = config.getName();\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n setPassword(config.getPassword());\n this.useTickets = config.getUseTickets();\n }\n", " private P4Material(String serverAndPort, String view, String userName, String folder, GoCipher goCipher) {\n this(goCipher);", " bombIfNull(serverAndPort, \"null serverAndPort\");\n this.serverAndPort = serverAndPort;\n setView(view);\n this.userName = userName;\n this.folder = folder;\n }", " @Override\n public MaterialConfig config() {\n P4MaterialConfig p4MaterialConfig = new P4MaterialConfig();\n p4MaterialConfig.setServerAndPort(this.serverAndPort);\n p4MaterialConfig.setUserName(this.userName);\n p4MaterialConfig.setPassword(getPassword());\n p4MaterialConfig.setUseTickets(this.useTickets);\n p4MaterialConfig.setView(view == null ? null : view.getValue());\n p4MaterialConfig.setName(this.name);\n p4MaterialConfig.setAutoUpdate(this.autoUpdate);\n p4MaterialConfig.setFilter(this.filter);\n p4MaterialConfig.setInvertFilter(this.invertFilter);\n p4MaterialConfig.setFolder(this.folder);\n return p4MaterialConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir));\n return p4.latestChange();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir));\n return p4.changesSince(revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new P4MaterialInstance(serverAndPort, userName, view.getValue(), useTickets, UUID.randomUUID().toString());\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, serverAndPort);\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"view\", view.getValue());\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n appendCriteria(parameters);\n }", " protected P4Client getP4(File baseDir) {\n InMemoryStreamConsumer outputConsumer = inMemoryConsumer();\n P4Client p4 = null;\n try {\n p4 = p4(baseDir, outputConsumer);\n } catch (Exception e) {\n bomb(e.getMessage() + \" \" + outputConsumer.getStdError(), e);\n }\n return p4;\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n boolean cleaned = cleanDirectoryIfRepoChanged(workingDir, outputConsumer);\n String revision = revisionContext.getLatestRevision().getRevision();\n try {\n outputConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision, serverAndPort));\n p4(workingDir, outputConsumer).sync(parseLong(revision), cleaned, outputConsumer);\n outputConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n File baseDir = new TempFiles().createUniqueFolder(\"for-p4\");\n try {\n getP4(baseDir).checkConnection();\n return ValidationBean.valid();\n } catch (Exception e) {\n return ValidationBean.notValid(\"Unable to connect to server \" + serverAndPort + \" : \\n\" + e.getMessage());\n } finally {\n FileUtils.deleteQuietly(baseDir);\n }\n }", " public String getServerAndPort() {\n return serverAndPort;\n }", " public String getView() {\n return view == null ? null : view.getValue();\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return serverAndPort;\n }", " @Override\n public String urlForCommandLine() {\n return serverAndPort;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(serverAndPort);\n }", " @Override\n public String getLongDescription() {\n return format(\"URL: %s, View: %s, Username: %s\", serverAndPort, view.getValue(), userName);\n }", " P4Client p4(File baseDir, ConsoleOutputStreamConsumer consumer) throws Exception {\n return _p4(baseDir, consumer, true);\n }", " /**\n * not for use externally, created for testing convenience\n */\n P4Client _p4(File workDir, ConsoleOutputStreamConsumer consumer, boolean failOnError) throws Exception {\n String clientName = clientName(workDir);\n return P4Client.fromServerAndPort(getFingerprint(), serverAndPort, userName, passwordForCommandLine(), clientName, this.useTickets, workDir, p4view(clientName), consumer, failOnError);\n }", " @Override\n public void populateAgentSideEnvironmentContext(EnvironmentVariableContext environmentVariableContext, File baseDir) {\n super.populateAgentSideEnvironmentContext(environmentVariableContext, baseDir);\n setVariableWithName(environmentVariableContext, clientName(workingdir(baseDir)), \"GO_P4_CLIENT\");\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"perforce\");\n Map<String, Object> configurationMap = new HashMap<>();\n configurationMap.put(\"url\", serverAndPort);\n configurationMap.put(\"username\", userName);\n if (addSecureFields) {\n configurationMap.put(\"password\", getPassword());\n }\n configurationMap.put(\"view\", getView());\n configurationMap.put(\"use-tickets\", useTickets);\n materialMap.put(\"perforce-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return P4MaterialInstance.class;\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " P4Material that = (P4Material) o;", " if (serverAndPort != null ? !serverAndPort.equals(that.serverAndPort) : that.serverAndPort != null) {\n return false;\n }\n if (useTickets != null ? !useTickets.equals(that.useTickets) : that.useTickets != null) {\n return false;\n }\n if (view != null ? !view.equals(that.view) : that.view != null) {\n return false;\n }", " if (userName != null ? !userName.equals(that.userName) : that.userName != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (serverAndPort != null ? serverAndPort.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (useTickets != null ? useTickets.hashCode() : 0);\n result = 31 * result + (view != null ? view.hashCode() : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return getServerAndPort();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Perforce\";\n }", " public String p4view(String clientName) {\n return view.viewUsing(clientName);\n }", " public String clientName(File workingDir) {\n String hash = FileUtil.filesystemSafeFileHash(workingDir);\n return \"cruise-\" + SystemUtil.getLocalhostName()\n + \"-\" + workingDir.getName()\n + \"-\" + hash;\n }", " private boolean cleanDirectoryIfRepoChanged(File workingDirectory, ConsoleOutputStreamConsumer outputConsumer) {\n boolean cleaned = false;\n try {\n String p4RepoId = p4RepoId();\n File file = new File(workingDirectory, \".cruise_p4repo\");\n if (!file.exists()) {\n FileUtils.writeStringToFile(file, p4RepoId, UTF_8);\n return true;\n }", " String existingRepoId = FileUtils.readFileToString(file, UTF_8);\n if (!p4RepoId.equals(existingRepoId)) {\n outputConsumer.stdOutput(format(\"[%s] Working directory has changed. Deleting and re-creating it.\", GoConstants.PRODUCT_NAME));\n FileUtils.deleteDirectory(workingDirectory);\n workingDirectory.mkdirs();\n FileUtils.writeStringToFile(file, p4RepoId, UTF_8);\n cleaned = true;\n }\n return cleaned;\n } catch (IOException e) {\n throw bomb(e);\n }\n }", " private String p4RepoId() {\n return hasUser() ? userName + \"@\" + serverAndPort : serverAndPort;\n }", " private boolean hasUser() {\n return userName != null && !userName.trim().isEmpty();\n }", " public boolean getUseTickets() {\n return this.useTickets;\n }", " public void setUseTickets(boolean useTickets) {\n this.useTickets = useTickets;\n }", " @Override\n public String toString() {\n return \"P4Material{\" +\n \"serverAndPort='\" + serverAndPort + '\\'' +\n \", userName='\" + userName + '\\'' +\n \", view=\" + view.getValue() +\n '}';\n }", " public void setUsername(String userName) {\n this.userName = userName;\n }", " private void setView(String viewStr) {\n this.view = new P4MaterialView(viewStr);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.perforce;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.perforce.P4Client;\nimport com.thoughtworks.go.domain.materials.perforce.P4MaterialInstance;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.FileUtil;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.SystemUtil;\nimport com.thoughtworks.go.util.TempFiles;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.InMemoryStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.io.FileUtils;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static com.thoughtworks.go.util.ExceptionUtils.bomb;\nimport static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;\nimport static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;\nimport static java.lang.Long.parseLong;\nimport static java.lang.String.format;\nimport static java.nio.charset.StandardCharsets.UTF_8;", "public class P4Material extends ScmMaterial implements PasswordEncrypter, PasswordAwareMaterial {\n private String serverAndPort;\n private Boolean useTickets = false;\n private P4MaterialView view;", " // Database stuff\n //TODO: use iBatis to set the type for us, and we can get rid of this field.\n public static final String TYPE = \"P4Material\";\n", " private P4Material() {\n super(TYPE);\n }", " public P4Material(String serverAndPort, String view) {\n this();", " bombIfNull(serverAndPort, \"null serverAndPort\");\n this.serverAndPort = serverAndPort;\n setView(view);\n }\n", " public P4Material(String serverAndPort, String view, String userName) {\n this(serverAndPort, view);", " this.userName = userName;\n }\n", "", " public P4Material(P4MaterialConfig config) {", " this(config.getUrl(), config.getView(), config.getUserName(), config.getFolder());", " this.name = config.getName();\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n setPassword(config.getPassword());\n this.useTickets = config.getUseTickets();\n }\n", " public P4Material(String serverAndPort, String view, String userName, String folder) {\n this();", " bombIfNull(serverAndPort, \"null serverAndPort\");\n this.serverAndPort = serverAndPort;\n setView(view);\n this.userName = userName;\n this.folder = folder;\n }", " @Override\n public MaterialConfig config() {\n P4MaterialConfig p4MaterialConfig = new P4MaterialConfig();\n p4MaterialConfig.setServerAndPort(this.serverAndPort);\n p4MaterialConfig.setUserName(this.userName);\n p4MaterialConfig.setPassword(getPassword());\n p4MaterialConfig.setUseTickets(this.useTickets);\n p4MaterialConfig.setView(view == null ? null : view.getValue());\n p4MaterialConfig.setName(this.name);\n p4MaterialConfig.setAutoUpdate(this.autoUpdate);\n p4MaterialConfig.setFilter(this.filter);\n p4MaterialConfig.setInvertFilter(this.invertFilter);\n p4MaterialConfig.setFolder(this.folder);\n return p4MaterialConfig;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir));\n return p4.latestChange();\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir));\n return p4.changesSince(revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new P4MaterialInstance(serverAndPort, userName, view.getValue(), useTickets, UUID.randomUUID().toString());\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, serverAndPort);\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"view\", view.getValue());\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n appendCriteria(parameters);\n }", " protected P4Client getP4(File baseDir) {\n InMemoryStreamConsumer outputConsumer = inMemoryConsumer();\n P4Client p4 = null;\n try {\n p4 = p4(baseDir, outputConsumer);\n } catch (Exception e) {\n bomb(e.getMessage() + \" \" + outputConsumer.getStdError(), e);\n }\n return p4;\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n boolean cleaned = cleanDirectoryIfRepoChanged(workingDir, outputConsumer);\n String revision = revisionContext.getLatestRevision().getRevision();\n try {\n outputConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision, serverAndPort));\n p4(workingDir, outputConsumer).sync(parseLong(revision), cleaned, outputConsumer);\n outputConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n } catch (Exception e) {\n bomb(e);\n }\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n File baseDir = new TempFiles().createUniqueFolder(\"for-p4\");\n try {\n getP4(baseDir).checkConnection();\n return ValidationBean.valid();\n } catch (Exception e) {\n return ValidationBean.notValid(\"Unable to connect to server \" + serverAndPort + \" : \\n\" + e.getMessage());\n } finally {\n FileUtils.deleteQuietly(baseDir);\n }\n }", " public String getServerAndPort() {\n return serverAndPort;\n }", " public String getView() {\n return view == null ? null : view.getValue();\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return serverAndPort;\n }", " @Override\n public String urlForCommandLine() {\n return serverAndPort;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(serverAndPort);\n }", " @Override\n public String getLongDescription() {\n return format(\"URL: %s, View: %s, Username: %s\", serverAndPort, view.getValue(), userName);\n }", " P4Client p4(File baseDir, ConsoleOutputStreamConsumer consumer) throws Exception {\n return _p4(baseDir, consumer, true);\n }", " /**\n * not for use externally, created for testing convenience\n */\n P4Client _p4(File workDir, ConsoleOutputStreamConsumer consumer, boolean failOnError) throws Exception {\n String clientName = clientName(workDir);\n return P4Client.fromServerAndPort(getFingerprint(), serverAndPort, userName, passwordForCommandLine(), clientName, this.useTickets, workDir, p4view(clientName), consumer, failOnError);\n }", " @Override\n public void populateAgentSideEnvironmentContext(EnvironmentVariableContext environmentVariableContext, File baseDir) {\n super.populateAgentSideEnvironmentContext(environmentVariableContext, baseDir);\n setVariableWithName(environmentVariableContext, clientName(workingdir(baseDir)), \"GO_P4_CLIENT\");\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"perforce\");\n Map<String, Object> configurationMap = new HashMap<>();\n configurationMap.put(\"url\", serverAndPort);\n configurationMap.put(\"username\", userName);\n if (addSecureFields) {\n configurationMap.put(\"password\", getPassword());\n }\n configurationMap.put(\"view\", getView());\n configurationMap.put(\"use-tickets\", useTickets);\n materialMap.put(\"perforce-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return P4MaterialInstance.class;\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " P4Material that = (P4Material) o;", " if (serverAndPort != null ? !serverAndPort.equals(that.serverAndPort) : that.serverAndPort != null) {\n return false;\n }\n if (useTickets != null ? !useTickets.equals(that.useTickets) : that.useTickets != null) {\n return false;\n }\n if (view != null ? !view.equals(that.view) : that.view != null) {\n return false;\n }", " if (userName != null ? !userName.equals(that.userName) : that.userName != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (serverAndPort != null ? serverAndPort.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (useTickets != null ? useTickets.hashCode() : 0);\n result = 31 * result + (view != null ? view.hashCode() : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return getServerAndPort();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Perforce\";\n }", " public String p4view(String clientName) {\n return view.viewUsing(clientName);\n }", " public String clientName(File workingDir) {\n String hash = FileUtil.filesystemSafeFileHash(workingDir);\n return \"cruise-\" + SystemUtil.getLocalhostName()\n + \"-\" + workingDir.getName()\n + \"-\" + hash;\n }", " private boolean cleanDirectoryIfRepoChanged(File workingDirectory, ConsoleOutputStreamConsumer outputConsumer) {\n boolean cleaned = false;\n try {\n String p4RepoId = p4RepoId();\n File file = new File(workingDirectory, \".cruise_p4repo\");\n if (!file.exists()) {\n FileUtils.writeStringToFile(file, p4RepoId, UTF_8);\n return true;\n }", " String existingRepoId = FileUtils.readFileToString(file, UTF_8);\n if (!p4RepoId.equals(existingRepoId)) {\n outputConsumer.stdOutput(format(\"[%s] Working directory has changed. Deleting and re-creating it.\", GoConstants.PRODUCT_NAME));\n FileUtils.deleteDirectory(workingDirectory);\n workingDirectory.mkdirs();\n FileUtils.writeStringToFile(file, p4RepoId, UTF_8);\n cleaned = true;\n }\n return cleaned;\n } catch (IOException e) {\n throw bomb(e);\n }\n }", " private String p4RepoId() {\n return hasUser() ? userName + \"@\" + serverAndPort : serverAndPort;\n }", " private boolean hasUser() {\n return userName != null && !userName.trim().isEmpty();\n }", " public boolean getUseTickets() {\n return this.useTickets;\n }", " public void setUseTickets(boolean useTickets) {\n this.useTickets = useTickets;\n }", " @Override\n public String toString() {\n return \"P4Material{\" +\n \"serverAndPort='\" + serverAndPort + '\\'' +\n \", userName='\" + userName + '\\'' +\n \", view=\" + view.getValue() +\n '}';\n }", " public void setUsername(String userName) {\n this.userName = userName;\n }", " private void setView(String viewStr) {\n this.view = new P4MaterialView(viewStr);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.svn;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.svn.*;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.io.FileUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static java.lang.String.format;", "/**\n * @understands configuration for subversion\n */\npublic class SvnMaterial extends ScmMaterial implements PasswordEncrypter, PasswordAwareMaterial {\n private static final Logger LOGGER = LoggerFactory.getLogger(SvnMaterial.class);\n private UrlArgument url;\n private boolean checkExternals;\n private transient Subversion svnLazyLoaded;", " public static final String TYPE = \"SvnMaterial\";\n", " private SvnMaterial(GoCipher goCipher) {\n super(\"SvnMaterial\", goCipher);\n }\n", " public SvnMaterial(String url, String userName, String password, boolean checkExternals) {\n this(url, userName, password, checkExternals, new GoCipher());\n }", " public SvnMaterial(Subversion svn) {\n this(svn.getUrl().originalArgument(), svn.getUserName(), svn.getPassword(), svn.isCheckExternals());\n this.svnLazyLoaded = svn;\n }", " public SvnMaterial(String url, String userName, String password, boolean checkExternals, String folder) {\n this(url, userName, password, checkExternals);\n this.folder = folder;\n }", " public SvnMaterial(SvnMaterialConfig config) {\n this(config.getUrl(), config.getUserName(), config.getPassword(), config.isCheckExternals(), config.getGoCipher());\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.folder = config.getFolder();\n this.name = config.getName();\n }", " public SvnMaterial(String url, String userName, String password, boolean checkExternals, GoCipher goCipher) {", " super(\"SvnMaterial\", goCipher);", " bombIfNull(url, \"null url\");\n setUrl(url);\n this.userName = userName;\n setPassword(password);\n this.checkExternals = checkExternals;\n }", " @Override\n public MaterialConfig config() {\n SvnMaterialConfig svnMaterialConfig = new SvnMaterialConfig();\n svnMaterialConfig.setUrl(this.url.originalArgument());\n svnMaterialConfig.setUserName(this.userName);\n svnMaterialConfig.setPassword(getPassword());\n svnMaterialConfig.setCheckExternals(this.checkExternals);\n svnMaterialConfig.setAutoUpdate(this.autoUpdate);\n svnMaterialConfig.setFilter(this.filter);\n svnMaterialConfig.setInvertFilter(this.invertFilter);\n svnMaterialConfig.setFolder(this.folder);\n svnMaterialConfig.setName(this.name);\n return svnMaterialConfig;\n }", " private Subversion svn() {\n if (svnLazyLoaded == null || !svnLazyLoaded.getUrl().equals(url)) {\n svnLazyLoaded = new SvnCommand(getFingerprint(), url.forCommandLine(), userName, passwordForCommandLine(), checkExternals);\n }\n return svnLazyLoaded;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n return svn().latestModification();\n }", " public List<Modification> modificationsSince(File workingDirectory, Revision revision, final SubprocessExecutionContext execCtx) {\n return svn().modificationsSince(new SubversionRevision(revision.getRevision()));\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new SvnMaterialInstance(url.originalArgument(), userName, UUID.randomUUID().toString(), checkExternals);\n }", " @Override\n protected void appendCriteria(Map parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"checkExternals\", checkExternals);\n }", " @Override\n protected void appendAttributes(Map parameters) {\n parameters.put(ScmMaterialConfig.URL, url);\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"checkExternals\", checkExternals);\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n LOGGER.debug(\"Updating to revision: {} in workingdirectory {}\", revision, workingDir);\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url));\n boolean shouldDoFreshCheckout = !workingDir.isDirectory() || isRepositoryChanged(workingDir);\n if (shouldDoFreshCheckout) {\n freshCheckout(outputStreamConsumer, new SubversionRevision(revision), workingDir);\n } else {\n cleanupAndUpdate(outputStreamConsumer, new SubversionRevision(revision), workingDir);\n }\n LOGGER.debug(\"done with update\");\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n }", " public boolean isRepositoryChanged(File workingFolder) {\n try {\n File file = new File(workingFolder, \".svn\");\n if (workingFolder.isDirectory() && file.exists() && file.isDirectory()) {\n String workingUrl = svn().workingRepositoryUrl(workingFolder);\n return !MaterialUrl.sameUrl(url.toString(), workingUrl);\n } else {\n return true;\n }\n } catch (IOException e) {\n return true;\n }\n }", " public void freshCheckout(ConsoleOutputStreamConsumer outputStreamConsumer, SubversionRevision revision,\n File workingFolder) {\n if (workingFolder.isDirectory()) {\n FileUtils.deleteQuietly(workingFolder);\n }\n LOGGER.trace(\"Checking out to revision {} in {}\", revision, workingFolder);\n createParentFolderIfNotExist(workingFolder);\n svn().checkoutTo(outputStreamConsumer, workingFolder, revision);\n }", " public void cleanupAndUpdate(ConsoleOutputStreamConsumer outputStreamConsumer, SubversionRevision revision,\n File workingFolder) {\n try {\n svn().cleanupAndRevert(outputStreamConsumer, workingFolder);\n } catch (Exception e) {\n String message = \"Failed to do cleanup and revert in \" + workingFolder.getAbsolutePath();\n LOGGER.error(message);\n LOGGER.debug(message, e);\n }\n LOGGER.trace(\"Updating to revision {} on {}\", revision, workingFolder);\n svn().updateTo(outputStreamConsumer, workingFolder, revision);\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " SvnMaterial that = (SvnMaterial) o;", " if (checkExternals != that.checkExternals) {\n return false;\n }\n if (url != null ? !url.equals(that.url) : that.url != null) {\n return false;\n }", " if (userName != null ? !userName.equals(that.userName) : that.userName != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (checkExternals ? 1 : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return url == null ? null : url.forDisplay();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Subversion\";\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"svn\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n configurationMap.put(\"password\", getPassword());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"username\", userName);\n configurationMap.put(\"check-externals\", checkExternals);\n materialMap.put(\"svn-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return SvnMaterialInstance.class;\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n return svn().checkConnection();\n }", " @Override\n public String getUrl() {\n return url == null ? null : url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n return url.forCommandLine();\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Username: %s, CheckExternals: %s\", url.forDisplay(), userName, checkExternals);\n }", " public void setUrl(String url) {\n this.url = new UrlArgument(url);\n }", " @Override\n public boolean isCheckExternals() {\n return checkExternals;\n }", " public void add(ConsoleOutputStreamConsumer outputStreamConsumer, File file) {\n svn().add(outputStreamConsumer, file);\n }", " public void commit(ConsoleOutputStreamConsumer outputStreamConsumer, File workingDir, String message) {\n svn().commit(outputStreamConsumer, workingDir, message);\n }", " @Override\n public boolean matches(String name, String regex) {\n if (!regex.startsWith(\"/\")) {\n regex = \"/\" + regex;\n }\n return name.matches(regex);\n }", " @Override\n public String toString() {\n return \"SvnMaterial{\" +\n \"url=\" + url +\n \", userName='\" + userName + '\\'' +\n \", checkExternals=\" + checkExternals +\n '}';\n }", " /**\n * @deprecated used only in tests - we need to disentangle this\n */\n public static SvnMaterial createSvnMaterialWithMock(Subversion svn) {\n return new SvnMaterial(svn);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.svn;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.svn.*;\nimport com.thoughtworks.go.security.GoCipher;\nimport com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.io.FileUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;\nimport static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;\nimport static java.lang.String.format;", "/**\n * @understands configuration for subversion\n */\npublic class SvnMaterial extends ScmMaterial implements PasswordEncrypter, PasswordAwareMaterial {\n private static final Logger LOGGER = LoggerFactory.getLogger(SvnMaterial.class);\n private UrlArgument url;\n private boolean checkExternals;\n private transient Subversion svnLazyLoaded;", " public static final String TYPE = \"SvnMaterial\";\n", "", " public SvnMaterial(String url, String userName, String password, boolean checkExternals) {\n this(url, userName, password, checkExternals, new GoCipher());\n }", " public SvnMaterial(Subversion svn) {\n this(svn.getUrl().originalArgument(), svn.getUserName(), svn.getPassword(), svn.isCheckExternals());\n this.svnLazyLoaded = svn;\n }", " public SvnMaterial(String url, String userName, String password, boolean checkExternals, String folder) {\n this(url, userName, password, checkExternals);\n this.folder = folder;\n }", " public SvnMaterial(SvnMaterialConfig config) {\n this(config.getUrl(), config.getUserName(), config.getPassword(), config.isCheckExternals(), config.getGoCipher());\n this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.folder = config.getFolder();\n this.name = config.getName();\n }", " public SvnMaterial(String url, String userName, String password, boolean checkExternals, GoCipher goCipher) {", " super(\"SvnMaterial\");", " bombIfNull(url, \"null url\");\n setUrl(url);\n this.userName = userName;\n setPassword(password);\n this.checkExternals = checkExternals;\n }", " @Override\n public MaterialConfig config() {\n SvnMaterialConfig svnMaterialConfig = new SvnMaterialConfig();\n svnMaterialConfig.setUrl(this.url.originalArgument());\n svnMaterialConfig.setUserName(this.userName);\n svnMaterialConfig.setPassword(getPassword());\n svnMaterialConfig.setCheckExternals(this.checkExternals);\n svnMaterialConfig.setAutoUpdate(this.autoUpdate);\n svnMaterialConfig.setFilter(this.filter);\n svnMaterialConfig.setInvertFilter(this.invertFilter);\n svnMaterialConfig.setFolder(this.folder);\n svnMaterialConfig.setName(this.name);\n return svnMaterialConfig;\n }", " private Subversion svn() {\n if (svnLazyLoaded == null || !svnLazyLoaded.getUrl().equals(url)) {\n svnLazyLoaded = new SvnCommand(getFingerprint(), url.forCommandLine(), userName, passwordForCommandLine(), checkExternals);\n }\n return svnLazyLoaded;\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n return svn().latestModification();\n }", " public List<Modification> modificationsSince(File workingDirectory, Revision revision, final SubprocessExecutionContext execCtx) {\n return svn().modificationsSince(new SubversionRevision(revision.getRevision()));\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new SvnMaterialInstance(url.originalArgument(), userName, UUID.randomUUID().toString(), checkExternals);\n }", " @Override\n protected void appendCriteria(Map parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"checkExternals\", checkExternals);\n }", " @Override\n protected void appendAttributes(Map parameters) {\n parameters.put(ScmMaterialConfig.URL, url);\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(\"checkExternals\", checkExternals);\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n LOGGER.debug(\"Updating to revision: {} in workingdirectory {}\", revision, workingDir);\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url));\n boolean shouldDoFreshCheckout = !workingDir.isDirectory() || isRepositoryChanged(workingDir);\n if (shouldDoFreshCheckout) {\n freshCheckout(outputStreamConsumer, new SubversionRevision(revision), workingDir);\n } else {\n cleanupAndUpdate(outputStreamConsumer, new SubversionRevision(revision), workingDir);\n }\n LOGGER.debug(\"done with update\");\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n }", " public boolean isRepositoryChanged(File workingFolder) {\n try {\n File file = new File(workingFolder, \".svn\");\n if (workingFolder.isDirectory() && file.exists() && file.isDirectory()) {\n String workingUrl = svn().workingRepositoryUrl(workingFolder);\n return !MaterialUrl.sameUrl(url.toString(), workingUrl);\n } else {\n return true;\n }\n } catch (IOException e) {\n return true;\n }\n }", " public void freshCheckout(ConsoleOutputStreamConsumer outputStreamConsumer, SubversionRevision revision,\n File workingFolder) {\n if (workingFolder.isDirectory()) {\n FileUtils.deleteQuietly(workingFolder);\n }\n LOGGER.trace(\"Checking out to revision {} in {}\", revision, workingFolder);\n createParentFolderIfNotExist(workingFolder);\n svn().checkoutTo(outputStreamConsumer, workingFolder, revision);\n }", " public void cleanupAndUpdate(ConsoleOutputStreamConsumer outputStreamConsumer, SubversionRevision revision,\n File workingFolder) {\n try {\n svn().cleanupAndRevert(outputStreamConsumer, workingFolder);\n } catch (Exception e) {\n String message = \"Failed to do cleanup and revert in \" + workingFolder.getAbsolutePath();\n LOGGER.error(message);\n LOGGER.debug(message, e);\n }\n LOGGER.trace(\"Updating to revision {} on {}\", revision, workingFolder);\n svn().updateTo(outputStreamConsumer, workingFolder, revision);\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " SvnMaterial that = (SvnMaterial) o;", " if (checkExternals != that.checkExternals) {\n return false;\n }\n if (url != null ? !url.equals(that.url) : that.url != null) {\n return false;\n }", " if (userName != null ? !userName.equals(that.userName) : that.userName != null) {\n return false;\n }", " return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (checkExternals ? 1 : 0);\n return result;\n }", " @Override\n protected String getLocation() {\n return url == null ? null : url.forDisplay();\n }", " @Override\n public String getTypeForDisplay() {\n return \"Subversion\";\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"svn\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.forCommandLine());\n configurationMap.put(\"password\", getPassword());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"username\", userName);\n configurationMap.put(\"check-externals\", checkExternals);\n materialMap.put(\"svn-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return SvnMaterialInstance.class;\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n return svn().checkConnection();\n }", " @Override\n public String getUrl() {\n return url == null ? null : url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n return url.forCommandLine();\n }", " @Override\n public UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Username: %s, CheckExternals: %s\", url.forDisplay(), userName, checkExternals);\n }", " public void setUrl(String url) {\n this.url = new UrlArgument(url);\n }", " @Override\n public boolean isCheckExternals() {\n return checkExternals;\n }", " public void add(ConsoleOutputStreamConsumer outputStreamConsumer, File file) {\n svn().add(outputStreamConsumer, file);\n }", " public void commit(ConsoleOutputStreamConsumer outputStreamConsumer, File workingDir, String message) {\n svn().commit(outputStreamConsumer, workingDir, message);\n }", " @Override\n public boolean matches(String name, String regex) {\n if (!regex.startsWith(\"/\")) {\n regex = \"/\" + regex;\n }\n return name.matches(regex);\n }", " @Override\n public String toString() {\n return \"SvnMaterial{\" +\n \"url=\" + url +\n \", userName='\" + userName + '\\'' +\n \", checkExternals=\" + checkExternals +\n '}';\n }", " /**\n * @deprecated used only in tests - we need to disentangle this\n */\n public static SvnMaterial createSvnMaterialWithMock(Subversion svn) {\n return new SvnMaterial(svn);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.tfs;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommand;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommandFactory;\nimport com.thoughtworks.go.domain.materials.tfs.TfsMaterialInstance;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.builder.ToStringBuilder;\nimport org.apache.commons.lang3.builder.ToStringStyle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isNotBlank;", "public class TfsMaterial extends ScmMaterial implements PasswordAwareMaterial, PasswordEncrypter {\n private static final Logger LOGGER = LoggerFactory.getLogger(TfsMaterial.class);", " public static final String TYPE = \"TfsMaterial\";\n public static final String GO_MATERIAL_DOMAIN = \"GO_MATERIAL_DOMAIN\";", " private UrlArgument url;\n private String domain = \"\";\n private String projectPath;\n", " public TfsMaterial(GoCipher goCipher) {\n super(TYPE, goCipher);\n }", " public TfsMaterial(GoCipher goCipher, UrlArgument url, String userName, String domain, String password, String projectPath) {\n this(goCipher);", " this.url = url;\n this.userName = userName;\n this.domain = domain;\n setPassword(password);\n this.projectPath = projectPath;\n }", " public TfsMaterial(TfsMaterialConfig config) {", " this(config.getGoCipher(), new UrlArgument(config.getUrl()), config.getUserName(), config.getDomain(), config.getPassword(), config.getProjectPath());", " this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.folder = config.getFolder();\n this.name = config.getName();\n }", " @Override\n public MaterialConfig config() {\n TfsMaterialConfig tfsMaterialConfig = new TfsMaterialConfig();\n tfsMaterialConfig.setUrl(this.url.originalArgument());\n tfsMaterialConfig.setUserName(this.userName);\n tfsMaterialConfig.setDomain(this.domain);\n tfsMaterialConfig.setPassword(getPassword());\n tfsMaterialConfig.setProjectPath(this.projectPath);\n tfsMaterialConfig.setAutoUpdate(this.autoUpdate);\n tfsMaterialConfig.setFilter(this.filter);\n tfsMaterialConfig.setInvertFilter(this.invertFilter);\n tfsMaterialConfig.setFolder(this.folder);\n tfsMaterialConfig.setName(this.name);\n return tfsMaterialConfig;\n }", " public String getDomain() {\n return domain;\n }", " public String getProjectPath() {\n return projectPath;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url == null ? null : url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n return url.forCommandLine();\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Username: %s, Domain: %s, ProjectPath: %s\", url.forDisplay(), userName, domain, projectPath);\n }", " @Override\n protected String getLocation() {\n return url == null ? null : url.forDisplay();\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(TfsMaterialConfig.DOMAIN, domain);\n parameters.put(TfsMaterialConfig.PROJECT_PATH, projectPath);\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n appendCriteria(parameters);\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n LOGGER.debug(\"[TFS] Updating to revision: {} in workingdirectory {}\", revision, workingDir);\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url));\n tfs(execCtx).checkout(workingDir, revision);\n LOGGER.debug(\"[TFS] done with update\");\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n }", " TfsCommand tfs(final SubprocessExecutionContext execCtx) {\n return new TfsCommandFactory().create(execCtx, url, domain, userName, passwordForCommandLine(), getFingerprint(), projectPath);\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n try {\n tfs(execCtx).checkConnection();\n return ValidationBean.valid();\n } catch (Exception e) {\n LOGGER.error(\"[TFS] Error during check connection\", e);\n return ValidationBean.notValid(e.getMessage());\n }\n }", " public List<Modification> latestModification(File workDir, final SubprocessExecutionContext execCtx) {\n return tfs(execCtx).latestModification(workDir);\n }", " public List<Modification> modificationsSince(File workDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return tfs(execCtx).modificationsSince(workDir, revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new TfsMaterialInstance(url.originalArgument(), userName, domain, projectPath, UUID.randomUUID().toString());\n }", " @Override\n public String getTypeForDisplay() {\n return \"Tfs\";\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"tfs\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.originalArgument());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"domain\", domain);\n configurationMap.put(\"username\", userName);\n if (addSecureFields) {\n configurationMap.put(\"password\", getPassword());\n }\n configurationMap.put(\"project-path\", projectPath);\n materialMap.put(\"tfs-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return TfsMaterialInstance.class;\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " TfsMaterial material = (TfsMaterial) o;", " if (projectPath != null ? !projectPath.equals(material.projectPath) : material.projectPath != null) {\n return false;\n }\n if (url != null ? !url.equals(material.url) : material.url != null) {\n return false;\n }\n if (domain != null ? !domain.equals(material.domain) : material.domain != null) {\n return false;\n }\n if (userName != null ? !userName.equals(material.userName) : material.userName != null) {\n return false;\n }\n return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (domain != null ? domain.hashCode() : 0);\n result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0);\n return result;\n }", " @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, true);\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n if (isNotBlank(domain)) {\n setVariableWithName(environmentVariableContext, domain, GO_MATERIAL_DOMAIN);\n }\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.config.materials.tfs;", "import com.thoughtworks.go.config.PasswordEncrypter;\nimport com.thoughtworks.go.config.materials.PasswordAwareMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.ScmMaterialConfig;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommand;\nimport com.thoughtworks.go.domain.materials.tfs.TfsCommandFactory;\nimport com.thoughtworks.go.domain.materials.tfs.TfsMaterialInstance;", "", "import com.thoughtworks.go.util.GoConstants;\nimport com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.EnvironmentVariableContext;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.apache.commons.lang3.builder.ToStringBuilder;\nimport org.apache.commons.lang3.builder.ToStringStyle;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;", "import java.io.File;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;", "import static java.lang.String.format;\nimport static org.apache.commons.lang3.StringUtils.isNotBlank;", "public class TfsMaterial extends ScmMaterial implements PasswordAwareMaterial, PasswordEncrypter {\n private static final Logger LOGGER = LoggerFactory.getLogger(TfsMaterial.class);", " public static final String TYPE = \"TfsMaterial\";\n public static final String GO_MATERIAL_DOMAIN = \"GO_MATERIAL_DOMAIN\";", " private UrlArgument url;\n private String domain = \"\";\n private String projectPath;\n", " public TfsMaterial() {\n super(TYPE);\n }", " public TfsMaterial(UrlArgument url, String userName, String domain, String password, String projectPath) {\n this();", " this.url = url;\n this.userName = userName;\n this.domain = domain;\n setPassword(password);\n this.projectPath = projectPath;\n }", " public TfsMaterial(TfsMaterialConfig config) {", " this(new UrlArgument(config.getUrl()), config.getUserName(), config.getDomain(), config.getPassword(), config.getProjectPath());", " this.autoUpdate = config.getAutoUpdate();\n this.filter = config.rawFilter();\n this.invertFilter = config.getInvertFilter();\n this.folder = config.getFolder();\n this.name = config.getName();\n }", " @Override\n public MaterialConfig config() {\n TfsMaterialConfig tfsMaterialConfig = new TfsMaterialConfig();\n tfsMaterialConfig.setUrl(this.url.originalArgument());\n tfsMaterialConfig.setUserName(this.userName);\n tfsMaterialConfig.setDomain(this.domain);\n tfsMaterialConfig.setPassword(getPassword());\n tfsMaterialConfig.setProjectPath(this.projectPath);\n tfsMaterialConfig.setAutoUpdate(this.autoUpdate);\n tfsMaterialConfig.setFilter(this.filter);\n tfsMaterialConfig.setInvertFilter(this.invertFilter);\n tfsMaterialConfig.setFolder(this.folder);\n tfsMaterialConfig.setName(this.name);\n return tfsMaterialConfig;\n }", " public String getDomain() {\n return domain;\n }", " public String getProjectPath() {\n return projectPath;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url == null ? null : url.originalArgument();\n }", " @Override\n public String urlForCommandLine() {\n return url.forCommandLine();\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return url;\n }", " @Override\n public String getLongDescription() {\n return String.format(\"URL: %s, Username: %s, Domain: %s, ProjectPath: %s\", url.forDisplay(), userName, domain, projectPath);\n }", " @Override\n protected String getLocation() {\n return url == null ? null : url.forDisplay();\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n parameters.put(ScmMaterialConfig.URL, url.originalArgument());\n parameters.put(ScmMaterialConfig.USERNAME, userName);\n parameters.put(TfsMaterialConfig.DOMAIN, domain);\n parameters.put(TfsMaterialConfig.PROJECT_PATH, projectPath);\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n appendCriteria(parameters);\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n Revision revision = revisionContext.getLatestRevision();\n File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);\n LOGGER.debug(\"[TFS] Updating to revision: {} in workingdirectory {}\", revision, workingDir);\n outputStreamConsumer.stdOutput(format(\"[%s] Start updating %s at revision %s from %s\", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url));\n tfs(execCtx).checkout(workingDir, revision);\n LOGGER.debug(\"[TFS] done with update\");\n outputStreamConsumer.stdOutput(format(\"[%s] Done.\\n\", GoConstants.PRODUCT_NAME));\n }", " TfsCommand tfs(final SubprocessExecutionContext execCtx) {\n return new TfsCommandFactory().create(execCtx, url, domain, userName, passwordForCommandLine(), getFingerprint(), projectPath);\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n try {\n tfs(execCtx).checkConnection();\n return ValidationBean.valid();\n } catch (Exception e) {\n LOGGER.error(\"[TFS] Error during check connection\", e);\n return ValidationBean.notValid(e.getMessage());\n }\n }", " public List<Modification> latestModification(File workDir, final SubprocessExecutionContext execCtx) {\n return tfs(execCtx).latestModification(workDir);\n }", " public List<Modification> modificationsSince(File workDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return tfs(execCtx).modificationsSince(workDir, revision);\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new TfsMaterialInstance(url.originalArgument(), userName, domain, projectPath, UUID.randomUUID().toString());\n }", " @Override\n public String getTypeForDisplay() {\n return \"Tfs\";\n }", " @Override\n public Map<String, Object> getAttributes(boolean addSecureFields) {\n Map<String, Object> materialMap = new HashMap<>();\n materialMap.put(\"type\", \"tfs\");\n Map<String, Object> configurationMap = new HashMap<>();\n if (addSecureFields) {\n configurationMap.put(\"url\", url.originalArgument());\n } else {\n configurationMap.put(\"url\", url.forDisplay());\n }\n configurationMap.put(\"domain\", domain);\n configurationMap.put(\"username\", userName);\n if (addSecureFields) {\n configurationMap.put(\"password\", getPassword());\n }\n configurationMap.put(\"project-path\", projectPath);\n materialMap.put(\"tfs-configuration\", configurationMap);\n return materialMap;\n }", " @Override\n public Class getInstanceType() {\n return TfsMaterialInstance.class;\n }", " @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n if (!super.equals(o)) {\n return false;\n }", " TfsMaterial material = (TfsMaterial) o;", " if (projectPath != null ? !projectPath.equals(material.projectPath) : material.projectPath != null) {\n return false;\n }\n if (url != null ? !url.equals(material.url) : material.url != null) {\n return false;\n }\n if (domain != null ? !domain.equals(material.domain) : material.domain != null) {\n return false;\n }\n if (userName != null ? !userName.equals(material.userName) : material.userName != null) {\n return false;\n }\n return true;\n }", " @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + (url != null ? url.hashCode() : 0);\n result = 31 * result + (userName != null ? userName.hashCode() : 0);\n result = 31 * result + (domain != null ? domain.hashCode() : 0);\n result = 31 * result + (projectPath != null ? projectPath.hashCode() : 0);\n return result;\n }", " @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, true);\n }", " @Override\n protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {\n super.setGoMaterialVariables(environmentVariableContext);\n if (isNotBlank(domain)) {\n setVariableWithName(environmentVariableContext, domain, GO_MATERIAL_DOMAIN);\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials;", "import com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.joda.time.DateTime;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "public class TestingMaterial extends ScmMaterial {\n public static final Date TWO_DAYS_AGO_CHECKIN = new DateTime().minusDays(2).toDate();", " public static final String MOD_TYPE = \"svn\";\n public static final String MOD_REVISION = \"98\";", " public static final String TYPE = \"TestingMaterial\";", " private String url;", " public TestingMaterial() {", " super(TYPE, new GoCipher());", " }", " public TestingMaterial(TestingMaterialConfig config) {\n this();\n this.url = config.getUrl();\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n throw new RuntimeException(\"NOT USED\");\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return multipleModificationList();\n }", " private List<Modification> multipleModificationList() {\n List<Modification> modifications = new ArrayList<>();", " Date today = new Date();\n Date yesterday = new DateTime().minusDays(1).toDate();", " Modification modification1 = new Modification(\"lgao\", \"Fixing the not checked in files\", \"foo@bar.com\", yesterday, \"99\");\n modification1.createModifiedFile(\"build.xml\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification1);", " Modification modification2 = new Modification(\"committer\", \"Added the README file\", \"foo@bar.com\", today, \"100\");\n modification2.createModifiedFile(\"oldbuild.xml\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification2);", " Modification modification3 = new Modification(\"committer <html />\", \"Added the README file with <html />\", \"foo@bar.com\", today, \"101\");\n modification3.createModifiedFile(\"README.txt\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification3);", " return modifications;\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new TestingMaterialInstance(url, \"FLYWEIGHTNAME\");\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n }", " public void setUrl(String url) {\n this.url = url;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url;\n }", " @Override\n public String urlForCommandLine() {\n return url;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(url);\n }", " @Override\n public String getLongDescription() {\n return String.format(\"Url: %s\", url);\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n return null;\n }", " @Override\n protected String getLocation() {\n return getUrl();\n }", " @Override\n public String getTypeForDisplay() {\n return TYPE;\n }", " @Override\n public Class getInstanceType() {\n return TestingMaterialInstance.class;\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n }", " @Override\n public MaterialConfig config() {\n return new TestingMaterialConfig(url);\n }", "}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials;", "import com.thoughtworks.go.config.materials.ScmMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.domain.MaterialInstance;", "", "import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.joda.time.DateTime;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "public class TestingMaterial extends ScmMaterial {\n public static final Date TWO_DAYS_AGO_CHECKIN = new DateTime().minusDays(2).toDate();", " public static final String MOD_TYPE = \"svn\";\n public static final String MOD_REVISION = \"98\";", " public static final String TYPE = \"TestingMaterial\";", " private String url;", " public TestingMaterial() {", " super(TYPE);", " }", " public TestingMaterial(TestingMaterialConfig config) {\n this();\n this.url = config.getUrl();\n }", " public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {\n throw new RuntimeException(\"NOT USED\");\n }", " public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {\n return multipleModificationList();\n }", " private List<Modification> multipleModificationList() {\n List<Modification> modifications = new ArrayList<>();", " Date today = new Date();\n Date yesterday = new DateTime().minusDays(1).toDate();", " Modification modification1 = new Modification(\"lgao\", \"Fixing the not checked in files\", \"foo@bar.com\", yesterday, \"99\");\n modification1.createModifiedFile(\"build.xml\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification1);", " Modification modification2 = new Modification(\"committer\", \"Added the README file\", \"foo@bar.com\", today, \"100\");\n modification2.createModifiedFile(\"oldbuild.xml\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification2);", " Modification modification3 = new Modification(\"committer <html />\", \"Added the README file with <html />\", \"foo@bar.com\", today, \"101\");\n modification3.createModifiedFile(\"README.txt\", \"\\\\build\", ModifiedAction.added);\n modifications.add(modification3);", " return modifications;\n }", " @Override\n public MaterialInstance createMaterialInstance() {\n return new TestingMaterialInstance(url, \"FLYWEIGHTNAME\");\n }", " @Override\n public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {\n }", " public void setUrl(String url) {\n this.url = url;\n }", " @Override\n public boolean isCheckExternals() {\n return false;\n }", " @Override\n public String getUrl() {\n return url;\n }", " @Override\n public String urlForCommandLine() {\n return url;\n }", " @Override\n protected UrlArgument getUrlArgument() {\n return new UrlArgument(url);\n }", " @Override\n public String getLongDescription() {\n return String.format(\"Url: %s\", url);\n }", " public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {\n return null;\n }", " @Override\n protected String getLocation() {\n return getUrl();\n }", " @Override\n public String getTypeForDisplay() {\n return TYPE;\n }", " @Override\n public Class getInstanceType() {\n return TestingMaterialInstance.class;\n }", " @Override\n protected void appendCriteria(Map<String, Object> parameters) {\n }", " @Override\n protected void appendAttributes(Map<String, Object> parameters) {\n }", " @Override\n public MaterialConfig config() {\n return new TestingMaterialConfig(url);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.tfs;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.Material;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.command.UrlArgument;", "public class TfsMaterialInstance extends MaterialInstance {", " private TfsMaterialInstance() {\n super();\n }", " public TfsMaterialInstance(String url, String userName, String domain, String projectPath, final String flyweightName) {\n super(url, userName, null, null, null, null, null, null, flyweightName, null, projectPath, domain, null);\n }", " @Override public Material toOldMaterial(String name, String folder, String password) {", " TfsMaterial tfsMaterial = new TfsMaterial(new GoCipher(), new UrlArgument(url), username, domain, password, projectPath);", " tfsMaterial.setFolder(folder);\n setName(name,tfsMaterial);\n return tfsMaterial;\n }\n}" ]
[ 1, 0, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.tfs;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.Material;", "", "import com.thoughtworks.go.util.command.UrlArgument;", "public class TfsMaterialInstance extends MaterialInstance {", " private TfsMaterialInstance() {\n super();\n }", " public TfsMaterialInstance(String url, String userName, String domain, String projectPath, final String flyweightName) {\n super(url, userName, null, null, null, null, null, null, flyweightName, null, projectPath, domain, null);\n }", " @Override public Material toOldMaterial(String name, String folder, String password) {", " TfsMaterial tfsMaterial = new TfsMaterial(new UrlArgument(url), username, domain, password, projectPath);", " tfsMaterial.setFolder(folder);\n setName(name,tfsMaterial);\n return tfsMaterial;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.helper;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.*;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.config.ConfigurationProperty;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.packagerepository.*;\nimport com.thoughtworks.go.domain.scm.SCM;\nimport com.thoughtworks.go.domain.scm.SCMMother;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.util.command.UrlArgument;", "import java.util.Arrays;\nimport java.util.List;", "public class MaterialsMother {", " public static Materials defaultMaterials() {\n return defaultSvnMaterialsWithUrl(\"http://some/svn/url\");\n }", " public static Materials defaultSvnMaterialsWithUrl(String svnUrl) {\n return new Materials(svnMaterial(svnUrl, \"svnDir\", null, null, false, null));\n }", " public static Materials multipleMaterials() {\n Materials materials = new Materials();\n materials.add(svnMaterial(\"http://svnurl\"));\n materials.add(hgMaterial(\"http://hgurl\", \"hgdir\"));\n materials.add(dependencyMaterial(\"cruise\", \"dev\"));\n return materials;\n }", " public static Materials twoMaterials() {\n Materials materials = new Materials();\n materials.add(svnMaterial(\"http://svnurl\"));\n materials.add(hgMaterial(\"http://hgurl\", \"hgdir\"));\n return materials;\n }", " public static PackageMaterial packageMaterial(){\n PackageMaterial material = new PackageMaterial(\"p-id\");\n material.setId(1);\n PackageRepository repository = PackageRepositoryMother.create(\"repo-id\", \"repo-name\", \"pluginid\", \"version\",\n new Configuration(ConfigurationPropertyMother.create(\"k1\", false, \"repo-v1\"), ConfigurationPropertyMother.create(\"k2\", false, \"repo-v2\")));\n PackageDefinition packageDefinition = PackageDefinitionMother.create(\"p-id\", \"package-name\", new Configuration(ConfigurationPropertyMother.create(\"k3\", false, \"package-v1\")), repository);\n material.setPackageDefinition(packageDefinition);\n repository.getPackages().add(packageDefinition);\n return material;\n }", " public static PackageMaterial packageMaterial(String repoId, String repoName, String pkgId, String pkgName, ConfigurationProperty... properties) {\n return packageMaterial(repoId, repoName, pkgId, pkgName, \"pluginid\", \"version\", Arrays.asList(properties), Arrays.asList(properties));\n }", " public static PackageMaterial packageMaterial(String repoId, String repoName, String pkgId, String pkgName, final String pluginid, final String version, List<ConfigurationProperty> repoProperties,\n List<ConfigurationProperty> packageProperties) {\n PackageRepository repository = PackageRepositoryMother.create(repoId, repoName, pluginid, version, new Configuration(repoProperties));\n PackageDefinition packageDefinition = PackageDefinitionMother.create(pkgId, pkgName, new Configuration(packageProperties), repository);\n repository.getPackages().add(packageDefinition);", " PackageMaterial material = new PackageMaterial(pkgId);\n material.setId(1);\n material.setPackageDefinition(packageDefinition);\n return material;\n }", " public static PluggableSCMMaterial pluggableSCMMaterial() {\n ConfigurationProperty k1 = ConfigurationPropertyMother.create(\"k1\", false, \"v1\");\n ConfigurationProperty k2 = ConfigurationPropertyMother.create(\"k2\", false, \"v2\");\n return pluggableSCMMaterial(\"scm-id\", \"scm-name\", k1, k2);\n }", " public static PluggableSCMMaterial pluggableSCMMaterial(String scmId, String scmName, ConfigurationProperty... properties) {\n return pluggableSCMMaterial(scmId, scmName, \"pluginid\", \"version\", Arrays.asList(properties));\n }", " public static PluggableSCMMaterial pluggableSCMMaterial(String scmId, String scmName, final String pluginid, final String version, List<ConfigurationProperty> properties) {\n PluggableSCMMaterial material = new PluggableSCMMaterial(scmId);\n material.setId(1);\n SCM scmConfig = SCMMother.create(scmId, scmName, pluginid, version, new Configuration(properties));\n material.setSCMConfig(scmConfig);\n return material;\n }", " public static DependencyMaterial dependencyMaterial(String pipelineName, String stageName) {\n return new DependencyMaterial(new CaseInsensitiveString(pipelineName), new CaseInsensitiveString(stageName));\n }", " public static DependencyMaterial dependencyMaterial() {\n return new DependencyMaterial(new CaseInsensitiveString(\"pipeline-name\"), new CaseInsensitiveString(\"stage-name\"));\n }", " public static Materials hgMaterials(String url) {\n return hgMaterials(url, null);\n }", " public static Materials hgMaterials(String url, String folder) {\n return new Materials(hgMaterial(url, folder));\n }", " public static HgMaterial hgMaterial(String url, String folder) {\n final HgMaterial material = new HgMaterial(url, folder);\n material.setAutoUpdate(true);\n return material;\n }", " public static HgMaterial hgMaterial() {\n return new HgMaterial(\"hg-url\", null);\n }", " public static HgMaterial hgMaterial(String url) {\n return hgMaterial(url, null);\n }", " public static Materials gitMaterials(String url) {\n return gitMaterials(url, null, null);\n }", " public static Materials gitMaterials(String url, String branch) {\n return gitMaterials(url, null, branch);\n }", " public static Materials gitMaterials(String url, String submoduleFolder, String branch) {\n return new Materials(gitMaterial(url, submoduleFolder, branch));\n }", " public static GitMaterial gitMaterial(String url) {\n return gitMaterial(url, null, null);\n }", " public static GitMaterial gitMaterial(String url, String submoduleFolder, String branch) {\n GitMaterial gitMaterial = new GitMaterial(url, branch);\n gitMaterial.setSubmoduleFolder(submoduleFolder);\n return gitMaterial;\n }", " public static Materials p4Materials(String view) {\n P4Material material = p4Material(\"localhost:1666\", \"user\", \"password\", view, true);\n return new Materials(material);\n }", " public static P4Material p4Material() {\n return p4Material(\"serverAndPort\", null, null, \"view\", false);\n }", " public static P4Material p4Material(String serverAndPort, String userName, String password, String view, boolean useTickets) {\n final P4Material material = new P4Material(serverAndPort, view, userName);\n material.setAutoUpdate(true);\n material.setPassword(password);\n material.setUseTickets(useTickets);\n return material;\n }", " public static TfsMaterial tfsMaterial(String url) {", " return new TfsMaterial(new GoCipher(), new UrlArgument(url), \"username\", \"domain\", \"password\", \"project-path\");", " }", " public static SvnMaterial svnMaterial(String svnUrl, String folder) {\n return svnMaterial(svnUrl, folder, \"user\", \"pass\", true, \"*.doc\");\n }", " public static SvnMaterial svnMaterial(String svnUrl, String folder, String userName, String password, boolean checkExternals, String filterPattern) {\n SvnMaterial svnMaterial = new SvnMaterial(svnUrl, userName, password, checkExternals, folder);\n if (filterPattern != null)\n svnMaterial.setFilter(new Filter(new IgnoredFiles(filterPattern)));\n return svnMaterial;\n }", " public static SvnMaterial svnMaterial(String svnUrl) {\n return svnMaterial(svnUrl, \"svnDir\");\n }", " public static SvnMaterial svnMaterial() {\n return svnMaterial(\"url\");\n }", " public static Material filteredHgMaterial(String pattern) {\n HgMaterial material = hgMaterial();\n material.setFilter(new Filter(new IgnoredFiles(pattern)));\n return material;\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.helper;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.*;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.config.ConfigurationProperty;\nimport com.thoughtworks.go.domain.materials.Material;\nimport com.thoughtworks.go.domain.packagerepository.*;\nimport com.thoughtworks.go.domain.scm.SCM;\nimport com.thoughtworks.go.domain.scm.SCMMother;", "", "import com.thoughtworks.go.util.command.UrlArgument;", "import java.util.Arrays;\nimport java.util.List;", "public class MaterialsMother {", " public static Materials defaultMaterials() {\n return defaultSvnMaterialsWithUrl(\"http://some/svn/url\");\n }", " public static Materials defaultSvnMaterialsWithUrl(String svnUrl) {\n return new Materials(svnMaterial(svnUrl, \"svnDir\", null, null, false, null));\n }", " public static Materials multipleMaterials() {\n Materials materials = new Materials();\n materials.add(svnMaterial(\"http://svnurl\"));\n materials.add(hgMaterial(\"http://hgurl\", \"hgdir\"));\n materials.add(dependencyMaterial(\"cruise\", \"dev\"));\n return materials;\n }", " public static Materials twoMaterials() {\n Materials materials = new Materials();\n materials.add(svnMaterial(\"http://svnurl\"));\n materials.add(hgMaterial(\"http://hgurl\", \"hgdir\"));\n return materials;\n }", " public static PackageMaterial packageMaterial(){\n PackageMaterial material = new PackageMaterial(\"p-id\");\n material.setId(1);\n PackageRepository repository = PackageRepositoryMother.create(\"repo-id\", \"repo-name\", \"pluginid\", \"version\",\n new Configuration(ConfigurationPropertyMother.create(\"k1\", false, \"repo-v1\"), ConfigurationPropertyMother.create(\"k2\", false, \"repo-v2\")));\n PackageDefinition packageDefinition = PackageDefinitionMother.create(\"p-id\", \"package-name\", new Configuration(ConfigurationPropertyMother.create(\"k3\", false, \"package-v1\")), repository);\n material.setPackageDefinition(packageDefinition);\n repository.getPackages().add(packageDefinition);\n return material;\n }", " public static PackageMaterial packageMaterial(String repoId, String repoName, String pkgId, String pkgName, ConfigurationProperty... properties) {\n return packageMaterial(repoId, repoName, pkgId, pkgName, \"pluginid\", \"version\", Arrays.asList(properties), Arrays.asList(properties));\n }", " public static PackageMaterial packageMaterial(String repoId, String repoName, String pkgId, String pkgName, final String pluginid, final String version, List<ConfigurationProperty> repoProperties,\n List<ConfigurationProperty> packageProperties) {\n PackageRepository repository = PackageRepositoryMother.create(repoId, repoName, pluginid, version, new Configuration(repoProperties));\n PackageDefinition packageDefinition = PackageDefinitionMother.create(pkgId, pkgName, new Configuration(packageProperties), repository);\n repository.getPackages().add(packageDefinition);", " PackageMaterial material = new PackageMaterial(pkgId);\n material.setId(1);\n material.setPackageDefinition(packageDefinition);\n return material;\n }", " public static PluggableSCMMaterial pluggableSCMMaterial() {\n ConfigurationProperty k1 = ConfigurationPropertyMother.create(\"k1\", false, \"v1\");\n ConfigurationProperty k2 = ConfigurationPropertyMother.create(\"k2\", false, \"v2\");\n return pluggableSCMMaterial(\"scm-id\", \"scm-name\", k1, k2);\n }", " public static PluggableSCMMaterial pluggableSCMMaterial(String scmId, String scmName, ConfigurationProperty... properties) {\n return pluggableSCMMaterial(scmId, scmName, \"pluginid\", \"version\", Arrays.asList(properties));\n }", " public static PluggableSCMMaterial pluggableSCMMaterial(String scmId, String scmName, final String pluginid, final String version, List<ConfigurationProperty> properties) {\n PluggableSCMMaterial material = new PluggableSCMMaterial(scmId);\n material.setId(1);\n SCM scmConfig = SCMMother.create(scmId, scmName, pluginid, version, new Configuration(properties));\n material.setSCMConfig(scmConfig);\n return material;\n }", " public static DependencyMaterial dependencyMaterial(String pipelineName, String stageName) {\n return new DependencyMaterial(new CaseInsensitiveString(pipelineName), new CaseInsensitiveString(stageName));\n }", " public static DependencyMaterial dependencyMaterial() {\n return new DependencyMaterial(new CaseInsensitiveString(\"pipeline-name\"), new CaseInsensitiveString(\"stage-name\"));\n }", " public static Materials hgMaterials(String url) {\n return hgMaterials(url, null);\n }", " public static Materials hgMaterials(String url, String folder) {\n return new Materials(hgMaterial(url, folder));\n }", " public static HgMaterial hgMaterial(String url, String folder) {\n final HgMaterial material = new HgMaterial(url, folder);\n material.setAutoUpdate(true);\n return material;\n }", " public static HgMaterial hgMaterial() {\n return new HgMaterial(\"hg-url\", null);\n }", " public static HgMaterial hgMaterial(String url) {\n return hgMaterial(url, null);\n }", " public static Materials gitMaterials(String url) {\n return gitMaterials(url, null, null);\n }", " public static Materials gitMaterials(String url, String branch) {\n return gitMaterials(url, null, branch);\n }", " public static Materials gitMaterials(String url, String submoduleFolder, String branch) {\n return new Materials(gitMaterial(url, submoduleFolder, branch));\n }", " public static GitMaterial gitMaterial(String url) {\n return gitMaterial(url, null, null);\n }", " public static GitMaterial gitMaterial(String url, String submoduleFolder, String branch) {\n GitMaterial gitMaterial = new GitMaterial(url, branch);\n gitMaterial.setSubmoduleFolder(submoduleFolder);\n return gitMaterial;\n }", " public static Materials p4Materials(String view) {\n P4Material material = p4Material(\"localhost:1666\", \"user\", \"password\", view, true);\n return new Materials(material);\n }", " public static P4Material p4Material() {\n return p4Material(\"serverAndPort\", null, null, \"view\", false);\n }", " public static P4Material p4Material(String serverAndPort, String userName, String password, String view, boolean useTickets) {\n final P4Material material = new P4Material(serverAndPort, view, userName);\n material.setAutoUpdate(true);\n material.setPassword(password);\n material.setUseTickets(useTickets);\n return material;\n }", " public static TfsMaterial tfsMaterial(String url) {", " return new TfsMaterial(new UrlArgument(url), \"username\", \"domain\", \"password\", \"project-path\");", " }", " public static SvnMaterial svnMaterial(String svnUrl, String folder) {\n return svnMaterial(svnUrl, folder, \"user\", \"pass\", true, \"*.doc\");\n }", " public static SvnMaterial svnMaterial(String svnUrl, String folder, String userName, String password, boolean checkExternals, String filterPattern) {\n SvnMaterial svnMaterial = new SvnMaterial(svnUrl, userName, password, checkExternals, folder);\n if (filterPattern != null)\n svnMaterial.setFilter(new Filter(new IgnoredFiles(filterPattern)));\n return svnMaterial;\n }", " public static SvnMaterial svnMaterial(String svnUrl) {\n return svnMaterial(svnUrl, \"svnDir\");\n }", " public static SvnMaterial svnMaterial() {\n return svnMaterial(\"url\");\n }", " public static Material filteredHgMaterial(String pattern) {\n HgMaterial material = hgMaterial();\n material.setFilter(new Filter(new IgnoredFiles(pattern)));\n return material;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124